Programs & Examples On #Gradientstop

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

How can I know if a process is running?

You can instantiate a Process instance once for the process you want and keep on tracking the process using that .NET Process object (it will keep on tracking till you call Close on that .NET object explicitly, even if the process it was tracking has died [this is to be able to give you time of process close, aka ExitTime etc.])

Quoting http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx:

When an associated process exits (that is, when it is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called WaitForExit. The Process component can then access the information, which includes the ExitTime, by using the Handle to the exited process.

Because the associated process has exited, the Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system’s information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the ExitTime and Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Start for a Process instance, call Close when the associated process has terminated and you no longer need any administrative information about it. Close frees the memory allocated to the exited process.

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

What is the best way to convert an array to a hash in Ruby

Appending to the answer but using anonymous arrays and annotating:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

Taking that answer apart, starting from the inside:

  • "a,b,c,d" is actually a string.
  • split on commas into an array.
  • zip that together with the following array.
  • [1,2,3,4] is an actual array.

The intermediate result is:

[[a,1],[b,2],[c,3],[d,4]]

flatten then transforms that to:

["a",1,"b",2,"c",3,"d",4]

and then:

*["a",1,"b",2,"c",3,"d",4] unrolls that into "a",1,"b",2,"c",3,"d",4

which we can use as the arguments to the Hash[] method:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

which yields:

{"a"=>1, "b"=>2, "c"=>3, "d"=>4}

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

sql insert into table with select case values

If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.

If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), '  ', ' ')
    , Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
    , City
    , Zip
FROM tblImport (NOLOCK);

Otherwise, this will work:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), '  ', ' ')
    , Address = ISNULL(Address1, '') + CASE
        WHEN Address2 IS NOT NULL THEN ', ' + Address2
        ELSE '' END
    , City
    , Zip
FROM tblImport (NOLOCK);

__init__() missing 1 required positional argument

You need to pass some data into it. An empty dictionary, for example.

if __name__ == '__main__': DHT('a').showData()

However, in your example a parameter is not even needed. You can declare it by just:

def __init__(self):

Maybe you mean to set it from the data?

class DHT:
    def __init__(self, data):
        self.data['one'] = data['one']
        self.data['two'] = data['two']
        self.data['three'] = data['three']
    def showData(self):
        print(self.data)

if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()

showData will print the data you just entered.

How to display Toast in Android?

To toast in Android

Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_SHORT).show();

or

Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_LONG).show();

( LENGTH_SHORT and LENGTH_LONG are acting as boolean flags - which means you cant sent toast timer to miliseconds, but you need to use either of those 2 options )

Maven Jacoco Configuration - Exclude classes/packages from report not working

Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs

<configuration>
    <excludes>
        <exclude>**/*Config.*</exclude>
        <exclude>**/*Dev.*</exclude>
    </excludes>
</configuration>

The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax

*   Match zero or more characters
**  Match zero or more directories
?   Match a single character

You may also exclude a package and all of its children/subpackages this way:

<exclude>some/package/**/*</exclude>

This will exclude every class in some.package, as well as any children. For example, some.package.child wouldn't be included in the reports either.

I have tested and my report goal reports on a reduced number of classes using the above.

If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings

Settings > General Settings > Exclusions > Code Coverage

Sonar Docs explains it a bit more

Running your command above

mvn clean verify

Will show the classes have been excluded

No exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes

With exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes

Hope this helps

SQL - Create view from multiple tables

Thanks for the help. This is what I ended up doing in order to make it work.

CREATE VIEW V AS
    SELECT *
    FROM ((POP NATURAL FULL OUTER JOIN FOOD)
    NATURAL FULL OUTER JOIN INCOME);

How to preview git-pull without doing fetch?

I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.

This goes in the ~/.gitconfig file:

[alias]
        diffpull=!git fetch && git diff HEAD..@{u}

It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull.

Moment.js - how do I get the number of years since a date, not rounded up?

Using moment.js is as easy as:

var years = moment().diff('1981-01-01', 'years');
var days = moment().diff('1981-01-01', 'days');

For additional reference, you can read moment.js official documentation.

Simple Random Samples from a Sql database

I think the fastest solution is

select * from table where rand() <= .3

Here is why I think this should do the job.

  • It will create a random number for each row. The number is between 0 and 1
  • It evaluates whether to display that row if the number generated is between 0 and .3 (30%).

This assumes that rand() is generating numbers in a uniform distribution. It is the quickest way to do this.

I saw that someone had recommended that solution and they got shot down without proof.. here is what I would say to that -

  • This is O(n) but no sorting is required so it is faster than the O(n lg n)
  • mysql is very capable of generating random numbers for each row. Try this -

    select rand() from INFORMATION_SCHEMA.TABLES limit 10;

Since the database in question is mySQL, this is the right solution.

How to get the position of a character in Python?

There are two string methods for this, find() and index(). The difference between the two is what happens when the search string isn't found. find() returns -1 and index() raises ValueError.

Using find()

>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1

Using index()

>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

From the Python manual

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

And:

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Which SchemaType in Mongoose is Best for Timestamp?

var ItemSchema = new Schema({
    name : { type: String }
});

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps

Docs: https://mongoosejs.com/docs/guide.html#timestamps

Char array in a struct - incompatible assignment?

You can use strcpy to populate it. You can also initialize it from another struct.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct name {
    char first[20];
    char last[20];
};

int main() {
    struct name sara;
    struct name other;

    strcpy(sara.first,"Sara");
    strcpy(sara.last, "Black");

    other = sara;

    printf("struct: %s\t%s\n", sara.first, sara.last);
    printf("other struct: %s\t%s\n", other.first, other.last);

}

How to put a text beside the image?

make the image float: left; and the text float: right;

Take a look at this fiddle I used a picture online but you can just swap it out for your picture.

How to use a Java8 lambda to sort a stream in reverse order?

Use

Comparator<File> comparator = Comparator.comparing(File::lastModified); 
Collections.sort(list, comparator.reversed());

Then

.forEach(item -> item.delete());

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

implementing merge sort in C++

I have completed @DietmarKühl s way of merge sort. Hope it helps all.

template <typename T>
void merge(vector<T>& array, vector<T>& array1, vector<T>& array2) {
    array.clear();

    int i, j, k;
    for( i = 0, j = 0, k = 0; i < array1.size() && j < array2.size(); k++){
        if(array1.at(i) <= array2.at(j)){
            array.push_back(array1.at(i));
            i++;
        }else if(array1.at(i) > array2.at(j)){
            array.push_back(array2.at(j));
            j++;
        }
        k++;
    }

    while(i < array1.size()){
        array.push_back(array1.at(i));
        i++;
    }

    while(j < array2.size()){
        array.push_back(array2.at(j));
        j++;
    }
}

template <typename T>
void merge_sort(std::vector<T>& array) {
    if (1 < array.size()) {
        std::vector<T> array1(array.begin(), array.begin() + array.size() / 2);
        merge_sort(array1);
        std::vector<T> array2(array.begin() + array.size() / 2, array.end());
        merge_sort(array2);
        merge(array, array1, array2);
    }
}

How to write files to assets folder or raw folder in android?

You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.

Command CompileSwift failed with a nonzero exit code in Xcode 10

I attempted

  • Closing & Reopening Xcode
  • Cleaning Build Folder
  • Running pod install --repo-update

and all of these still did not fix the problem.

Restarting the Mac did the trick!

Convert string date to timestamp in Python

You can refer this following link for using strptime function from datetime.datetime, to convert date from any format along with time zone.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Django gives Bad Request (400) when DEBUG = False

I had to stop the apache server first.

(f.e. sudo systemctl stop httpd.service / sudo systemctl disable httpd.service).

That solved my problem besides editing the 'settings.py' file

to ALLOWED_HOSTS = ['se.rv.er.ip', 'www.example.com']

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

What is this date format? 2011-08-12T20:17:46.384Z

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

Can an abstract class have a constructor?

In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:

  • A means by which code can request the creation of an instance of Fnord

  • A means by which an instance of a type derived from Fnord which is under construction can request that all base-class features be initialized.

While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.

How can I list all foreign keys referencing a given table in SQL Server?

 SELECT OBJECT_NAME(fk.parent_object_id) as ReferencingTable, 
        OBJECT_NAME(fk.constraint_object_id) as [FKContraint]
  FROM sys.foreign_key_columns as fk
 WHERE fk.referenced_object_id = OBJECT_ID('ReferencedTable', 'U')

This only shows the relationship if the are foreign key constraints. My database apparently predates the FK constraint.Some table use triggers to enforce referential integrity, and sometimes there's nothing but a similarly named column to indicate the relationship (and no referential integrity at all).

Fortunately, we do have a consistent naming scene so I am able to find referencing tables and views like this:

SELECT OBJECT_NAME(object_id) from sys.columns where name like 'client_id'

I used this select as the basis for generating a script the does what I need to do on the related tables.

converting multiple columns from character to numeric format in r

You could use convert from the hablar package:

library(dplyr)
library(hablar)

# Sample df (stolen from the solution by Luca Braglia)
df <- tibble("a" = as.character(0:5),
                 "b" = paste(0:5, ".1", sep = ""),
                 "c" = letters[1:6])

# insert variable names in num()
df %>% convert(num(a, b))

Which gives you:

# A tibble: 6 x 3
      a     b c    
  <dbl> <dbl> <chr>
1    0. 0.100 a    
2    1. 1.10  b    
3    2. 2.10  c    
4    3. 3.10  d    
5    4. 4.10  e    
6    5. 5.10  f   

Or if you are lazy, let retype() from hablar guess the right data type:

df %>% retype()

which gives you:

# A tibble: 6 x 3
      a     b c    
  <int> <dbl> <chr>
1     0 0.100 a    
2     1 1.10  b    
3     2 2.10  c    
4     3 3.10  d    
5     4 4.10  e    
6     5 5.10  f   

How do malloc() and free() work?

One implementation of malloc/free does the following:

  1. Get a block of memory from the OS through sbrk() (Unix call).
  2. Create a header and a footer around that block of memory with some information such as size, permissions, and where the next and previous block are.
  3. When a call to malloc comes in, a list is referenced which points to blocks of the appropriate size.
  4. This block is then returned and headers and footers are updated accordingly.

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

How do I enable --enable-soap in php on linux?

In case that you have Ubuntu in your machine, the following steps will help you:

  1. Check first in your php testing file if you have soap (client / server)or not by using phpinfo(); and check results in the browser. In case that you have it, it will seems like the following image ( If not go to step 2 ):

enter image description here

  1. Open your terminal and paste: sudo apt-get install php-soap.

  2. Restart your apache2 server in terminal : service apache2 restart.

  3. To check use your php test file again to be seems like mine in step 1.

How do I clone a Django model instance object and save it to the database?

Use the below code :

from django.forms import model_to_dict

instance = Some.objects.get(slug='something')

kwargs = model_to_dict(instance, exclude=['id'])
new_instance = Some.objects.create(**kwargs)

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

Ansible - Use default if a variable is not defined

The question is quite old, but what about:

- hosts: 'localhost'
  tasks:
    - debug:
        msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"

It looks less cumbersome to me...

Why doesn't [01-12] range work as expected?

As polygenelubricants says yours would look for 0|1-1|2 rather than what you wish for, due to the fact that character classes (things in []) match characters rather than strings.

android - How to get view from context?

Why don't you just use a singleton?

import android.content.Context;


public class ClassicSingleton {
    private Context c=null;
    private static ClassicSingleton instance = null;
    protected ClassicSingleton()
    {
       // Exists only to defeat instantiation.
    }
    public void setContext(Context ctx)
    {
    c=ctx;
    }
    public Context getContext()
    {
       return c;
    }
    public static ClassicSingleton getInstance()
    {
        if(instance == null) {
            instance = new ClassicSingleton();
        }
        return instance;
    }
}

Then in the activity class:

 private ClassicSingleton cs = ClassicSingleton.getInstance();

And in the non activity class:

ClassicSingleton cs= ClassicSingleton.getInstance();
        Context c=cs.getContext();
        ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);

Bootstrap carousel multiple frames at once

You can add multiple li in ol tag that has attribute as class with value "carousel-indicators" and with data-slide-to has sequential values like 0 to 6 or 0 to 9.

than you just need to copy and paste the div which has attribute as class with value "item".

This works for me.

<div data-ride="carousel" class="carousel slide" id="myCarousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li class="" data-slide-to="0" data-target="#myCarousel"></li>
        <li data-slide-to="1" data-target="#myCarousel" class=""></li>
        <li data-slide-to="2" data-target="#myCarousel" class="active"></li>
        <li data-slide-to="3" data-target="#myCarousel" class=""></li>
        <li data-slide-to="4" data-target="#myCarousel" class=""></li>
        <li data-slide-to="5" data-target="#myCarousel" class=""></li>
        <li data-slide-to="6" data-target="#myCarousel" class=""></li>
    </ol>
    <div role="listbox" class="carousel-inner">
        <div class="item active">
            <img alt="First slide" src="images/carousel/11.jpg"
                class="first-slide">
        </div>
        <div class="item">
            <img alt="Second slide" src="images/carousel/22.jpg"
                class="second-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/33.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/44.jpeg"
                class="fourth-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/55.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/66.jpg"
                class="third-slide">
        </div>
        <div class="item">
            <img alt="Third slide" src="images/carousel/77.jpg"
                class="third-slide">
        </div>
    </div>
    <a data-slide="prev" role="button" href="#myCarousel"
        class="left carousel-control"> <span aria-hidden="true"
        class="glyphicon glyphicon-chevron-left"></span> <span
        class="sr-only">Previous</span>
    </a> <a data-slide="next" role="button" href="#myCarousel"
        class="right carousel-control"> <span aria-hidden="true"
        class="glyphicon glyphicon-chevron-right"></span> <span
        class="sr-only">Next</span>
    </a>
</div>

What is difference between png8 and png24

You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

  • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
  • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
  • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
  • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
  • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

How to get current route in react-router 2.0.0-rc5

In App.js add the below code and try

window.location.pathname

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

If you have to use the older client, here is my experience.

We are running a 32bit server so the development machines run the 32bit client. We run the 11.1 install, 11.2 gets the error. Once you have installed the 11.2 version you have to manually delete the files Oracle.Web.dll and System.Data.OracleClient.dll from the %windir%\Microsoft.NET\Framework\v2.0.50727, reinstall 11.1, then register the dlls with gacutil.exe.

This fixed the issue with my systems.

For vs. while in C programming?

They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

How do I exit the Vim editor?

After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit.

You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!).

Import Maven dependencies in IntelliJ IDEA

  1. From maven tab click + and choose pom.xml
  2. From maven tab click download sources and documentation
  3. On project structure(where you can view project files/directories) right click the project you're trying to build and choose Build Module Project Name.
  4. From tab Run- Edit Configurations with + add Application and fill the below fields: i. Main Class- Manually choose from Project tab select the main class ii. Use classpath of module - choose the application name iii. Shorten command line - classpath file
  5. Now simply run the app.

estimating of testing effort as a percentage of development time

When you speak of tests, you could mean waterfall or agile test development. In an agile environment, developers should spend 50% of their time developing and maintaining tests.

But that 50% extra will save you time when the re-factoring and manual verification time comes.

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

MySQL: ALTER TABLE if column not exists

Add field if not exist:

CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');

addFieldIfNotExists code:

DELIMITER $$

DROP PROCEDURE IF EXISTS addFieldIfNotExists 
$$

DROP FUNCTION IF EXISTS isFieldExisting 
$$

CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100)) 
RETURNS INT
RETURN (
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.columns 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = table_name_IN 
    AND COLUMN_NAME = field_name_IN
)
$$

CREATE PROCEDURE addFieldIfNotExists (
    IN table_name_IN VARCHAR(100)
    , IN field_name_IN VARCHAR(100)
    , IN field_definition_IN VARCHAR(100)
)
BEGIN

    SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
    IF (@isFieldThere = 0) THEN

        SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
        SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);

        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END IF;

END;
$$

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

How do I change the android actionbar title and icon

The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().

To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.

Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.

jQuery deferreds and promises - .then() vs .done()

then() always means it will be called in whatever case. But the parameters passing are different in different jQuery versions.

Prior to jQuery 1.8, then() equals done().fail(). And all of the callback functions share same parameters.

But as of jQuery 1.8, then() returns a new promise, and if it has return a value, it will be passed into the next callback function.

Let's see the following example:

var defer = jQuery.Deferred();

defer.done(function(a, b){
            return a + b;
}).done(function( result ) {
            console.log("result = " + result);
}).then(function( a, b ) {
            return a + b;
}).done(function( result ) {
            console.log("result = " + result);
}).then(function( a, b ) {
            return a + b;
}).done(function( result ) {
            console.log("result = " + result);
});

defer.resolve( 3, 4 );

Prior to jQuery 1.8, the answer should be

result = 3
result = 3
result = 3

All result takes 3. And then() function always passes the same deferred object to the next function.

But as of jQuery 1.8, the result should be:

result = 3
result = 7
result = NaN

Because the first then() function returns a new promise, and the value 7 (and this is the only parameter that will passed on)is passed to the next done(), so the second done() write result = 7. The second then() takes 7 as the value of a and takes undefined as the value of b, so the second then() returns a new promise with the parameter NaN, and the last done() prints NaN as its result.

"NOT IN" clause in LINQ to Entities

I created it in a more similar way to the SQL, I think it is easier to understand

var list = (from a in listA.AsEnumerable()
            join b in listB.AsEnumerable() on a.id equals b.id into ab
            from c in ab.DefaultIfEmpty()
            where c != null
            select new { id = c.id, name = c.nome }).ToList();

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

How to find list of possible words from a letter matrix [Boggle Solver]

I'd have to give more thought to a complete solution, but as a handy optimisation, I wonder whether it might be worth pre-computing a table of frequencies of digrams and trigrams (2- and 3-letter combinations) based on all the words from your dictionary, and use this to prioritise your search. I'd go with the starting letters of words. So if your dictionary contained the words "India", "Water", "Extreme", and "Extraordinary", then your pre-computed table might be:

'IN': 1
'WA': 1
'EX': 2

Then search for these digrams in the order of commonality (first EX, then WA/IN)

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For webpack 1 or 2 with Bootstrap 4 you need

new webpack.ProvidePlugin({
   $: 'jquery',
   jQuery: 'jquery',
   Tether: 'tether'
})

How to get the current location latitude and longitude in android

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

sendUserActionEvent() is null

This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project

List of macOS text editors and code editors

If you ever plan on making a serious effort at learning Emacs, immediately forget about Aquamacs. It tries to twist and bend Emacs into something it's not (a super-native OS X app). That might sound well and all, but once you realize that it completely breaks nearly every standard keybinding and behavior of Emacs, you begin to wonder why you aren't just using TextEdit or TextMate.

Carbon Emacs is a good Emacs application for OS X. It is as close as you'll get to GNU Emacs without compiling for yourself. It fits in well enough with the operating system, but at the same time, is the wonderful Emacs we all know and love. Currently it requires Leopard with the latest release, but most people have upgraded by now anyway. You can fetch it here.

Alternatively, if you want to use Vim on OS X, I've heard good things about MacVim.

Beyond those, there are the obvious TextEdit, TextMate, etc line of editors. They work for some people, but most "advanced" users I know (myself included) hate touching them with anything shorter than a 15ft pole.

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

MS-DOS Batch file pause with enter key

The only valid answer would be the pause command.

Though this does not wait specifically for the 'ENTER' key, it waits for any key that is pressed.

And just in case you want it convenient for the user, pause is the best option.

how to convert current date to YYYY-MM-DD format with angular 2

Here is a very nice and compact way to do this, you can also change this function as your case needs:

result: 03.11.2017

//get date now function
    getNowDate() {
    //return string
    var returnDate = "";
    //get datetime now
    var today = new Date();
    //split
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //because January is 0! 
    var yyyy = today.getFullYear();
    //Interpolation date
    if (dd < 10) {
        returnDate += `0${dd}.`;
    } else {
        returnDate += `${dd}.`;
    }

    if (mm < 10) {
        returnDate += `0${mm}.`;
    } else {
        returnDate += `${mm}.`;
    }
    returnDate += yyyy;
    return returnDate;
}

What is the difference between a URI, a URL and a URN?

After reading through the posts, I find some very relevant comments. In short, the confusion between the URL and URI definitions is based in part on which definition depends on which and also informal use of the word URI in software development.

By definition URL is a subset of URI [RFC2396]. URI contain URN and URL. Both URI and URL each have their own specific syntax that confers upon them the status of being either URI or URL. URN are for uniquely identifying a resource while URL are for locating a resource. Note that a resource can have more than one URL but only a single URN.[RFC2611]

As web developers and programmers we will almost always be concerned with URL and therefore URI. Now a URL is specifically defined to have all the parts scheme:scheme-specific-part, like for example https://stackoverflow.com/questions. This is a URL and it is also a URI. Now consider a relative link embedded in the page such as ../index.html. This is no longer a URL by definition. It is still what is referred to as a "URI-reference" [RFC2396].

I believe that when the word URI is used to refer to relative paths, "URI-reference" is actually what is being thought of. So informally, software systems use URI to refer to relative pathing and URL for the absolute address. So in this sense, a relative path is no longer a URL but still URI.

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

SQL Server Operating system error 5: "5(Access is denied.)"

For me it was solved in the following way with SQL Server Management studio -Log in as admin (I logged in as windows authentication) -Attach the mdf file (right click Database | attach | Add ) -Log out as admin -Log in as normal user

mkdir's "-p" option

Note that -p is an argument to the mkdir command specifically, not the whole of Unix. Every command can have whatever arguments it needs.

In this case it means "parents", meaning mkdir will create a directory and any parents that don't already exist.

Is there a way to add/remove several classes in one single instruction with classList?

Another polyfill for element.classList is here. I found it via MDN.

I include that script and use element.classList.add("first","second","third") as it's intended.

Save text file UTF-8 encoded with VBA

This writes a Byte Order Mark at the start of the file, which is unnecessary in a UTF-8 file and some applications (in my case, SAP) don't like it. Solution here: Can I export excel data with UTF-8 without BOM?

Make a div into a link

Just have the link in the block and enhance it with jquery. It degrades 100% gracefully for anyone without javascript. Doing this with html isn't really the best solution imho. For example:

<div id="div_link">
<h2><a href="mylink.htm">The Link and Headline</a></h2>
<p>Some more stuff and maybe another <a href="mylink.htm">link</a>.</p>
</div>

Then use jquery to make the block clickable (via web designer wall):

$(document).ready(function(){

    $("#div_link").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

});

Then all you have to do is add cursor styles to the div

    #div_link:hover {cursor: pointer;}

For bonus points only apply these styles if javascript is enabled by adding a 'js_enabled' class to the div, or the body, or whatever.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

What does the ELIFECYCLE Node.js error mean?

I had this issue when I was running two projects that had the same set up and I already had one running. This meant that the other project couldn't use that port number. As soon as I stopped the other project running I had no issues.

Permutation of array

If you're using C++, you can use std::next_permutation from the <algorithm> header file:

int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

Error while trying to run project: Unable to start program. Cannot find the file specified

Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.

Setting default value in select drop-down using Angularjs

we should use name value pair binding values into dropdown.see the code for more details

_x000D_
_x000D_
function myCtrl($scope) {_x000D_
     $scope.statusTaskList = [_x000D_
        { name: 'Open', value: '1' },_x000D_
        { name: 'In Progress', value: '2' },_x000D_
        { name: 'Complete', value: '3' },_x000D_
        { name: 'Deleted', value: '4' },_x000D_
    ];_x000D_
    $scope.atcStatusTasks = $scope.statusTaskList[0]; // 0 -> Open _x000D_
}
_x000D_
<select ng-model="atcStatusTasks" ng-options="s.name for s in statusTaskList"></select>
_x000D_
_x000D_
_x000D_

Manually type in a value in a "Select" / Drop-down HTML list?

It can be done now with HTML5

See this post here HTML select form with option to enter custom value

<input type="text" list="cars" />
<datalist id="cars">
  <option>Volvo</option>
  <option>Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</datalist>

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

How to add New Column with Value to the Existing DataTable?

//Data Table

 protected DataTable tblDynamic
        {
            get
            {
                return (DataTable)ViewState["tblDynamic"];
            }
            set
            {
                ViewState["tblDynamic"] = value;
            }
        }
//DynamicReport_GetUserType() function for getting data from DB


System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];

//Add Column as "TypeName"

                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));

//fill column data against ds.Tables[13]


                for (int i = 0; i < tblDynamic.Rows.Count; i++)
                {

                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Dog;
                    }
                }

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Jenkins/Hudson - accessing the current build number?

BUILD_NUMBER is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.

See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.

Windows Forms - Enter keypress activates submit button?

Simply use

this.Form.DefaultButton = MyButton.UniqueID;  

**Put your button id in place of 'MyButton'.

Differences between Lodash and Underscore.js

I just found one difference that ended up being important for me. The non-Underscore.js-compatible version of Lodash's _.extend() does not copy over class-level-defined properties or methods.

I've created a Jasmine test in CoffeeScript that demonstrates this:

https://gist.github.com/softcraft-development/1c3964402b099893bd61

Fortunately, lodash.underscore.js preserves Underscore.js's behaviour of copying everything, which for my situation was the desired behaviour.

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

How to edit a text file in my terminal

Try this command:

sudo gedit helloWorld.txt

it, will open up a text editor to edit your file.

OR

sudo nano helloWorld.txt

Here, you can edit your file in the terminal window.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

Here is a modified JSBin with a working sample:

http://jsbin.com/sezamuja/1/edit

Here is what I did with filters in the input:

<input ng-model="(results.subjects | filter:{grade:'C'})[0].title">

Java: getMinutes and getHours

I would recommend looking ad joda time. http://www.joda.org/joda-time/

I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome. Plus, it plays nice with existing code, to some extent.

Check to see if cURL is installed locally?

Assuming you want curl installed: just execute the install command and see what happens.

$ sudo yum install curl

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.cat.pdx.edu
 * epel: mirrors.kernel.org
 * extras: mirrors.cat.pdx.edu
 * remi-php72: repo1.sea.innoscale.net
 * remi-safe: repo1.sea.innoscale.net
 * updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do

.war vs .ear file

To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files

WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.

EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app

set background color: Android

Color.parseColor("#rrggbb")

instead of #rrggbb you should be using hex values 0 to F for rr, gg and bb:

e.g. Color.parseColor("#000000") or Color.parseColor("#FFFFFF")

Source

From documentation:

public static int parseColor (String colorString):

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'

So I believe that if you are using #rrggbb you are getting IllegalArgumentException in your logcat

Source

Alternative:

Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);

Source

Validate Dynamically Added Input fields

jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.

$(document).find('#add_patient_form').validate({
          ignore: [],
          rules:{
            'email[]':
            {
              required:true,
            },               
          },
          messages:{
            'email[]':
            {
              'required':'Required'
            },            
          },    
        });

Is there any way to set environment variables in Visual Studio Code?

As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "ddtBatch",
      "request": "launch",
      "mainClass": "com.something.MyApplication",
      "projectName": "MyProject",
      "args": "Hello",
      "vmArgs": "-Dspring.config.location=./application.properties"
    }
  ]
}

Java time-based map/cache with expiring keys

Google collections (guava) has the MapMaker in which you can set time limit(for expiration) and you can use soft or weak reference as you choose using a factory method to create instances of your choice.

How to convert image to byte array

If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();

    public static byte[] SerializeImage() {
        MemoryStream m;
        string PicPath = pathToImage";

        byte[] imageBytes;
        using (Image image = Image.FromFile(PicPath)) {
            
            using ( m = new MemoryStream()) {

                image.Save(m, image.RawFormat);
                imageBytes = new byte[m.Length];
               //Very Important    
               imageBytes = m.ToArray();
                
            }//end using
        }//end using

        return imageBytes;
    }//SerializeImage

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

In simple words

$.ajax("info.txt").done(function(data) {
  alert(data);
}).fail(function(data){
  alert("Try again champ!");
});

if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

JS: iterating over result of getElementsByClassName using Array.forEach

This is the safer way:

var elements = document.getElementsByClassName("myclass");
for (var i = 0; i < elements.length; i++) myFunction(elements[i]);

Upload artifacts to Nexus, without Maven

You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.

Here is the command:

version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus

curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz

Using Cygwin to Compile a C program; Execution error

Compiling your C program using Cygwin

We will be using the gcc compiler on Cygwin to compile programs.

1) Launch Cygwin

2) Change to the directory you created for this class by typing

cd c:/windows/desktop

3) Compile the program by typing

gcc myProgram.c -o myProgram

the command gcc invokes the gcc compiler to compile your C program.

Difference between app.use and app.get in express.js

There are 3 main differences I have found till now. The 3rd one is not so obvious and you may find it interesting. The differences are the same for the express router. That means router.use() and router.get() or other post, put, all, etc methods has also same difference.

1

  • app.use(path, callback) will respond to any HTTP request.
  • app.get(path, callback) will only respond to GET HTTP request. In the same way, post, put, etc will respond to their corresponding request. app.all() responds to any HTTP request so app.use() and app.all() are the same in this part.

2

  • app.use(path, callback) will match the prefix of the request path and responds if any prefix of the request path matches the path parameter. Such as if the path parameter is "/", then it will match "/", "/about", "/users/123" etc.
  • app.get(path, callback) Here get will match the whole path. Same for other HTTP requests and app.all(). Such as, if the path parameter is "/", then it will only match "/".

3

next('route') doesn't work on the middleware/callback functions of app.use(). It works only on app.get(), app.all() and other similar function of other HTTP requests.

According to express documentation:

next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

From here we will use the keyword METHOD instead of get, post, all, etc.
But what is next('route')?!

Let's see.

next('route')

we see, app.use() or app.METHOD() can take several callback/middleware functions.

From the express documentation:

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

So we see each middleware functions have to either call the next middleware function or end the response. And this is same for app.use() and app.METHOD().

But sometimes in some conditions, you may want to skip all the next callback functions for the current route but also don't want to end the response right now. Because maybe there are other routes which should be matched. So to skip all the callback functions of the current route without ending the response, you can run next('route'). It will skip all the callback functions of the current route and search to match the next routes.

For Example (From express documentation):

app.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next route
  if (req.params.id === '0') next('route')
  // otherwise pass the control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // send a regular response
  res.send('regular')
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function (req, res, next) {
  res.send('special')
})

See, here in a certain condition(req.params.id === '0') we want to skip the next callback function but also don't want to end the response because there is another route of the same path parameter which will be matched and that route will send a special response. (Yeah, it is valid to use the same path parameter for the same METHOD several times. In such cases, all the routes will be matched until the response ends). So in such cases, we run the next('route') and all the callback function of the current route is skipped. Here if the condition is not met then we call the next callback function.

This next('route') behavior is only possible in the app.METHOD() functions.

Recalling from express documentation:

next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

Since skipping all callback functions of the current route is not possible in app.use(), we should be careful here. We should only use the middleware functions in app.use() which need not be skipped in any condition. Because we either have to end the response or traverse all the callback functions from beginning to end, we can not skip them at all.

You may visit here for more information

"Instantiating" a List in Java?

Use List<Integer> list = new ArrayList<Integer>();

How to change font-color for disabled input?

It is the solution that I found for this problem:

//If IE

inputElement.writeAttribute("unselectable", "on");

//Other browsers

inputElement.writeAttribute("disabled", "disabled");

By using this trick, you can add style sheet to your input element that works in IE and other browsers on your not-editable input box.

Why "no projects found to import"?

After a long time finally i found that! Here my Way: File -> New Project -> Android Project From Existing Code -> Browse to your project root directory finish!

SQL Server: Invalid Column Name

Whenever this happens to me, I press Ctrl+Shift+R which refreshes intellisense, close the query window (save if necessary), then start a new session which usually works quite well.

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

How to hide scrollbar in Firefox?

Try using this:

overflow-y: -moz-hidden-unscrollable;

Get all rows from SQLite

Update queueAll() method as below:

public Cursor queueAll() {

     String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
     Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

     return cursor;
}

Update readFileFromSQLite() method as below:

public ArrayList<String> readFileFromSQLite() {

    fileName = new ArrayList<String>();

    fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
    fileSQLiteAdapter.openToRead();

    cursor = fileSQLiteAdapter.queueAll();

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do 
            {
                String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
                fileName.add(name);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    fileSQLiteAdapter.close();

    return fileName;
}

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

How to retrieve checkboxes values in jQuery

Anyway, you probably need something like this:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

Note that in your example code you should put the checkboxes in a form.

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

What is the difference between UNION and UNION ALL?

In ORACLE: UNION does not support BLOB (or CLOB) column types, UNION ALL does.

How to pass multiple parameters in json format to a web service using jquery?

i have same issue and resolved by

 data: "Id1=" + id1 + "&Id2=" + id2

How to find out the server IP address (using JavaScript) that the browser is connected to?

I believe John's answer is correct. For instance, I'm using my laptop through a wifi service run by a conference centre -- I'm pretty sure that there is no way for javascript running within my browser to discover the IP address being used by the service provider. On the other hand, it may be possible to address a suitable external resource from javascript. You can write your own if your own by making an ajax call to a server which can take the IP address from the HTTP headers and return it, or try googling "find my ip". The cleanest solution is probably to capture the information before the page is served and insert it in the html returned to the user. See How to get a viewer's IP address with python? for info on how to capture the information if you are serving the page with python.

How do I find out if a column exists in a VB.Net DataRow

You can use DataSet.Tables(0).Columns.Contains(name) to check whether the DataTable contains a column with a particular name.

undefined reference to `WinMain@16'

Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.

--Had similar issue when building C projects

JTable - Selected Row click event

I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.

To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

How do you log content of a JSON object in Node.js?

console.log(obj);

Run: node app.js > output.txt

Android Studio doesn't recognize my device

Although my computer could recognise my phone, I had to install the official drivers from the Samsung developer site to get adb/Android Studio to recognise it:

Samsung Android USB Driver for Windows

Can't find bundle for base name /Bundle, locale en_US

I had the same problemo, and balus solution fixed it.

For the record:

WEB-INF\faces-config is

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <message-bundle>
            Message
        </message-bundle>
    </application>
</faces-config>

And had Message.properties under WebContent\Resources (after mkyong's tutorial)

the pesky exception appeared even when i renamed the bundle to "Message_en_us" and "Message_en". Moving it to src\ worked.

Should someone post the missing piece to make bundles work under resources,it would be a beautiful thing.

How to remove old Docker containers

Update: As of Docker version 1.13 (released January 2017), you can issue the following command to clean up stopped containers, unused volumes, dangling images and unused networks:

docker system prune

If you want to insure that you're only deleting containers which have an exited status, use this:

docker ps -aq -f status=exited | xargs docker rm

Similarly, if you're cleaning up docker stuff, you can get rid of untagged, unnamed images in this way:

docker images -q --no-trunc -f dangling=true | xargs docker rmi

Get bytes from std::string in C++

From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.

It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:

length = str.copy( buffer, str.size() );

:: (double colon) operator in Java 8

:: is called Method Reference. It is basically a reference to a single method. I.e. it refers to an existing method by name.

Short Explanation:
Below is an example of a reference to a static method:

class Hey {
     public static double square(double num){
        return Math.pow(num, 2);
    }
}

Function<Double, Double> square = Hey::square;
double ans = square.apply(23d);

square can be passed around just like object references and triggered when needed. In fact, it can be just as easily used as a reference to "normal" methods of objects as static ones. For example:

class Hey {
    public double square(double num) {
        return Math.pow(num, 2);
    }
}

Hey hey = new Hey();
Function<Double, Double> square = hey::square;
double ans = square.apply(23d);

Function above is a functional interface. To fully understand ::, it is important to understand functional interfaces as well. Plainly, a functional interface is an interface with just one abstract method.

Examples of functional interfaces include Runnable, Callable, and ActionListener.

Function above is a functional interface with just one method: apply. It takes one argument and produces a result.


The reason why ::s are awesome is that:

Method references are expressions which have the same treatment as lambda expressions (...), but instead of providing a method body, they refer an existing method by name.

E.g. instead of writing the lambda body

Function<Double, Double> square = (Double x) -> x * x;

You can simply do

Function<Double, Double> square = Hey::square;

At runtime, these two square methods behave exactly the same as each other. The bytecode may or may not be the same (though, for the above case, the same bytecode is generated; compile the above and check with javap -c).

The only major criterion to satisfy is: the method you provide should have a similar signature to the method of the functional interface you use as object reference.

The below is illegal:

Supplier<Boolean> p = Hey::square; // illegal

square expects an argument and returns a double. The get method in Supplier returns a value but does not take an argument. Thus, this results in an error.

A method reference refers to the method of a functional interface. (As mentioned, functional interfaces can have only one method each).

Some more examples: the accept method in Consumer takes an input but doesn't return anything.

Consumer<Integer> b1 = System::exit;   // void exit(int status)
Consumer<String[]> b2 = Arrays::sort;  // void sort(Object[] a)
Consumer<String> b3 = MyProgram::main; // void main(String... args)

class Hey {
    public double getRandom() {
        return Math.random();
    }
}

Callable<Double> call = hey::getRandom;
Supplier<Double> call2 = hey::getRandom;
DoubleSupplier sup = hey::getRandom;
// Supplier is functional interface that takes no argument and gives a result

Above, getRandom takes no argument and returns a double. So any functional interface that satisfies the criteria of: take no argument and return double can be used.

Another example:

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));
Predicate<String> pred = set::contains;
boolean exists = pred.test("leo");

In case of parameterized types:

class Param<T> {
    T elem;
    public T get() {
        return elem;
    }

    public void set(T elem) {
        this.elem = elem;
    }

    public static <E> E returnSame(E elem) {
        return elem;
    }
}

Supplier<Param<Integer>> obj = Param<Integer>::new;
Param<Integer> param = obj.get();
Consumer<Integer> c = param::set;
Supplier<Integer> s = param::get;

Function<String, String> func = Param::<String>returnSame;

Method references can have different styles, but fundamentally they all mean the same thing and can simply be visualized as lambdas:

  1. A static method (ClassName::methName)
  2. An instance method of a particular object (instanceRef::methName)
  3. A super method of a particular object (super::methName)
  4. An instance method of an arbitrary object of a particular type (ClassName::methName)
  5. A class constructor reference (ClassName::new)
  6. An array constructor reference (TypeName[]::new)

For further reference, see http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html.

How to pass an object into a state using UI-router?

No, the URL will always be updated when params are passed to transitionTo.

This happens on state.js:698 in ui-router.

Unresolved Import Issues with PyDev and Eclipse

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.

Using lambda expressions for event handlers

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

Force to open "Save As..." popup open at text link click for PDF in HTML

I just used this, but I don't know if it works across all browsers.

It works in Firefox:

<a href="myfile.pdf" download>Click to Download</a>

Percentage width in a RelativeLayout

Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage

Git: How to find a deleted file in the project commit history?

Could not edit the accepted response so adding it as an answer here,

to restore the file in git, use the following (note the '^' sign just after the SHA)

git checkout <SHA>^ -- /path/to/file

Global environment variables in a shell script

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

How do I add one month to current date in Java?

If you need a one-liner (i.e. for Jasper Reports formula) and don't mind if the adjustment is not exactly one month (i.e "30 days" is enough):

new Date($F{invoicedate}.getTime() + 30L * 24L * 60L * 60L * 1000L)

Style disabled button with CSS

By CSS:

.disable{
   cursor: not-allowed;
   pointer-events: none;
}

Them you can add any decoration to that button. For change the status you can use jquery

$("#id").toggleClass('disable');

Sorting arrays in NumPy by column

A little more complicated lexsort example - descending on the 1st column, secondarily ascending on the 2nd. The tricks with lexsort are that it sorts on rows (hence the .T), and gives priority to the last.

In [120]: b=np.array([[1,2,1],[3,1,2],[1,1,3],[2,3,4],[3,2,5],[2,1,6]])
In [121]: b
Out[121]: 
array([[1, 2, 1],
       [3, 1, 2],
       [1, 1, 3],
       [2, 3, 4],
       [3, 2, 5],
       [2, 1, 6]])
In [122]: b[np.lexsort(([1,-1]*b[:,[1,0]]).T)]
Out[122]: 
array([[3, 1, 2],
       [3, 2, 5],
       [2, 1, 6],
       [2, 3, 4],
       [1, 1, 3],
       [1, 2, 1]])

Understanding Spring @Autowired usage

Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

This autowiring will fail:

 @Autowired
 public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }

Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

 @Autowired
 public void prepare( @Qualifier("bean1") Interface1 bean1,
     @Qualifier("bean2")  Interface1 bean2 ) { ... }

How do I redirect output to a variable in shell?

I got error sometimes when using $(`code`) constructor.

Finally i got some approach to that here: https://stackoverflow.com/a/7902174/2480481

Basically, using Tee to read again the ouput and putting it into a variable. Theres how you see the normal output then read it from the ouput.

is not? I guess your current task genhash will output just that, a single string hash so might work for you.

Im so neewbie and still looking for full output & save into 1 command. Regards.

What is the mouse down selector in CSS?

I figured out that this behaves like a mousedown event:

button:active:hover {}

chrome undo the action of "prevent this page from creating additional dialogs"

Close the tab of the page you disabled alerts. Re-open the page in a new tab. The setting only lasts for the session, so alerts will be re-enabled once the new session begins in the new tab.

Need to find a max of three numbers in java

You should know more about java.lang.Math.max:

  1. java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are writing 3 arguments in your code.
  2. The 2 arguments should be double,int,long and float but your are writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.

Try following updated code, that will solve your purpose:

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);    
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);    
        }
        System.out.println("The max of three is: " + max);
    }
} 

Displaying files (e.g. images) stored in Google Drive on a website

You can do it directly from Drive & Gmail. Here's how:

1.Upload an image to Google drive and set permissions for viewing (can be public OR anyone w/ link)

  1. Go to Gmail>Compose. Select the + next to attachment icon.

  2. Select drive icon (triangle shape)

  3. Navigate to your image and right-click copy image url

  4. Paste into web browser or embed on webpages as needed.

Facebook how to check if user has liked page and show content?

You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code

include_once("facebook.php");

    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => FACEBOOK_APP_ID,
      'secret' => FACEBOOK_SECRET,
      'cookie' => true,
    ));

$signed_request = $facebook->getSignedRequest();

// Return you the Page like status
$like_status = $signed_request["page"]["liked"];

if($like_status)
{
    echo 'User Liked the page';
    // Place some content you wanna show to user

}else{
    echo 'User do not liked the page';
    // Place some content that encourage user to like the page
}

Read user input inside a loop

I have found this parameter -u with read.

"-u 1" means "read from stdin"

while read -r newline; do
    ((i++))
    read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
    echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)

Something better than .NET Reflector?

9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...

There is also a new one (at least for me) named Dis#.

connect to host localhost port 22: Connection refused

Check if this port is open. Maybe your SSH demon is not running. See if sshd is running. If not, then start it.

How to save all console output to file in R?

You can print to file and at the same time see progress having (or not) screen, while running a R script.

When not using screen, use R CMD BATCH yourscript.R & and step 4.

  1. When using screen, in a terminal, start screen

     screen
    
  2. run your R script

     R CMD BATCH yourscript.R
    
  3. Go to another screen pressing CtrlA, then c

  4. look at your output with (real-time):

     tail -f yourscript.Rout
    
  5. Switch among screens with CtrlA then n

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JOIN two SELECT statement results

you can use the UNION ALL keyword for this.

Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx

UNION ALL - combines the result set

UNION- Does something like a Set Union and doesnt output duplicate values

For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html

Using R to download zipped data file, extract, and import data

To do this using data.table, I found that the following works. Unfortunately, the link does not work anymore, so I used a link for another data set.

library(data.table)
temp <- tempfile()
download.file("https://www.bls.gov/tus/special.requests/atusact_0315.zip", temp)
timeUse <- fread(unzip(temp, files = "atusact_0315.dat"))
rm(temp)

I know this is possible in a single line since you can pass bash scripts to fread, but I am not sure how to download a .zip file, extract, and pass a single file from that to fread.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Multiple radio button groups in MVC 4 Razor

all you need is to tie the group to a different item in your model

@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")

@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")

How can I access and process nested objects, arrays or JSON?

I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.

_x000D_
_x000D_
var data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'aaa',_x000D_
    items: [{_x000D_
        id: 3,_x000D_
        name: 'ccc'_x000D_
      }, {_x000D_
        id: 4,_x000D_
        name: 'ddd'_x000D_
      }]_x000D_
    }, {_x000D_
    id: 2,_x000D_
    name: 'bbb',_x000D_
    items: [{_x000D_
        id: 5,_x000D_
        name: 'eee'_x000D_
      }, {_x000D_
        id: 6,_x000D_
        name: 'fff'_x000D_
      }]_x000D_
    }]_x000D_
};_x000D_
_x000D_
var jsonloop = new JSONLoop(data, 'id', 'items');_x000D_
_x000D_
jsonloop.findNodeById(data, 5, function(err, node) {_x000D_
  if (err) {_x000D_
    document.write(err);_x000D_
  } else {_x000D_
    document.write(JSON.stringify(node, null, 2));_x000D_
  }_x000D_
});
_x000D_
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
_x000D_
_x000D_
_x000D_

How to check if input date is equal to today's date?

function sameDay( d1, d2 ){
  return d1.getUTCFullYear() == d2.getUTCFullYear() &&
         d1.getUTCMonth() == d2.getUTCMonth() &&
         d1.getUTCDate() == d2.getUTCDate();
}

if (sameDay( new Date(userString), new Date)){
  // ...
}

Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)

How to apply CSS page-break to print a table with lots of rows?

Unfortunately the examples above didn't work for me in Chrome.

I came up with the below solution where you can specify the max height in PXs of each page. This will then splits the table into separate tables when the rows equal that height.

$(document).ready(function(){

    var MaxHeight = 200;
    var RunningHeight = 0;
    var PageNo = 1;

    $('table.splitForPrint>tbody>tr').each(function () {

        if (RunningHeight + $(this).height() > MaxHeight) {
            RunningHeight = 0;
            PageNo += 1;
        }

        RunningHeight += $(this).height();

        $(this).attr("data-page-no", PageNo);

    });

    for(i = 1; i <= PageNo; i++){

        $('table.splitForPrint').parent().append("<div class='tablePage'><hr /><table id='Table" + i + "'><tbody></tbody></table><hr /></div>");

        var rows = $('table tr[data-page-no="' + i + '"]');

        $('#Table' + i).find("tbody").append(rows);
    }
    $('table.splitForPrint').remove();

});

You will also need the below in your stylesheet

    div.tablePage {
        page-break-inside:avoid; page-break-after:always;            
    }

Update Jenkins from a war file

I didn't want to install the x11-common and other components that come bundled in the apt-get install approach, so I just downloaded the .war file and ran the command Francois mentioned. That worked nicely, but you have to write your own daemon script with that approach. Full details here: http://strem.in/stream/9488/Using-the-war-file-for-jenkins-ci

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

Maven has updatePolicy settings for specifying the frequency to check the updates in the repository or to keep the repository in sync with remote.

  • The default value for updatePolicy is daily.
  • Other values can be always / never/ XX (specifying interval in minutes).

Below code sample can be added to maven user settings file to configure updatePolicy.

<pluginRepositories>
    <pluginRepository>
        <id>Releases</id>
        <url>http://<host>:<port>/nexus/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>             
</pluginRepositories>

How do I check if the mouse is over an element in jQuery?

As I cannot comment, so I will write this as an answer!

Please understand the difference between css selector ":hover" and the hover event!

":hover" is a css selector and was indeed removed with the event when used like this $("#elementId").is(":hover"), but in it's meaning it has really nothing to do with the jQuery event hover.

if you code $("#elementId:hover"), the element will only be selected when you hover with the mouse. the above statement will work with all jQuery versions as your selecting this element with pure and legit css selection.

On the other hand the event hover which is

$("#elementId").hover(
     function() { 
         doSomething(); 
     }
); 

is indeed deprecaded as jQuery 1.8 here the state from jQuery website:

When the event name "hover" is used, the event subsystem converts it to "mouseenter mouseleave" in the event string. This is annoying for several reasons:

Semantics: Hovering is not the same as the mouse entering and leaving an element, it implies some amount of deceleration or delay before firing. Event name: The event.type returned by the attached handler is not hover, but either mouseenter or mouseleave. No other event does this. Co-opting the "hover" name: It is not possible to attach an event with the name "hover" and fire it using .trigger("hover"). The docs already call this name "strongly discouraged for new code", I'd like to deprecate it officially for 1.8 and eventually remove it.

Why they removed the usage is(":hover") is unclear but oh well, you can still use it like above and here is a little hack to still use it.

(function ($) {
   /** 
    * :hover selector was removed from jQuery 1.8+ and cannot be used with .is(":hover") 
    * but using it in this way it works as :hover is css selector! 
    *
    **/
    $.fn.isMouseOver = function() {
        return $(this).parent().find($(this).selector + ":hover").length > 0;
    };
})(jQuery);

Oh and I would not recomment the timeout version as this brings a lot of complexity, use timeout functionalities for this kind of stuff if there is no other way and believe me, in 95% percent of all cases there is another way!

Hope I could help a couple people out there.

Greetz Andy

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

VB.net Need Text Box to Only Accept Numbers

First of all set the TextBox's MaxLength to 2 that will limit the amount of text entry in your TextBox. Then you can try something like this using the KeyPress Event. Since you are using a 2 digit maximum (10) you will need to use a Key such as Enter to initiate the check.

Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim tb As TextBox = CType(sender, TextBox)
    If Not IsNumeric(e.KeyChar) Then    'Check if Numeric
        If Char.IsControl(e.KeyChar) Then  'If not Numeric Check if a Control
            If e.KeyChar = ChrW(Keys.Enter) Then
                If Val(tb.Text) > 10 Then  'Check Bounds
                    tb.Text = ""
                    ShowPassFail(False)
                Else
                    ShowPassFail(True)
                End If
                e.Handled = True
            End If
            Exit Sub
        End If
        e.Handled = True
        ShowPassFail(False)
    End If
End Sub

Private Sub ShowPassFail(pass As Boolean)
    If pass Then
        MessageBox.Show("Thank you, your rating was " & TextBox1.Text)
    Else
        MessageBox.Show("Please Enter a Number from 1 to 10")
    End If
    TextBox1.Clear()
    TextBox1.Focus()
End Sub

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

Check whether variable is number or string in JavaScript

Created a jsperf on the checking if a variable is a number. Quite interesting! typeof actually has a performance use. Using typeof for anything other than numbers, generally goes a 1/3rd the speed as a variable.constructor since the majority of data types in javascript are Objects; numbers are not!

http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number

typeof variable === 'number'| fastest | if you want a number, such as 5, and not '5'
typeof parseFloat(variable) === 'number'| fastest | if you want a number, such as 5, and '5'

isNaN() is slower, but not that much slower. I had high hopes for parseInt and parseFloat, however they were horribly slower.

How to get the contents of a webpage in a shell variable?

You can use wget command to download the page and read it into a variable as:

content=$(wget google.com -q -O -)
echo $content

We use the -O option of wget which allows us to specify the name of the file into which wget dumps the page contents. We specify - to get the dump onto standard output and collect that into the variable content. You can add the -q quiet option to turn off's wget output.

You can use the curl command for this aswell as:

content=$(curl -L google.com)
echo $content

We need to use the -L option as the page we are requesting might have moved. In which case we need to get the page from the new location. The -L or --location option helps us with this.

Can I configure a subdomain to point to a specific port on my server

I... don't think so. You can redirect the subdomain (such as blah.something.com) to point to something.com:25566, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.

Angles between two n-dimensional vectors in Python

For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1) geometrical lines, there is the below minimal solution (uses the shapely module, but can be easily modified not to):

from shapely.geometry import LineString
import numpy as np

ninety_degrees_rad = 90.0 * np.pi / 180.0

def angle_between(line1, line2):
    coords_1 = line1.coords
    coords_2 = line2.coords

    line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
    line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0

    # Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
    if line1_vertical and line2_vertical:
        # Perpendicular vertical lines
        return 0.0
    if line1_vertical or line2_vertical:
        # 90° - angle of non-vertical line
        non_vertical_line = line2 if line1_vertical else line1
        return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))

    m1 = slope(line1)
    m2 = slope(line2)

    return np.arctan((m1 - m2)/(1 + m1*m2))

def slope(line):
    # Assignments made purely for readability. One could opt to just one-line return them
    x0 = line.coords[0][0]
    y0 = line.coords[0][1]
    x1 = line.coords[1][0]
    y1 = line.coords[1][1]
    return (y1 - y0) / (x1 - x0)

And the use would be

>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0

mysqli or PDO - what are the pros and cons?

Personally I use PDO, but I think that is mainly a question of preference.

PDO has some features that help agains SQL injection (prepared statements), but if you are careful with your SQL you can achieve that with mysqli, too.

Moving to another database is not so much a reason to use PDO. As long as you don't use "special SQL features", you can switch from one DB to another. However as soon as you use for example "SELECT ... LIMIT 1" you can't go to MS-SQL where it is "SELECT TOP 1 ...". So this is problematic anyway.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

<table align='center' style='text-align:center'>
  <tr>
    <td align='center' style='text-align:center'>
      <!-- AMAZING CONTENT! -->
    </td>
  </tr>
</table>

I only listed some of the key things that resolved my Microsoft email issues.

Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/

It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.

how to create dynamic two dimensional array in java?

Scanner sc=new Scanner(System.in) ;
int p[][] = new int[n][] ;
for(int i=0 ; i<n ; i++)
{
    int m = sc.nextInt() ;      //Taking input from user in JAVA.
    p[i]=new int[m] ;       //Allocating memory block of 'm' int size block.

    for(int j=0 ; j<m ; j++)
    {
         p[i][j]=sc.nextInt();   //Initializing 2D array block.
    }
 }

Changing text of UIButton programmatically swift

Swift 3:

Set button title:

//for normal state:
my_btn.setTitle("Button Title", for: .normal)

// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)

How to read all files in a folder from Java?

    static File mainFolder = new File("Folder");
    public static void main(String[] args) {

        lf.getFiles(lf.mainFolder);
    }
    public void getFiles(File f) {
        File files[];
        if (f.isFile()) {
            String name=f.getName();

        } else {
            files = f.listFiles();
            for (int i = 0; i < files.length; i++) {
                getFiles(files[i]);
            }
        }
    }

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

Is HTML considered a programming language?

The 'M' stands for a 'Markup'. It's a 'Markup Language' not a programming language. Some people will disagree with this, but my opinion is that if it lacks logical constructs (conditional branching, iteration, etc) its not really a programming language.

As for the resume, I would suggest putting HTML and XML under a section like 'Technologies'. I usually have a section like this where I list things like version control software, OS's I've developed for, build systems, etc.

List of All Locales and Their Short Codes?

Language List

List of all languages with names and ISO 639-1 codes in all languages and all data formats.

Formats Available

  • Text
  • JSON
  • YAML
  • XML
  • HTML
  • CSV
  • SQL (MySQL, PostgreSQL, SQLite)
  • PHP

https://github.com/umpirsky/language-list

How do you push just a single Git branch (and no other branches)?

So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.

To push the contents of foo to origin/master, you first need to set its upstream:

git checkout foo
git branch -u origin/master

Then you can push to this branch using:

git push origin HEAD:master

In the last command you can add --force to replace the entire history of origin/master with that of foo.

Any good, visual HTML5 Editor or IDE?

I must question whether you need, specifically, an editor capable of handling HTML5. It's still HTML. There are changes, yes, but not all that much if you are already comfortable with HTML4. I suspect that most any editor capable of handling HTML should be able to handle HTML5 as well.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Abort a git cherry-pick?

For me, the only way to reset the failed cherry-pick-attempt was

git reset --hard HEAD

Using regular expression in css?

First of all, there are many, many ways of matching items within a HTML document. Start with this reference to see some of the available selectors/patterns which you can use to apply a style rule to an element(s).

http://www.w3.org/TR/selectors/

Match all divs which are direct descendants of #main.

#main > div

Match all divs which are direct or indirect descendants of #main.

#main div

Match the first div which is a direct descendant of #sections.

#main > div:first-child

Match a div with a specific attribute.

#main > div[foo="bar"]

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I also got the same issue of IE9 rendering in IE7 Document standards for local host. I tried many conditional comments tags but unsuccesful. In the end I just removed all conditional tags and just added meta tag immediatly after head like below and it worked like charm.

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Hope it helps

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

How to use Lambda in LINQ select statement

Using Lambda expressions:

  1. If we don't have a specific class to bind the result:

     var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
    

Using simple LINQ expressions:

  1. If we don't have a specific class to bind the result:

    var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
    
  2. If we have a specific class then we need to bind the result with it:

    List<SelectListItem> stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
    

How to click a link whose href has a certain substring in Selenium?

I need to click the link who's href has substring "long" in it. How can I do this?

With the beauty of CSS selectors.

your statement would be...

driver.findElement(By.cssSelector("a[href*='long']")).click();

This means, in english,

Find me any 'a' elements, that have the href attribute, and that attribute contains 'long'

You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains, starts with, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html

Android - Get value from HashMap

Note: If you know Key, use this code

String value=meMap.get(key);

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

javascript node.js next()

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

One more variant with foreign keys support and in one statement:

 SELECT
        obj.name
        ,'CREATE TABLE [' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')'
        + ISNULL(' ' + refs.list, '')
    FROM sysobjects obj
    CROSS APPLY (
        SELECT 
            CHAR(10)
            + ' [' + column_name + '] '
            + data_type
            + CASE data_type
                WHEN 'sql_variant' THEN ''
                WHEN 'text' THEN ''
                WHEN 'ntext' THEN ''
                WHEN 'xml' THEN ''
                WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
                ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
            END
            + ' '
            + case when exists ( -- Identity skip
            select id from syscolumns
            where object_name(id) = obj.name
            and name = column_name
            and columnproperty(id,name,'IsIdentity') = 1 
            ) then
            'IDENTITY(' + 
            cast(ident_seed(obj.name) as varchar) + ',' + 
            cast(ident_incr(obj.name) as varchar) + ')'
            else ''
            end + ' '
            + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
            + 'NULL'
            + CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END
            + ','
        FROM
            INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = obj.name
        ORDER BY ordinal_position
        FOR XML PATH('')
    ) cols (list)
    CROSS APPLY(
        SELECT
            CHAR(10) + 'ALTER TABLE ' + obj.name + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)
        FROM(
            SELECT
                CHAR(10)
                + ' CONSTRAINT ' + tc.constraint_name
                + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
                + COALESCE(CHAR(10) + r.list, ', ')
            FROM
                information_schema.table_constraints tc
                CROSS APPLY(
                    SELECT
                        '[' + kcu.column_name + '], '
                    FROM
                        information_schema.key_column_usage kcu
                    WHERE
                        kcu.constraint_name = tc.constraint_name
                    ORDER BY
                        kcu.ordinal_position
                    FOR XML PATH('')
                ) c (list)
                OUTER APPLY(
                    -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
                    SELECT
                        '  REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '(' + kcu2.column_name + '), '
                    FROM information_schema.referential_constraints as rc
                        JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
                        JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
                    WHERE
                        kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name
                ) r (list)
            WHERE tc.table_name = obj.name
            FOR XML PATH('')
        ) a (alt)
    ) refs (list)
    WHERE
        xtype = 'U'
    AND name NOT IN ('dtproperties')
    AND obj.name = 'your_table_name'

You could try in is sqlfiddle: http://sqlfiddle.com/#!6/e3b66/3/0

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

How to create a new schema/new user in Oracle Database 11g?

From oracle Sql developer, execute the below in sql worksheet:

create user lctest identified by lctest;
grant dba to lctest;

then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.

Python: How would you save a simple settings/config file?

Save and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.

How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.

The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).

if(objectA == objectB) {
   // objects are the same instance. i.e. compare two memory addresses against each other.
}

if(objectA.equals(objectB)) {
   // objects have the same contents. i.e. compare all characters to each other 
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.

String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.

All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with

if(objectA == objectB || objectA.equals(objectB)) {

}

if you have a mix of the two scenarios. The inline

if(objectA == null ? objectB == null : objectA.equals(objectB)) {

}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

@AspectJ pointcut for all methods of a class with specific annotation

From Spring's AnnotationTransactionAspect:

/**
 * Matches the execution of any public method in a type with the Transactional
 * annotation, or any subtype of a type with the Transactional annotation.
 */
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
    execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);

Fastest way to convert string to integer in PHP

Run a test.

   string coerce:          7.42296099663
   string cast:            8.05654597282
   string fail coerce:     7.14159703255
   string fail cast:       7.87444186211

This was a test that ran each scenario 10,000,000 times. :-)

Co-ercion is 0 + "123"

Casting is (integer)"123"

I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123') is a fatal error in PHP. You might want your code to check the type of the supplied value.

My test code is below.


function test_string_coerce($s) {
    return 0 + $s;
}

function test_string_cast($s) {
    return (integer)$s;
}

$iter = 10000000;

print "-- running each text $iter times.\n";

// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();

print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('123');
}

$string_coerce->Stop();

// string cast
$string_cast = new Timer;
$string_cast->Start();

print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('123');
}

$string_cast->Stop();

// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();

print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('hello');
}

$string_coerce_fail->Stop();

// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();

print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('hello');
}

$string_cast_fail->Stop();

// -----------------
print "\n";
print "string coerce:          ".$string_coerce->Elapsed()."\n";
print "string cast:            ".$string_cast->Elapsed()."\n";
print "string fail coerce:     ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast:       ".$string_cast_fail->Elapsed()."\n";


class Timer {
    var $ticking = null;
    var $started_at = false;
    var $elapsed = 0;

    function Timer() {
        $this->ticking = null;
    }

    function Start() {
        $this->ticking = true;
        $this->started_at = microtime(TRUE);
    }

    function Stop() {
        if( $this->ticking )
            $this->elapsed = microtime(TRUE) - $this->started_at;
        $this->ticking = false;
    }

    function Elapsed() {
        switch( $this->ticking ) {
            case true: return "Still Running";
            case false: return $this->elapsed;
            case null: return "Not Started";
        }
    }
}

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

How to tell if a file is git tracked (by shell exit code)?

I don't know of any git command that gives a "bad" exit code, but it seems like an easy way to do it would be to use a git command that gives no output for a file that isn't tracked, such as git-log or git-ls-files. That way you don't really have to do any parsing, you can run it through another simple utility like grep to see if there was any output.

For example,

git-ls-files test_file.c | grep .

will exit with a zero code if the file is tracked, but a exit code of one if the file is not tracked.

did you register the component correctly? For recursive components, make sure to provide the "name" option

Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.

I was using vue splitpanes.

Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).

Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.

[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.