Programs & Examples On #Duplicates

The "duplicates" tag concerns detecting and/or dealing with multiple instances of items in collections.

How do I delete all the duplicate records in a MySQL table without temp tables

If you are not using any primary key, then execute following queries at one single stroke. By replacing values:

# table_name - Your Table Name
# column_name_of_duplicates - Name of column where duplicate entries are found

create table table_name_temp like table_name;
insert into table_name_temp select distinct(column_name_of_duplicates),value,type from table_name group by column_name_of_duplicates;
delete from table_name;
insert into table_name select * from table_name_temp;
drop table table_name_temp
  1. create temporary table and store distinct(non duplicate) values
  2. make empty original table
  3. insert values to original table from temp table
  4. delete temp table

It is always advisable to take backup of database before you play with it.

In MySQL, can I copy one row to insert into the same table?

I might be late in this, but I have a similar solution which has worked for me.

 INSERT INTO `orders` SELECT MAX(`order_id`)+1,`container_id`, `order_date`, `receive_date`, `timestamp` FROM `orders` WHERE `order_id` = 1

This way I don't need to create a temporary table and etc. As the row is copied in the same table the Max(PK)+1 function can be used easily.

I came looking for the solution of this question (had forgotten the syntax) and I ended up making my own query. Funny how things work out some times.

Regards

How to remove duplicates from a list?

List ? Set ? List (distinct)

Just add all your elements to a Set: it does not allow it's elements to be repeated. If you need a list afterwards, use new ArrayList(theSet) constructor afterwards (where theSet is your resulting set).

Map implementation with duplicate keys

No fancy libs required. Maps are defined by a unique key, so dont bend them, use a list. Streams are mighty.

import java.util.AbstractMap.SimpleImmutableEntry;

List<SimpleImmutableEntry<String, String>> nameToLocationMap = Arrays.asList(
    new SimpleImmutableEntry<>("A", "A1"),
    new SimpleImmutableEntry<>("A", "A2"),
    new SimpleImmutableEntry<>("B", "B1"),
    new SimpleImmutableEntry<>("B", "B1"),
);

And thats it. Usage examples:

List<String> allBsLocations = nameToLocationMap.stream()
        .filter(x -> x.getKey().equals("B"))
        .map(x -> x.getValue())
        .collect(Collectors.toList());

nameToLocationMap.stream().forEach(x -> 
do stuff with: x.getKey()...x.getValue()...

How to delete duplicates on a MySQL table?

After running into this issue myself, on a huge database, I wasn't completely impressed with the performance of any of the other answers. I want to keep only the latest duplicate row, and delete the rest.

In a one-query statement, without a temp table, this worked best for me,

DELETE e.*
FROM employee e
WHERE id IN
 (SELECT id
   FROM (SELECT MIN(id) as id
          FROM employee e2
          GROUP BY first_name, last_name
          HAVING COUNT(*) > 1) x);

The only caveat is that I have to run the query multiple times, but even with that, I found it worked better for me than the other options.

How to "select distinct" across multiple data frame columns in pandas?

You can take the sets of the columns and just subtract the smaller set from the larger set:

distinct_values = set(df['a'])-set(df['b'])

Removing duplicates in the lists

There are also solutions using Pandas and Numpy. They both return numpy array so you have to use the function .tolist() if you want a list.

t=['a','a','b','b','b','c','c','c']
t2= ['c','c','b','b','b','a','a','a']

Pandas solution

Using Pandas function unique():

import pandas as pd
pd.unique(t).tolist()
>>>['a','b','c']
pd.unique(t2).tolist()
>>>['c','b','a']

Numpy solution

Using numpy function unique().

import numpy as np
np.unique(t).tolist()
>>>['a','b','c']
np.unique(t2).tolist()
>>>['a','b','c']

Note that numpy.unique() also sort the values. So the list t2 is returned sorted. If you want to have the order preserved use as in this answer:

_, idx = np.unique(t2, return_index=True)
t2[np.sort(idx)].tolist()
>>>['c','b','a']

The solution is not so elegant compared to the others, however, compared to pandas.unique(), numpy.unique() allows you also to check if nested arrays are unique along one selected axis.

MySQL duplicate entry error even though there is no duplicate entry

Try with auto increment:

CREATE TABLE IF NOT EXISTS `my_table` (
   `number` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(50) NOT NULL,
   `money` int(11) NOT NULL,
    PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;

How do I get a list of all the duplicate items using pandas in python?

Method #1: print all rows where the ID is one of the IDs in duplicated:

>>> import pandas as pd
>>> df = pd.read_csv("dup.csv")
>>> ids = df["ID"]
>>> df[ids.isin(ids[ids.duplicated()])].sort("ID")
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

but I couldn't think of a nice way to prevent repeating ids so many times. I prefer method #2: groupby on the ID.

>>> pd.concat(g for _, g in df.groupby("ID") if len(g) > 1)
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

Drop all duplicate rows across multiple columns in Python Pandas

Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Drop duplicates except for the first occurrence.

  • last : Drop duplicates except for the last occurrence.

  • False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with duplicate rows removed, optionally only considering certain columns

Parameters: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. take_last : deprecated inplace : boolean, default False Whether to drop duplicates in place or to return a copy cols : kwargs only argument of subset [deprecated] Returns: deduplicated : DataFrame

How to delete duplicate rows in SQL Server?

with myCTE
as

(
select productName,ROW_NUMBER() over(PARTITION BY productName order by slno) as Duplicate from productDetails
)
Delete from myCTE where Duplicate>1

Removing duplicate rows from table in Oracle

For best performance, here is what I wrote :
(see execution plan)

DELETE FROM your_table
WHERE rowid IN 
  (select t1.rowid from your_table  t1
      LEFT OUTER JOIN (
      SELECT MIN(rowid) as rowid, column1,column2, column3
      FROM your_table 
      GROUP BY column1, column2, column3
  )  co1 ON (t1.rowid = co1.rowid)
  WHERE co1.rowid IS NULL
);

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

If you want a REAL cloned object/array in JS with cloned references of all attributes and sub-objects:

export function clone(arr) {
    return JSON.parse(JSON.stringify(arr))
}

ALL other operations do not create clones, because they just change the base address of the root element, not of the included objects.

Except you traverse recursive through the object-tree.

For a simple copy, these are OK. For storage address relevant operations I suggest (and in most all other cases, because this is fast!) to type convert into string and back in a complete new object.

TypeError: unhashable type: 'list' when using built-in set function

Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.

Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.

result = sorted(set(map(tuple, my_list)), reverse=True)

Additional note: If a tuple contains a list, the tuple is still considered mutable.

Some examples:

>>> hash( tuple() )
3527539
>>> hash( dict() )

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    hash( list() )
TypeError: unhashable type: 'list'

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

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

import os
import shutil
import datetime

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

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

Removing duplicate rows in Notepad++

If the rows are immediately after each other then you can use a regex replace:

Search Pattern: ^(.*\r?\n)(\1)+

Replace with: \1

How to merge 2 List<T> and removing duplicate values from it in C#

Use Linq's Union:

using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();

php: check if an array has duplicates

The simple solution but quite faster.

$elements = array_merge(range(1,10000000),[1]);

function unique_val_inArray($arr) {
    $count = count($arr);
    foreach ($arr as $i_1 => $value) {
        for($i_2 = $i_1 + 1; $i_2 < $count; $i_2++) {
            if($arr[$i_2] === $arr[$i_1]){
                return false;
            }
        }
    }
    return true;
}

$time = microtime(true);
unique_val_inArray($elements);
echo 'This solution: ', (microtime(true) - $time), 's', PHP_EOL;

Speed - [0.71]!

Remove duplicates from an array of objects in JavaScript

If you can wait to eliminate the duplicates until after all the additions, the typical approach is to first sort the array and then eliminate duplicates. The sorting avoids the N * N approach of scanning the array for each element as you walk through them.

The "eliminate duplicates" function is usually called unique or uniq. Some existing implementations may combine the two steps, e.g., prototype's uniq

This post has few ideas to try (and some to avoid :-) ) if your library doesn't already have one! Personally I find this one the most straight forward:

    function unique(a){
        a.sort();
        for(var i = 1; i < a.length; ){
            if(a[i-1] == a[i]){
                a.splice(i, 1);
            } else {
                i++;
            }
        }
        return a;
    }  

    // Provide your own comparison
    function unique(a, compareFunc){
        a.sort( compareFunc );
        for(var i = 1; i < a.length; ){
            if( compareFunc(a[i-1], a[i]) === 0){
                a.splice(i, 1);
            } else {
                i++;
            }
        }
        return a;
    }

How do I (or can I) SELECT DISTINCT on multiple columns?

If you put together the answers so far, clean up and improve, you would arrive at this superior query:

UPDATE sales
SET    status = 'ACTIVE'
WHERE  (saleprice, saledate) IN (
    SELECT saleprice, saledate
    FROM   sales
    GROUP  BY saleprice, saledate
    HAVING count(*) = 1 
    );

Which is much faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).

But this is still far from optimal. Use a NOT EXISTS (anti-)semi-join for even better performance. EXISTS is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:

UPDATE sales s
SET    status = 'ACTIVE'
WHERE  NOT EXISTS (
   SELECT FROM sales s1                     -- SELECT list can be empty for EXISTS
   WHERE  s.saleprice = s1.saleprice
   AND    s.saledate  = s1.saledate
   AND    s.id <> s1.id                     -- except for row itself
   )
AND    s.status IS DISTINCT FROM 'ACTIVE';  -- avoid empty updates. see below

db<>fiddle here
Old SQL Fiddle

Unique key to identify row

If you don't have a primary or unique key for the table (id in the example), you can substitute with the system column ctid for the purpose of this query (but not for some other purposes):

   AND    s1.ctid <> s.ctid

Every table should have a primary key. Add one if you didn't have one, yet. I suggest a serial or an IDENTITY column in Postgres 10+.

Related:

How is this faster?

The subquery in the EXISTS anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes way more efficient.

Exclude empty updates

For rows that already have status = 'ACTIVE' this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another WHERE condition like demonstrated above to avoid this and make it even faster:

If status is defined NOT NULL, you can simplify to:

AND status <> 'ACTIVE';

The data type of the column must support the <> operator. Some types like json don't. See:

Subtle difference in NULL handling

This query (unlike the currently accepted answer by Joel) does not treat NULL values as equal. The following two rows for (saleprice, saledate) would qualify as "distinct" (though looking identical to the human eye):

(123, NULL)
(123, NULL)

Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:

OTOH, GROUP BY, DISTINCT or DISTINCT ON () treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with IS NOT DISTINCT FROM instead of = for any or all comparisons to make NULL compare equal. More:

If all columns being compared are defined NOT NULL, there is no room for disagreement.

how to prevent adding duplicate keys to a javascript array

var a = [1,2,3], b = [4,1,5,2];

b.forEach(function(value){
  if (a.indexOf(value)==-1) a.push(value);
});

console.log(a);
// [1, 2, 3, 4, 5]

For more details read up on Array.indexOf.

If you want to rely on jQuery, instead use jQuery.inArray:

$.each(b,function(value){
  if ($.inArray(value,a)==-1) a.push(value);
});

If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by @JonathanSampson).

How do you remove duplicates from a list whilst preserving order?

A solution without using imported modules or sets:

text = "ask not what your country can do for you ask what you can do for your country"
sentence = text.split(" ")
noduplicates = [(sentence[i]) for i in range (0,len(sentence)) if sentence[i] not in sentence[:i]]
print(noduplicates)

Gives output:

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']

Finding duplicate rows in SQL Server

Try

SELECT orgName, id, count(*) as dupes
FROM organizations
GROUP BY orgName, id
HAVING count(*) > 1;

Regular Expression For Duplicate Words

I believe this regex handles more situations:

/(\b\S+\b)\s+\b\1\b/

A good selection of test strings can be found here: http://callumacrae.github.com/regex-tuesday/challenge1.html

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

What's the best way to dedupe a table?

For deduplicate / dedupe / remove duplication / remove repeated rows / ??? ?? / ??? ?? ????, there are multiple ways.

  1. If duplicated rows are exact the same, use group by

    create table TABLE_NAME_DEDUP
    as select column1, column2, ... (all column names) from TABLE_NAME group by column1, column2, -- all column names

Then TABLE_NAME_DEDUP is the deduplicated table.

For example,

create table test (t1 varchar(5), t2 varchar(5));
insert into test  values ('12345', 'ssdlh');
insert into test  values ('12345', 'ssdlh');
create table test_dedup as
select * from test 
group by t1, t2;
-----optional
--remove original table and rename dedup table to previous table
--this is not recommend in dev or qa. DROP table test; Alter table test_dedup rename to test;
  1. You have a rowid, the rowid has duplication but other columns are different Records partial same, this may happened in a transactional system while update a row, and the rows failed to update will have nulls. You want to remove the duplication

    create table test_dedup as select column1, column2, ... (all column names) from ( select * , row_number() over (partition by rowid order by column1, column2, ... (all column names except rowid) ) as cn from test ) where cn =1

This is using the feature that when you use order by, the null value will be ordered behind the non-null value.

create table test (rowid_ varchar(5), t1 varchar(5), t2 varchar(5));
insert into test  values ('12345', 'ssdlh', null);
insert into test  values ('12345', 'ssdlh', 'lhbzj');
create table test_dedup as
select rowid_, t1, t2 from
(select *
  , row_number() over (partition by rowid_ order by t1, t2) as cn
  from  test)
 where cn =1
 ;

-----optional
--remove original table and rename dedup table to previous table
--this is not recommend in dev or qa. DROP table test; Alter table test_dedup rename to test;

Left Join without duplicate rows from left table

Using the DISTINCT flag will remove duplicate rows.

SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
ORDER BY C.Content_DatePublished ASC

Removing duplicates from a SQL query (not just "use distinct")

You need to tell the query what value to pick for the other columns, MIN or MAX seem like suitable choices.

 SELECT
   U.NAME, MIN(P.PIC_ID)
 FROM
   USERS U,
   PICTURES P,
   POSTINGS P1
 WHERE
   U.EMAIL_ID = P1.EMAIL_ID AND
   P1.PIC_ID = P.PIC_ID AND
   P.CAPTION LIKE '%car%'
 GROUP BY
   U.NAME;

How can I remove duplicate rows?

DELETE 
FROM MyTable
WHERE NOT EXISTS (
              SELECT min(RowID)
              FROM Mytable
              WHERE (SELECT RowID 
                     FROM Mytable
                     GROUP BY Col1, Col2, Col3
                     ))
               );

Finding duplicate integers in an array and display how many times they occurred

You made a minor mistake of using J instead of i ...

class Program
{
    static void Main(string[] args)
    {              
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {
               if(array[i] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

Find duplicate records in MySQL

The key is to rewrite this query so that it can be used as a subquery.

SELECT firstname, 
   lastname, 
   list.address 
FROM list
   INNER JOIN (SELECT address
               FROM   list
               GROUP  BY address
               HAVING COUNT(id) > 1) dup
           ON list.address = dup.address;

Remove duplicate rows in MySQL

Delete duplicate rows using DELETE JOIN statement MySQL provides you with the DELETE JOIN statement that you can use to remove duplicate rows quickly.

The following statement deletes duplicate rows and keeps the highest id:

DELETE t1 FROM contacts t1
    INNER JOIN
contacts t2 WHERE
t1.id < t2.id AND t1.email = t2.email;

How to find duplicate records in PostgreSQL

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

In order to find duplicate values you should run,

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

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

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

Remove duplicate values from JS array

var uniqueCompnies = function(companyArray) {
    var arrayUniqueCompnies = [],
        found, x, y;

    for (x = 0; x < companyArray.length; x++) {
        found = undefined;
        for (y = 0; y < arrayUniqueCompnies.length; y++) {
            if (companyArray[x] === arrayUniqueCompnies[y]) {
                found = true;
                break;
            }
        }

        if ( ! found) {
            arrayUniqueCompnies.push(companyArray[x]);
        }
    }

    return arrayUniqueCompnies;
}

var arr = [
    "Adobe Systems Incorporated",
    "IBX",
    "IBX",
    "BlackRock, Inc.",
    "BlackRock, Inc.",
];

Finding duplicate values in a SQL table

You may want to try this

SELECT NAME, EMAIL, COUNT(*)
FROM USERS
GROUP BY 1,2
HAVING COUNT(*) > 1

Java Scanner class reading strings

use sc.nextLine(); two time so that we can read the last line of string

sc.nextLine() sc.nextLine()

Java generating non-repeating random numbers

public class RandomNum {
    public static void main(String[] args) {
        Random rn = new Random();
        HashSet<Integer> hSet = new HashSet<>();
        while(hSet.size() != 1000) {
            hSet.add(rn.nextInt(1000));
        }
        System.out.println(hSet);
    }
}

How do I find duplicates across multiple columns?

 SELECT name, city, count(*) as qty 
 FROM stuff 
 GROUP BY name, city HAVING count(*)> 1

How do I remove repeated elements from ArrayList?

In Java 8:

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

Please note that the hashCode-equals contract for list members should be respected for the filtering to work properly.

How do I check if there are duplicates in a flat list?

A more simple solution is as follows. Just check True/False with pandas .duplicated() method and then take sum. Please also see pandas.Series.duplicated — pandas 0.24.1 documentation

import pandas as pd

def has_duplicated(l):
    return pd.Series(l).duplicated().sum() > 0

print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False

How to find all duplicate from a List<string>?

    lblrepeated.Text = ""; 
    string value = txtInput.Text;
    char[] arr = value.ToCharArray();
    char[] crr=new char[1];        
   int count1 = 0;        
    for (int i = 0; i < arr.Length; i++)
    {
        int count = 0;  
        char letter=arr[i];
        for (int j = 0; j < arr.Length; j++)
        {
            char letter3 = arr[j];
                if (letter == letter3)
                {
                    count++;
                }                    
        }
        if (count1 < count)
        {
            Array.Resize<char>(ref crr,0);
            int count2 = 0;
            for(int l = 0;l < crr.Length;l++)
            {
                if (crr[l] == letter)
                    count2++;                    
            }


            if (count2 == 0)
            {
                Array.Resize<char>(ref crr, crr.Length + 1);
                crr[crr.Length-1] = letter;
            }

            count1 = count;               
        }
        else if (count1 == count)
        {
            int count2 = 0;
            for (int l = 0; l < crr.Length; l++)
            {
                if (crr[l] == letter)
                    count2++;
            }


            if (count2 == 0)
            {
                Array.Resize<char>(ref crr, crr.Length + 1);
                crr[crr.Length - 1] = letter;
            }

            count1 = count; 
        }
    }

    for (int k = 0; k < crr.Length; k++)
        lblrepeated.Text = lblrepeated.Text + crr[k] + count1.ToString();

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

Remove duplicate elements from array in Ruby

You can return the intersection.

a = [1,1,2,3]
a & a

This will also delete duplicates.

How to get duplicate items from a list using LINQ?

var duplicates = lst.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct to the resulting sequence or use the solution given by Mark Byers.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

How do I find the duplicates in a list and create another list with them?

Try this For check duplicates

>>> def checkDuplicate(List):
    duplicate={}
    for i in List:
            ## checking whether the item is already present in dictionary or not
            ## increasing count if present
            ## initializing count to 1 if not present

        duplicate[i]=duplicate.get(i,0)+1

    return [k for k,v in duplicate.items() if v>1]

>>> checkDuplicate([1,2,3,"s",1,2,3])
[1, 2, 3]

Remove duplicated rows

For people who have come here to look for a general answer for duplicate row removal, use !duplicated():

a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

duplicated(df)
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE

> df[duplicated(df), ]
  a b
2 A 1
6 B 1
8 C 2

> df[!duplicated(df), ]
  a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2

Answer from: Removing duplicated rows from R data frame

Remove duplicates from a List<T> in C#

Might be easier to simply make sure that duplicates are not added to the list.

if(items.IndexOf(new_item) < 0) 
    items.add(new_item)

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Here's a variation I had to solve that's worth sharing: for each unique string in columnA I wanted to find the most common associated string in columnB.

df.groupby('columnA').agg({'columnB': lambda x: x.mode().any()}).reset_index()

The .any() picks one if there's a tie for the mode. (Note that using .any() on a Series of ints returns a boolean rather than picking one of them.)

For the original question, the corresponding approach simplifies to

df.groupby('columnA').columnB.agg('max').reset_index().

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Get all unique values in a JavaScript array (remove duplicates)

Yet another answer, just because I wrote one for my specific use case. I happened to be sorting the array anyway, and given I'm sorting I can use that to deduplicate.

Note that my sort deals with my specific data types, you might need a different sort depending on what sort of elements you have.

var sortAndDedup = function(array) {
  array.sort(function(a,b){
    if(isNaN(a) && isNaN(b)) { return a > b ? 1 : (a < b ? -1 : 0); }
    if(isNaN(a)) { return 1; }
    if(isNaN(b)) { return -1; }
    return a-b;
  });

  var newArray = [];
  var len = array.length;
  for(var i=0; i<len; i++){
    if(i === 0 || array[i] != array[i-1]){
      newArray.push(array[i]);
    }
  }
};

What's the most efficient way to erase duplicates and sort a vector?

With the Ranges v3 library, you can simply use

action::unique(vec);

Note that it actually removes the duplicate elements, not just move them.

Unfortunately, actions weren’t standardized in C++20 as other parts of the ranges library were you still have to use the original library even in C++20.

How do I remove duplicate items from an array in Perl?

Previous answers pretty much summarize the possible ways of accomplishing this task.

However, I suggest a modification for those who don't care about counting the duplicates, but do care about order.

my @record = qw( yeah I mean uh right right uh yeah so well right I maybe );
my %record;
print grep !$record{$_} && ++$record{$_}, @record;

Note that the previously suggested grep !$seen{$_}++ ... increments $seen{$_} before negating, so the increment occurs regardless of whether it has already been %seen or not. The above, however, short-circuits when $record{$_} is true, leaving what's been heard once 'off the %record'.

You could also go for this ridiculousness, which takes advantage of autovivification and existence of hash keys:

...
grep !(exists $record{$_} || undef $record{$_}), @record;

That, however, might lead to some confusion.

And if you care about neither order or duplicate count, you could for another hack using hash slices and the trick I just mentioned:

...
undef @record{@record};
keys %record; # your record, now probably scrambled but at least deduped

Remove pandas rows with duplicate indices

Unfortunately, I don't think Pandas allows one to drop dups off the indices. I would suggest the following:

df3 = df3.reset_index() # makes date column part of your data
df3.columns = ['timestamp','A','B','rownum'] # set names
df3 = df3.drop_duplicates('timestamp',take_last=True).set_index('timestamp') #done!

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

Select and display only duplicate records in MySQL

here is the simple example :

select <duplicate_column_name> from <table_name> group by <duplicate_column_name> having count(*)>=2

It will definitly work. :)

Algorithm: efficient way to remove duplicate integers from an array

For someone who want to have simple solution in C++:

int* rmdup(int path[], int start, int end, int& newEnd) {
    int ret[100];
newEnd = end;
int j = start;

for (int i = start; i < end; i++) {
    if (path[i] == path[i+1]) {
    newEnd--;
        continue;
    }
    ret[j++] = path[i];
}

ret[j++] = path[end];

for(int i = start; i <= newEnd; i++)
     path[i] = ret[i];
}

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

Java: Detect duplicates in ArrayList?

    String tempVal = null;
    for (int i = 0; i < l.size(); i++) {
        tempVal = l.get(i); //take the ith object out of list
        while (l.contains(tempVal)) {
            l.remove(tempVal); //remove all matching entries
        }
        l.add(tempVal); //at last add one entry
    }

Note: this will have major performance hit though as items are removed from start of the list. To address this, we have two options. 1) iterate in reverse order and remove elements. 2) Use LinkedList instead of ArrayList. Due to biased questions asked in interviews to remove duplicates from List without using any other collection, above example is the answer. In real world though, if I have to achieve this, I will put elements from List to Set, simple!

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

your column value is already in database table it means your table column is Unique you should change your value and try again

sql query to find the duplicate records

This query uses the Group By and and Having clauses to allow you to select (locate and list out) for each duplicate record. The As clause is a convenience to refer to Quantity in the select and Order By clauses, but is not really part of getting you the duplicate rows.

Select
    Title,
    Count( Title ) As [Quantity]
   From
    Training
   Group By
    Title
   Having 
    Count( Title ) > 1
   Order By
    Quantity desc

How do I remove duplicates from a C# array?

The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist:

private void RemoveDuplicate() 
{

ArrayList dataArray = new ArrayList(5);

            dataArray.Add("1");
            dataArray.Add("1");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("3");
            dataArray.Add("6");
            dataArray.Add("4");
            dataArray.Add("5");
            dataArray.Add("4");
            dataArray.Add("1");

            dataArray.Sort();

            GetDistinctArrayList(dataArray, 0);
}

private void GetDistinctArrayList(ArrayList arr, int idx)

{

            int count = 0;

            if (idx >= arr.Count) return;

            string val = arr[idx].ToString();
            foreach (String s in arr)
            {
                if (s.Equals(arr[idx]))
                {
                    count++;
                }
            }

            if (count > 1)
            {
                arr.Remove(val);
                GetDistinctArrayList(arr, idx);
            }
            else
            {
                idx += 1;
                GetDistinctArrayList(arr, idx);
            }
        }

How to select records without duplicate on just one field in SQL?

Try this:

SELECT MIN(id) AS id, title
FROM tbl_countries
GROUP BY title

How To Use DateTimePicker In WPF?

There is DatePicker in WPF Tool Kit, but I have not seen DateTime Picker in WPF ToolKit. So I don't know what kind of DateTimePicker control John is talking about.

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Failed to load AppCompat ActionBar with unknown error in android studio

This is Worked for me i have made the following changes in Style.xml

Change the Following Code:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

With

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);

String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

How to get numeric position of alphabets in java?

First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.

For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.

Permission denied for relation

GRANT on the database is not what you need. Grant on the tables directly.

Granting privileges on the database mostly is used to grant or revoke connect privileges. This allows you to specify who may do stuff in the database if they have sufficient other permissions.

You want instead:

 GRANT ALL PRIVILEGES ON TABLE side_adzone TO jerry;

This will take care of this issue.

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

The above solutions are great, but if you're using WampServer you might find setting the curl.cainfo variable in php.ini doesn't work.

I eventually found WampServer has two php.ini files:

C:\wamp\bin\apache\Apachex.x.x\bin
C:\wamp\bin\php\phpx.x.xx

The first is apparently used for when PHP files are invoked through a web browser, while the second is used when a command is invoked through the command line or shell_exec().

TL;DR

If using WampServer, you must add the curl.cainfo line to both php.ini files.

How to set Default Controller in asp.net MVC 4 & MVC 5

the best way is to change your route. The default route (defined in your App_Start) sets /Home/Index

routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters*
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

as the default landing page. You can change that to be any route you wish.

routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters*
        new { controller = "Sales", action = "ProjectionReport", 
        id = UrlParameter.Optional }
);

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

How to align td elements in center

What worked for me is the following (in view of the confusion in other answers):

<td style="text-align:center;">
    <input type="radio" name="ageneral" value="male">
</td>

The proposed solution (text-align) works but must be used in a style attribute.

Include jQuery in the JavaScript Console

Turnkey solution :

Put your code in yourCode_here function. And prevent HTML without HEAD tag.

_x000D_
_x000D_
(function(head) {_x000D_
  var jq = document.createElement('script');_x000D_
  jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";_x000D_
  ((head && head[0]) || document.firstChild).appendChild(jq);_x000D_
})(document.getElementsByTagName('head'));_x000D_
_x000D_
function jQueryReady() {_x000D_
  if (window.jQuery) {_x000D_
    jQuery.noConflict();_x000D_
    yourCode_here(jQuery);_x000D_
  } else {_x000D_
    setTimeout(jQueryReady, 100);_x000D_
  }_x000D_
}_x000D_
_x000D_
jQueryReady();_x000D_
_x000D_
function yourCode_here($) {_x000D_
  console.log("OK");_x000D_
  $("body").html("<h1>Hello world !</h1>");_x000D_
}
_x000D_
_x000D_
_x000D_

Error during SSL Handshake with remote server

I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.

So, I had to generate the SSL certificate again and it started working...

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

Android list view inside a scroll view

I was having the same problem for such a long time. Then I found a solution that worked for me. Add a ListViewHelper java class. Here below is code for ListViewHelper.java

package com.molescope;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class ListViewHelper {
    public static void getListViewSize(ListView listView){
        ListAdapter adapter = listView.getAdapter();
        if(adapter!=null){
            int totalHeight = 0;

            //setting list adapter in loop tp get final size
            for (int i=0; i<adapter.getCount(); i++){
                View listItem = adapter.getView(i, null, listView);
                listItem.measure(0,0);
                totalHeight += listItem.getMeasuredHeight();
            }
            //setting listview items in adapter
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * 
    (adapter.getCount()-1));
            listView.setLayoutParams(params);

        }else{
            return;
        }
    }
}

And after adding this java file, in your code wherever you are setting adapter to listview, right after that line add the code below:

  ListView myList=(ListView) findViewById(R.id.listView);
  myList.setAdapter(new ArrayAdapter<String>. 
  (this,android.R.layout.simple_list_item_1, listview_array));
  ListViewHelper.getListViewSize(myList);

Pardon my english.

CSS table td width - fixed, not flexible

The above suggestions trashed the layout of my table so I ended up using:

td {
  min-width: 30px;
  max-width: 30px;
  overflow: hidden;
}

This is horrible to maintain but was easier than re-doing all the existing css for the site. Hope it helps someone else.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I was able to fix the error by

  1. Completely closing Access
  2. Renaming the database file
  3. Opening the renamed database file in Access.
  4. Accepted various security warnings and prompts.
    • Not only did I choose to Enable Macros, but also accepted to make the renamed database a Trusted Document.
    • The previous file had also been marked as a Trusted Document.
  5. Successfully compile the VBA project without error, no changes to code.
  6. After the successful compile, I was able to close Access again, rename it back to the original filename. I had to reply to the same security prompts, but once I opened the VBA project it still compiled without error.

A little history of this case and observations:

  • I'm posting this answer because my observed symptoms were a little different than others and/or my solution seems unique.
  • At least during part of the time I experienced the error, my VBA window was showing two extra, "mysterious" projects. Regrettably I did not record the names before I resolved the error. One was something like ACXTOOLS. The modules inside could not be opened.
  • I think the original problem was indeed due to bad code since I had made major changes to a form before attempting to update its module code. But even after fixing the code the error persisted. I knew the code worked, because the form would load and no errors. As the original post states, the “User-defined type not defined” error would appear but it would not go to any offending line of code.
  • Prior to finding this error, I ensured all necessary references were added. I compacted and repaired the database more than once. I closed down Access and reopened the file numerous times between various fix attempts. I removed the suspected offending form, but still got the error. I tried other various steps suggested here and on other forums, but nothing fix the problem.
  • I stumbled upon this fix when I made a backup copy for attempting drastic measures, like deleting one form/module at a time. But upon opening the backup copy, the problem did not reoccur.

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

How can I bind a background color in WPF/XAML?

You can still use "Background" as the property name, as long as you give your window a name and use this name on the "Source" of the Binding.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Convert string to a variable name

There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

To convert a string to a variable:

x <- 42
eval(parse(text = "x"))
[1] 42

And the opposite:

x <- 42
deparse(substitute(x))
[1] "x"

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

For those looking for an answer and the others haven't worked, this might:

If you're using a component within a component (e.g. something like this in the Vue DOM):

App
  MyComponent
   ADifferentComponent
     MyComponent

Here the issue is that MyComponent is both the parent and child of itself. This throws Vue into a loop, with each component depending on the other.

There's a few solutions to this:

 1. Globally register MyComponent

vue.component("MyComponent", MyComponent)

2. Using beforeCreate

beforeCreate: function () {
  this.$options.components.MyComponent = require('./MyComponent.vue').default
}

3. Move the import into a lambda function within the components object

components: {
  MyComponent: () => import('./MyComponent.vue')
}

My preference is the third option, it's the simplest tweak and fixes the issue in my case.


More info: Vue.js Official Docs — Handling Edge Cases: Circular References Between Components

Note: if you choose method's 2 or 3, in my instance I had to use this method in both the parent and child components to stop this issue arising.

How do I call a non-static method from a static method in C#?

You can't call a non-static method without first creating an instance of its parent class.

So from the static method, you would have to instantiate a new object...

Vehicle myCar = new Vehicle();

... and then call the non-static method.

myCar.Drive();

Find and replace in file and overwrite file doesn't work, it empties the file

Warning: this is a dangerous method! It abuses the i/o buffers in linux and with specific options of buffering it manages to work on small files. It is an interesting curiosity. But don't use it for a real situation!

Besides the -i option of sed you can use the tee utility.

From man:

tee - read from standard input and write to standard output and files

So, the solution would be:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee | tee index.html

-- here the tee is repeated to make sure that the pipeline is buffered. Then all commands in the pipeline are blocked until they get some input to work on. Each command in the pipeline starts when the upstream commands have written 1 buffer of bytes (the size is defined somewhere) to the input of the command. So the last command tee index.html, which opens the file for writing and therefore empties it, runs after the upstream pipeline has finished and the output is in the buffer within the pipeline.

Most likely the following won't work:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee index.html

-- it will run both commands of the pipeline at the same time without any blocking. (Without blocking the pipeline should pass the bytes line by line instead of buffer by buffer. Same as when you run cat | sed s/bar/GGG/. Without blocking it's more interactive and usually pipelines of just 2 commands run without buffering and blocking. Longer pipelines are buffered.) The tee index.html will open the file for writing and it will be emptied. However, if you turn the buffering always on, the second version will work too.

How to get the device's IMEI/ESN programmatically in android?

The method getDeviceId() of TelephonyManager returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.

Java Code

package com.AndroidTelephonyManager;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView textDeviceID = (TextView)findViewById(R.id.deviceid);

    //retrieve a reference to an instance of TelephonyManager
    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    textDeviceID.setText(getDeviceID(telephonyManager));

}

String getDeviceID(TelephonyManager phonyManager){

 String id = phonyManager.getDeviceId();
 if (id == null){
  id = "not available";
 }

 int phoneType = phonyManager.getPhoneType();
 switch(phoneType){
 case TelephonyManager.PHONE_TYPE_NONE:
  return "NONE: " + id;

 case TelephonyManager.PHONE_TYPE_GSM:
  return "GSM: IMEI=" + id;

 case TelephonyManager.PHONE_TYPE_CDMA:
  return "CDMA: MEID/ESN=" + id;

 /*
  *  for API Level 11 or above
  *  case TelephonyManager.PHONE_TYPE_SIP:
  *   return "SIP";
  */

 default:
  return "UNKNOWN: ID=" + id;
 }

}
}

XML

<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<textview android:id="@+id/deviceid" android:layout_height="wrap_content" android:layout_width="fill_parent">
</textview></textview></linearlayout> 

Permission Required READ_PHONE_STATE in manifest file.

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

How to uncommit my last commit in Git

If you commit to the wrong branch

While on the wrong branch:

  1. git log -2 gives you hashes of 2 last commits, let's say $prev and $last
  2. git checkout $prev checkout correct commit
  3. git checkout -b new-feature-branch creates a new branch for the feature
  4. git cherry-pick $last patches a branch with your changes

Then you can follow one of the methods suggested above to remove your commit from the first branch.

svn over HTTP proxy

svn:// doesn't talk http, therefor there's nothing a http proxy could do.

Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.

Rename all files in a folder with a prefix in a single command

You can just use -i instead of -I {}

ls | xargs -i mv {} unix_{}

This also works perfectly.

  • ls - lists all the files in the directory
  • xargs - accepts all files line by line due to the -i option
  • {} is the placeholder for all files, necessary if xargs gets more than two arguments as input

Using awk:

ls -lrt | grep '^-' | awk '{print "mv "$9" unix_"$9""}' | sh

Determining whether an object is a member of a collection in VBA

this version works for primitive types and for classes (short test-method included)

' TODO: change this to the name of your module
Private Const sMODULE As String = "MVbaUtils"

Public Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean
    Const scSOURCE As String = "ExistsInCollection"

    Dim lErrNumber As Long
    Dim sErrDescription As String

    lErrNumber = 0
    sErrDescription = "unknown error occurred"
    Err.Clear
    On Error Resume Next
        ' note: just access the item - no need to assign it to a dummy value
        ' and this would not be so easy, because we would need different
        ' code depending on the type of object
        ' e.g.
        '   Dim vItem as Variant
        '   If VarType(oCollection.Item(sKey)) = vbObject Then
        '       Set vItem = oCollection.Item(sKey)
        '   Else
        '       vItem = oCollection.Item(sKey)
        '   End If
        oCollection.Item sKey
        lErrNumber = CLng(Err.Number)
        sErrDescription = Err.Description
    On Error GoTo 0

    If lErrNumber = 5 Then ' 5 = not in collection
        ExistsInCollection = False
    ElseIf (lErrNumber = 0) Then
        ExistsInCollection = True
    Else
        ' Re-raise error
        Err.Raise lErrNumber, mscMODULE & ":" & scSOURCE, sErrDescription
    End If
End Function

Private Sub Test_ExistsInCollection()
    Dim asTest As New Collection

    Debug.Assert Not ExistsInCollection(asTest, "")
    Debug.Assert Not ExistsInCollection(asTest, "xx")

    asTest.Add "item1", "key1"
    asTest.Add "item2", "key2"
    asTest.Add New Collection, "key3"
    asTest.Add Nothing, "key4"
    Debug.Assert ExistsInCollection(asTest, "key1")
    Debug.Assert ExistsInCollection(asTest, "key2")
    Debug.Assert ExistsInCollection(asTest, "key3")
    Debug.Assert ExistsInCollection(asTest, "key4")
    Debug.Assert Not ExistsInCollection(asTest, "abcx")

    Debug.Print "ExistsInCollection is okay"
End Sub

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.

My initial wrong XSD was alike the following:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

The good XSD format for my migration to succeed was the following:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

And so on for every similar XSD nodes.

Changing route doesn't scroll to top in the new page

None of the answer provided solved my issue. I am using an animation between views and the scrolling would always happen after the animation. The solution I found so that the scrolling to the top happen before the animation is the following directive:

yourModule.directive('scrollToTopBeforeAnimation', ['$animate', function ($animate) {
    return {
        restrict: 'A',
        link: function ($scope, element) {
            $animate.on('enter', element, function (element, phase) {

                if (phase === 'start') {

                    window.scrollTo(0, 0);
                }

            })
        }
    };
}]);

I inserted it on my view as follows:

<div scroll-to-top-before-animation>
    <div ng-view class="view-animation"></div>
</div>

How to install both Python 2.x and Python 3.x in Windows

Here's what you can do:

Install cmder. Open and use Cmder as you would with you cmd terminal. Use the command alias to create command aliases.

I did the following:

alias python2 = c:\python27\python.exe
alias python3 = c:\python34\python.exe

And that's it! ;-)

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

Back button and refreshing previous activity

 @Override
protected void onRestart() {
    super.onRestart();
    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);
}

In previous activity use this code. This will do a smooth transition and reload the activity when you come back by pressing back button.

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

JavaFX Location is not set error message

I had this problem and found this post. My issue was just a file name issue.

FXMLLoader(getClass().getResource("/com/companyname/reports/" +
report.getClass().getCanonicalName().substring(18).replaceAll("Controller", "") +
".fxml"));

Parent root = (Parent) loader.load();

I have an xml that this is all coming from and I have made sure that my class is the same as the fxml file less the word controller.

I messed up the substring so the path was wrong...sure enough after I fixed the file name it worked.

To make a long story short I think that the problem is either the filename is named improperly or the path is wrong.

ADDITION: I have since moved to a Maven Project. The non Maven way is to have everything inside of your project path. The Maven way which was listed in the answer below was a bit frustrating at the start but I made a change to my code as follows:

FXMLLoader loader = new FXMLLoader(ReportMenu.this.getClass().getResource("/fxml/" + report.getClass().getCanonicalName().substring(18).replaceAll("Controller", "") + ".fxml"));

How can I add an item to a SelectList in ASP.net MVC

private SelectList AddFirstItem(SelectList list)
        {
            List<SelectListItem> _list = list.ToList();
            _list.Insert(0, new SelectListItem() { Value = "-1", Text = "This Is First Item" });
            return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text");
        }

This Should do what you need ,just send your selectlist and it will return a select list with an item in index 0

You can custome the text,value or even the index of the item you need to insert

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

How to prevent Browser cache on Angular 2 site?

I had similar issue with the index.html being cached by the browser or more tricky by middle cdn/proxies (F5 will not help you).

I looked for a solution which verifies 100% that the client has the latest index.html version, luckily I found this solution by Henrik Peinar:

https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c

The solution solve also the case where the client stays with the browser open for days, the client checks for updates on intervals and reload if newer version deployd.

The solution is a bit tricky but works like a charm:

  • use the fact that ng cli -- prod produces hashed files with one of them called main.[hash].js
  • create a version.json file that contains that hash
  • create an angular service VersionCheckService that checks version.json and reload if needed.
  • Note that a js script running after deployment creates for you both version.json and replace the hash in angular service, so no manual work needed, but running post-build.js

Since Henrik Peinar solution was for angular 4, there were minor changes, I place also the fixed scripts here:

VersionCheckService :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class VersionCheckService {
    // this will be replaced by actual hash post-build.js
    private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';

    constructor(private http: HttpClient) {}

    /**
     * Checks in every set frequency the version of frontend application
     * @param url
     * @param {number} frequency - in milliseconds, defaults to 30 minutes
     */
    public initVersionCheck(url, frequency = 1000 * 60 * 30) {
        //check for first time
        this.checkVersion(url); 

        setInterval(() => {
            this.checkVersion(url);
        }, frequency);
    }

    /**
     * Will do the call and check if the hash has changed or not
     * @param url
     */
    private checkVersion(url) {
        // timestamp these requests to invalidate caches
        this.http.get(url + '?t=' + new Date().getTime())
            .subscribe(
                (response: any) => {
                    const hash = response.hash;
                    const hashChanged = this.hasHashChanged(this.currentHash, hash);

                    // If new version, do something
                    if (hashChanged) {
                        // ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
                        // for an example: location.reload();
                        // or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
                    }
                    // store the new hash so we wouldn't trigger versionChange again
                    // only necessary in case you did not force refresh
                    this.currentHash = hash;
                },
                (err) => {
                    console.error(err, 'Could not get version');
                }
            );
    }

    /**
     * Checks if hash has changed.
     * This file has the JS hash, if it is a different one than in the version.json
     * we are dealing with version change
     * @param currentHash
     * @param newHash
     * @returns {boolean}
     */
    private hasHashChanged(currentHash, newHash) {
        if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
            return false;
        }

        return currentHash !== newHash;
    }
}

change to main AppComponent:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    constructor(private versionCheckService: VersionCheckService) {

    }

    ngOnInit() {
        console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
        if (environment.versionCheckUrl) {
            this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
        }
    }

}

The post-build script that makes the magic, post-build.js:

const path = require('path');
const fs = require('fs');
const util = require('util');

// get application version from package.json
const appVersion = require('../package.json').version;

// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);

console.log('\nRunning post-build tasks');

// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');

let mainHash = '';
let mainBundleFile = '';

// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;

// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
  .then(files => {
    mainBundleFile = files.find(f => mainBundleRegexp.test(f));

    if (mainBundleFile) {
      let matchHash = mainBundleFile.match(mainBundleRegexp);

      // if it has a hash in it's name, mark it down
      if (matchHash.length > 1 && !!matchHash[1]) {
        mainHash = matchHash[1];
      }
    }

    console.log(`Writing version and hash to ${versionFilePath}`);

    // write current version and hash into the version.json file
    const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
    return writeFile(versionFilePath, src);
  }).then(() => {
    // main bundle file not found, dev build?
    if (!mainBundleFile) {
      return;
    }

    console.log(`Replacing hash in the ${mainBundleFile}`);

    // replace hash placeholder in our main.js file so the code knows it's current hash
    const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
    return readFile(mainFilepath, 'utf8')
      .then(mainFileData => {
        const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
        return writeFile(mainFilepath, replacedFile);
      });
  }).catch(err => {
    console.log('Error with post build:', err);
  });

simply place the script in (new) build folder run the script using node ./build/post-build.js after building dist folder using ng build --prod

wget can't download - 404 error

I had the same problem. Solved using single quotes like this:

$ wget 'http://www.icerts.com/images/logo.jpg'

wget version in use:

$ wget --version
GNU Wget 1.11.4 Red Hat modified

Cycles in family tree software

The most important thing is to avoid creating a problem, so I believe that you should use a direct relation to avoid having a cycle.

As @markmywords said, #include "fritzl.h".

Finally I have to say recheck your data structure. Maybe something is going wrong over there (maybe a bidirectional linked list solves your problem).

How to switch between frames in Selenium WebDriver using Java

to switchto a frame:

driver.switchTo.frame("Frame_ID");

to switch to the default again.

driver.switchTo().defaultContent();

Can I map a hostname *and* a port with /etc/hosts?

If you really need to do this, use reverse proxy.

For example, with nginx as reverse proxy

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

Invalid hook call. Hooks can only be called inside of the body of a function component

You can use "export default" by calling an Arrow Function that returns its React.Component by passing it through the MaterialUI class object props, which in turn will be used within the Component render ().

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}

export default () => {
    const classes = useStyles();
    return (
        <AllowanceClass classes={classes} />
    )
}

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

How can I build for release/distribution on the Xcode 4?

To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.

Then you see a clear choice.

The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Sounds like your initialized AudioElement class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress in state.

You can either initialize the AudioElement class object in a new React component or just convert that class to a React component.

class MyAudioPlayer extends React.Component {
  constructor(props) {
    super(props);

    this.player = new AudioElement('test.mp3');

    this.player.audio.ontimeupdate = this.updateProgress;
  }

  updateProgress () {
    // Dispatch action to reducer with updated progress.
    // You might want to actually send the current time and do the
    // calculation from within the reducer.
    this.props.updateProgressAction();
  }

  render () {
    // Render the audio player controls, progress bar, whatever else
    return <p>Progress: {this.props.progress}</p>;
  }
}

class MyContainer extends React.Component {
   render() {
     return <MyAudioPlayer updateProgress={this.props.updateProgress} />
   }
}

function mapStateToProps (state) { return {}; }

return connect(mapStateToProps, {
  updateProgressAction
})(MyContainer);

Note that the updateProgressAction is automatically wrapped with dispatch so you don't need to call dispatch directly.

Simple division in Java - is this a bug or a feature?

You've used integers in the expression 7/10, and integer 7 divided by integer 10 is zero.

What you're expecting is floating point division. Any of the following would evaluate the way you expected:

7.0 / 10
7 / 10.0
7.0 / 10.0
7 / (double) 10

Simulate Keypress With jQuery

This works:

var event = jQuery.Event('keypress');
event.which = 13; 
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event); 

CSS for grabbing cursors (drag & drop)

"more custom" than CSS cursors means a plugin of some type, but you can totally specify your own cursors using CSS. I think this list has what you want:

_x000D_
_x000D_
.alias {cursor: alias;}_x000D_
.all-scroll {cursor: all-scroll;}_x000D_
.auto {cursor: auto;}_x000D_
.cell {cursor: cell;}_x000D_
.context-menu {cursor: context-menu;}_x000D_
.col-resize {cursor: col-resize;}_x000D_
.copy {cursor: copy;}_x000D_
.crosshair {cursor: crosshair;}_x000D_
.default {cursor: default;}_x000D_
.e-resize {cursor: e-resize;}_x000D_
.ew-resize {cursor: ew-resize;}_x000D_
.grab {cursor: grab;}_x000D_
.grabbing {cursor: grabbing;}_x000D_
.help {cursor: help;}_x000D_
.move {cursor: move;}_x000D_
.n-resize {cursor: n-resize;}_x000D_
.ne-resize {cursor: ne-resize;}_x000D_
.nesw-resize {cursor: nesw-resize;}_x000D_
.ns-resize {cursor: ns-resize;}_x000D_
.nw-resize {cursor: nw-resize;}_x000D_
.nwse-resize {cursor: nwse-resize;}_x000D_
.no-drop {cursor: no-drop;}_x000D_
.none {cursor: none;}_x000D_
.not-allowed {cursor: not-allowed;}_x000D_
.pointer {cursor: pointer;}_x000D_
.progress {cursor: progress;}_x000D_
.row-resize {cursor: row-resize;}_x000D_
.s-resize {cursor: s-resize;}_x000D_
.se-resize {cursor: se-resize;}_x000D_
.sw-resize {cursor: sw-resize;}_x000D_
.text {cursor: text;}_x000D_
.url {cursor: url(https://www.w3schools.com/cssref/myBall.cur),auto;}_x000D_
.w-resize {cursor: w-resize;}_x000D_
.wait {cursor: wait;}_x000D_
.zoom-in {cursor: zoom-in;}_x000D_
.zoom-out {cursor: zoom-out;}
_x000D_
<h1>The cursor Property</h1>_x000D_
<p>Hover mouse over each to see how the cursor looks</p>_x000D_
_x000D_
<p class="alias">cursor: alias</p>_x000D_
<p class="all-scroll">cursor: all-scroll</p>_x000D_
<p class="auto">cursor: auto</p>_x000D_
<p class="cell">cursor: cell</p>_x000D_
<p class="context-menu">cursor: context-menu</p>_x000D_
<p class="col-resize">cursor: col-resize</p>_x000D_
<p class="copy">cursor: copy</p>_x000D_
<p class="crosshair">cursor: crosshair</p>_x000D_
<p class="default">cursor: default</p>_x000D_
<p class="e-resize">cursor: e-resize</p>_x000D_
<p class="ew-resize">cursor: ew-resize</p>_x000D_
<p class="grab">cursor: grab</p>_x000D_
<p class="grabbing">cursor: grabbing</p>_x000D_
<p class="help">cursor: help</p>_x000D_
<p class="move">cursor: move</p>_x000D_
<p class="n-resize">cursor: n-resize</p>_x000D_
<p class="ne-resize">cursor: ne-resize</p>_x000D_
<p class="nesw-resize">cursor: nesw-resize</p>_x000D_
<p class="ns-resize">cursor: ns-resize</p>_x000D_
<p class="nw-resize">cursor: nw-resize</p>_x000D_
<p class="nwse-resize">cursor: nwse-resize</p>_x000D_
<p class="no-drop">cursor: no-drop</p>_x000D_
<p class="none">cursor: none</p>_x000D_
<p class="not-allowed">cursor: not-allowed</p>_x000D_
<p class="pointer">cursor: pointer</p>_x000D_
<p class="progress">cursor: progress</p>_x000D_
<p class="row-resize">cursor: row-resize</p>_x000D_
<p class="s-resize">cursor: s-resize</p>_x000D_
<p class="se-resize">cursor: se-resize</p>_x000D_
<p class="sw-resize">cursor: sw-resize</p>_x000D_
<p class="text">cursor: text</p>_x000D_
<p class="url">cursor: url</p>_x000D_
<p class="w-resize">cursor: w-resize</p>_x000D_
<p class="wait">cursor: wait</p>_x000D_
<p class="zoom-in">cursor: zoom-in</p>_x000D_
<p class="zoom-out">cursor: zoom-out</p>
_x000D_
_x000D_
_x000D_

Source: CSS cursor Property @ W3Schools

Define: What is a HashSet?

    1. A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here

    2. HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here

  1. There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

The HashSet class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.

The only catch of HashSet is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet into a List and iterate through that. Take a look here

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

Close all infowindows in Google Maps API v3

For loops that creates infowindows dynamically, declare a global variable

var openwindow;

and then in the addListenerfunction call (which is within the loop):

google.maps.event.addListener(marker<?php echo $id; ?>, 'click', function() {
if(openwindow){
    eval(openwindow).close();
}
openwindow="myInfoWindow<?php echo $id; ?>";
myInfoWindow<?php echo $id; ?>.open(map, marker<?php echo $id; ?>);
});

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

How to call a method after bean initialization is complete?

You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).

Difference between return and exit in Bash functions

In simple words (mainly for newbie in coding), we can say,

    `return`: exits the function,
    `exit()`: exits the program (called as process while running)

Also if you observed, this is very basic, but...,

    `return`: is the keyword
    `exit()`: is the function

How can I convert an Integer to localized month name in Java?

Just inserting the line

DateFormatSymbols.getInstance().getMonths()[view.getMonth()] 

will do the trick.

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

Maximum request length exceeded.

It may be worth noting that you may want to limit this change to the URL you expect to be used for the upload rather then your entire site.

<location path="Documents/Upload">
  <system.web>
    <!-- 50MB in kilobytes, default is 4096 or 4MB-->
    <httpRuntime maxRequestLength="51200" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- 50MB in bytes, default is 30000000 or approx. 28.6102 Mb-->
        <requestLimits maxAllowedContentLength="52428800" /> 
      </requestFiltering>
    </security>
  </system.webServer>
</location>

How to get Month Name from Calendar?

You can get it one line like this: String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

Firebug like plugin for Safari browser

Why do you want to use Firebug if Safari already comes with great Developer tools? :)

As Matt said, you can enable them from the preferences menu.

Here you will find an overview, summarized, of the Safari's Web inspector, and how to use it:

Javascript isnull

Why not try .test() ? ... Try its and best boolean (true or false):

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)');
    return results.test(window.location.href);
}

Tutorial: http://www.w3schools.com/jsref/jsref_regexp_test.asp

Continue For loop

A lot of years after... I like this one:

For x = LBound(arr) To UBound(arr): Do

    sname = arr(x)  
    If instr(sname, "Configuration item") Then Exit Do 

    '// other code to copy past and do various stuff

Loop While False: Next x

Print a file, skipping the first X lines, in Bash

If you want to skip first two line:

tail -n +3 <filename>

If you want to skip first x line:

tail -n +$((x+1)) <filename>

jquery find closest previous sibling with class

Try

$('li.current_sub').prev('.par_cat').[do stuff];

Get text of the selected option with jQuery

You could actually put the value = to the text and then do

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("#select_2 option:selected").html();
        alert(val);
    });
});

Or what I did on a similar case was

<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
  with you're options here
</select>

With this second option you should have a undefined. Give me feedback if it worked :)

Patrick

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

Since the syntaxes are equivalent (in MySQL anyhow), I prefer the INSERT INTO table SET x=1, y=2 syntax, since it is easier to modify and easier to catch errors in the statement, especially when inserting lots of columns. If you have to insert 10 or 15 or more columns, it's really easy to mix something up using the (x, y) VALUES (1,2) syntax, in my opinion.

If portability between different SQL standards is an issue, then maybe INSERT INTO table (x, y) VALUES (1,2) would be preferred.

And if you want to insert multiple records in a single query, it doesn't seem like the INSERT INTO ... SET syntax will work, whereas the other one will. But in most practical cases, you're looping through a set of records to do inserts anyhow, though there could be some cases where maybe constructing one large query to insert a bunch of rows into a table in one query, vs. a query for each row, might have a performance improvement. Really don't know.

How to join two JavaScript Objects, without using JQUERY

Just another solution using underscore.js:

_.extend({}, obj1, obj2);

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

create a text file using javascript

That works better with this :

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

Can't get Python to import from a different folder

You're missing __init__.py. From the Python tutorial:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Put an empty file named __init__.py in your Models directory, and all should be golden.

jquery, selector for class within id

I think your asking to select only <span class = "my_class">hello</span> this element, You have do like this, If I am understand your question correctly this is the answer,

$("#my_id [class='my_class']").addClass('test');

DEMO

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

:last is not part of the css spec, this is jQuery specific.

you should be looking for last-child

var first = div.querySelector('[move_id]:first-child');
var last  = div.querySelector('[move_id]:last-child');

Extract Number from String in Python

I am a beginner in coding. This is my attempt to answer the questions. Used Python3.7 version without importing any libraries.

This code extracts and returns a decimal number from a string made of sets of characters separated by blanks (words).

Attention: In case there are more than one number, it returns the last value.

line = input ('Please enter your string ')
for word in line.split():
    try:
        a=float(word)
        print (a)
    except ValueError:
        pass

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

How to get ER model of database from server with Workbench

  1. Migrate your DB "simply make sure the tables and columns exist".
  2. Recommended to delete all your data (this freezes MySQL Workbench on my MAC everytime due to "software out of memory..")

  1. Open MySQL Workbench
  2. click + to make MySQL connection
  3. enter credentials and connect
  4. go to database tab
  5. click reverse engineer
  6. follow the wizard Next > Next ….
  7. DONE :)
  8. now you can click the arrange tab then choose auto-layout (keep clicking it until you are satisfied with the result)

git: updates were rejected because the remote contains work that you do not have locally

It happens when we are trying to push to remote repository but has created a new file on remote which has not been pulled yet, let say Readme. In that case as the error says

git rejects the update

as we have not taken updated remote in our local environment. So Take pull first from remote

git pull

It will update your local repository and add a new Readme file. Then Push updated changes to remote

git push origin master

A generic list of anonymous class

Not exactly, but you can say List<object> and things will work. However, list[0].Id won't work.

This will work at runtime in C# 4.0 by having a List<dynamic>, that is you won't get IntelliSense.

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

Python matplotlib multiple bars

I did this solution: if you want plot more than one plot in one figure, make sure before plotting next plots you have set right matplotlib.pyplot.hold(True) to able adding another plots.

Concerning the datetime values on the X axis, a solution using the alignment of bars works for me. When you create another bar plot with matplotlib.pyplot.bar(), just use align='edge|center' and set width='+|-distance'.

When you set all bars (plots) right, you will see the bars fine.

Android webview slow

None of those answers was not helpful for me.

Finally I have found reason and solution. The reason was a lot of CSS3 filters (filter, -webkit-filter).

Solution

I have added detection of WebView in web page script in order to add class "lowquality" to HTML body. BTW. You can easily track WebView by setting user-agent in WebView settings. Then I created new CSS rule

body.lowquality * { filter: none !important; }

How does the compilation/linking process work?

The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.

First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.

If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.

A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.

So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.

That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.

Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.

What is the difference between a strongly typed language and a statically typed language?

Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.

What is Strongly typed VS Weakly typed?

Strongly Typed: Will not be automatically converted from one type to another

In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".

Weakly (loosely) Typed: Will be automatically converted to one type to another: Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.

Perl Example:

my $a = "2" + 8;
print $a,"\n";

Save it to main.pl and run perl main.pl and you will get output 10.

What is Static VS Dynamic type?

In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

What is this means?

In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

Save this file in main.go and run it, you will get compilation failed message for this.

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

You will see following output

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

How to trigger event in JavaScript?

The accepted answer didn’t work for me, none of the createEvent ones did.

What worked for me in the end was:

targetElement.dispatchEvent(
    new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
}));

Here’s a snippet:

_x000D_
_x000D_
const clickBtn = document.querySelector('.clickme');_x000D_
const viaBtn = document.querySelector('.viame');_x000D_
_x000D_
viaBtn.addEventListener('click', function(event) {_x000D_
    clickBtn.dispatchEvent(_x000D_
        new MouseEvent('click', {_x000D_
            bubbles: true,_x000D_
            cancelable: true,_x000D_
            view: window,_x000D_
    }));_x000D_
});_x000D_
_x000D_
clickBtn.addEventListener('click', function(event) {_x000D_
    console.warn(`I was accessed via the other button! A ${event.type} occurred!`);_x000D_
});
_x000D_
<button class="clickme">Click me</button>_x000D_
_x000D_
<button class="viame">Via me</button>
_x000D_
_x000D_
_x000D_

From reading: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

How to add white spaces in HTML paragraph

You can try it by adding &nbsp;

How can I format a decimal to always show 2 decimal places?

I suppose you're probably using the Decimal() objects from the decimal module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)

If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:

Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?

A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

The next question reads

Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?

If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimals with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str will work fine:

str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'

Convert char * to LPWSTR

I'm using the following in VC++ and it works like a charm for me.

CA2CT(charText)

How to format DateTime in Flutter , How to get current time in flutter?

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Difference between SurfaceView and View?

Views are all drawn on the same GUI thread which is also used for all user interaction.

So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.

Dynamic SELECT TOP @var In SQL Server

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

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

How to create JNDI context in Spring Boot with Embedded Tomcat Container

After all i got the answer thanks to wikisona, first the beans:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

        @Override
        protected void postProcessContext(Context context) {
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "your.db.Driver");
            resource.setProperty("url", "jdbc:yourDb");

            context.getNamingResources().addResource(resource);
        }
    };
}

@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

After you've installed the package (link if you haven't), add the path to dot.exe as a new system variable.

Default path is:

C:\Program Files (x86)\Graphviz2.38\bin\dot.exe

enter image description here

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

in controller just convert json data to object using json_decode php function like this

$member = json_decode($json_string); 

and pass to view in view

return view('page',compact('$member'))

in view blade

Member ID: {{$member->member[0]->id}}
Firstname: {{$member->member[0]->firstname}}
Lastname: {{$member->member[0]->lastname}}
Phone: {{$member->member[0]->phone}}

Owner ID: {{$member->owner[0]->id}}
Firstname: {{$member->owner[0]->firstname}}
Lastname: {{$member->owner[0]->lastname}}

Using NSLog for debugging

Use NSLog() like this:

NSLog(@"The code runs through here!");

Or like this - with placeholders:

float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);

In NSLog() you can use it like + (id)stringWithFormat:(NSString *)format, ...

float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];

You can add other placeholders, too:

float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);

How to use clock() in C++

clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;

How to sort multidimensional array by column?

You can use the sorted method with a key.

sorted(a, key=lambda x : x[1])

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

href image link download on click

No, it isn't. You will need something on the server to send a Content-Disposition header to set the file as an attachment instead of being inline. You could do this with plain Apache configuration though.

I've found an example of doing it using mod_rewrite, although I know there is a simpler way.

Generating random integer from a range

int RandU(int nMin, int nMax)
{
    return nMin + (int)((double)rand() / (RAND_MAX+1) * (nMax-nMin+1));
}

This is a mapping of 32768 integers to (nMax-nMin+1) integers. The mapping will be quite good if (nMax-nMin+1) is small (as in your requirement). Note however that if (nMax-nMin+1) is large, the mapping won't work (For example - you can't map 32768 values to 30000 values with equal probability). If such ranges are needed - you should use a 32-bit or 64-bit random source, instead of the 15-bit rand(), or ignore rand() results which are out-of-range.

Filename too long in Git for Windows

If you are working with your encrypted partition, consider moving the folder to an unencrypted partition, for example a /tmp, running git pull, and then moving back.

Progress Bar with HTML and CSS

_x000D_
_x000D_
#progressbar {_x000D_
  background-color: black;_x000D_
  border-radius: 13px;_x000D_
  /* (height of inner div) / 2 + padding */_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
#progressbar>div {_x000D_
  background-color: orange;_x000D_
  width: 40%;_x000D_
  /* Adjust with JavaScript */_x000D_
  height: 20px;_x000D_
  border-radius: 10px;_x000D_
}
_x000D_
<div id="progressbar">_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

(EDIT: Changed Syntax highlight; changed descendant to child selector)

TypeError: 'str' object is not callable (Python)

it is recommended not to use str int list etc.. as variable names, even though python will allow it. this is because it might create such accidents when trying to access reserved keywords that are named the same

javascript check for not null

It's because val is not null, but contains 'null' as a string.

Try to check with 'null'

if ('null' != val)

For an explanation of when and why this works, see the details below.

urlencode vs rawurlencode?

I believe spaces must be encoded as:

  • %20 when used inside URL path component
  • + when used inside URL query string component or form data (see 17.13.4 Form content types)

The following example shows the correct use of rawurlencode and urlencode:

echo "http://example.com"
    . "/category/" . rawurlencode("latest songs")
    . "/search?q=" . urlencode("lady gaga");

Output:

http://example.com/category/latest%20songs/search?q=lady+gaga

What happens if you encode path and query string components the other way round? For the following example:

http://example.com/category/latest+songs/search?q=lady%20gaga
  • The webserver will look for the directory latest+songs instead of latest songs
  • The query string parameter q will contain lady gaga

ModelState.IsValid == false, why?

The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.

How to use a DataAdapter with stored procedure and parameter

   public DataSet Myfunction(string Myparameter)
    {
        config.cmd.Connection = config.cnx;
        config.cmd.CommandText = "ProcName";
        config.cmd.CommandType = CommandType.StoredProcedure;
        config.cmd.Parameters.Add("parameter", SqlDbType.VarChar, 10);
        config.cmd.Parameters["parameter"].Value = Myparameter;

        config.dRadio = new SqlDataAdapter(config.cmd);
        config.dRadio.Fill(config.ds,"Table");

        return config.ds;


    }

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

In this case, one of the easiest and best approach is to first cast it to list and then use where or select.

result = result.ToList().where(p => date >= p.DOB);

Execute action when back bar button of UINavigationController is pressed

override func willMove(toParent parent: UIViewController?)
{
    super.willMove(toParent: parent)
    if parent == nil
    {
        print("This VC is 'will' be popped. i.e. the back button was pressed.")
    }
}

How to use @Nullable and @Nonnull annotations more effectively?

Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:

    directPathToA(y);
                  ^
Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'

This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA() has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.

And when using a clever @NonNullByDefault we don't even have to say this every time.

In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.

Download a single folder or directory from a GitHub repo

A straightforward answer to this is to first tortoise svn from following link.

https://tortoisesvn.net/downloads.html

while installation turn on CLI option, so that it can be used from command line interface.

copy the git hub sub directory link.

Example

https://github.com/tensorflow/models/tree/master/research/deeplab

replace tree/master with trunk

https://github.com/tensorflow/models/trunk/research/deeplab

and do

svn checkout https://github.com/tensorflow/models/trunk/research/deeplab

files will be downloaded to the deeplab folder in the current directory.

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

How to use WebRequest to POST some data and read response?

Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

StringBuilder sb = new StringBuilder();
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
    request.Referer = "http://www.yourdomain.com";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    Char[] readBuffer = new Char[256];
    int count = reader.Read(readBuffer, 0, 256);

    while (count > 0)
    {
        String output = new String(readBuffer, 0, count);
        sb.Append(output);
        count = reader.Read(readBuffer, 0, 256);
    }
    string xml = sb.ToString();

Copy a table from one database to another in Postgres

Extract the table and pipe it directly to the target database:

pg_dump -t table_to_copy source_db | psql target_db

Note: If the other database already has the table set up, you should use the -a flag to import data only, else you may see weird errors like "Out of memory":

pg_dump -a -t my_table my_db | psql target_db

How to grant remote access to MySQL for a whole subnet?

It looks like you can also use a netmask, e.g.

GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...

What is the difference between compileSdkVersion and targetSdkVersion?

The CompileSdkVersion is the version of the SDK platform your app works with for compilation, etc DURING the development process (you should always use the latest) This is shipped with the API version you are using

enter image description here

You will see this in your build.gradle file:

enter image description here

targetSdkVersion: contains the info your app ships with AFTER the development process to the app store that allows it to TARGET the SPECIFIED version of the Android platform. Depending on the functionality of your app, it can target API versions lower than the current.For instance, you can target API 18 even if the current version is 23.

Take a good look at this official Google page.

Parse JSON from JQuery.ajax success data

parse and convert it to js object that's it.

success: function(response) {
    var content = "";
    var jsondata = JSON.parse(response);
    for (var x = 0; x < jsonData.length; x++) {
        content += jsondata[x].Id;
        content += "<br>";
        content += jsondata[x].Name;
        content += "<br>";
    }
    $("#ProductList").append(content);
}

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

How do I get cURL to not show the progress bar?

I found that with curl 7.18.2 the download progress bar is not hidden with:

curl -s http://google.com > temp.html

but it is with:

curl -ss http://google.com > temp.html

PHP Echo text Color

And if you are using Command line on Windows, download a program ANSICON that enables console to accept color codes. ANSICON is available at https://github.com/adoxa/ansicon/releases

Setting background-image using jQuery CSS property

$('myObject').css({'background-image': 'url(imgUrl)',});

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

Do not want scientific notation on plot axis

You can use format or formatC to, ahem, format your axis labels.

For whole numbers, try

x <- 10 ^ (1:10)
format(x, scientific = FALSE)
formatC(x, digits = 0, format = "f")

If the numbers are convertable to actual integers (i.e., not too big), you can also use

formatC(x, format = "d")

How you get the labels onto your axis depends upon the plotting system that you are using.

Driver executable must be set by the webdriver.ie.driver system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

driver = new ChromeDriver();

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

I had this problem, it is for foreign-key

Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key

enter image description here

Hope that works!

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

Can you 'exit' a loop in PHP?

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

Android ACTION_IMAGE_CAPTURE Intent

To follow up on Yenchi's comment above, the OK button will also do nothing if the camera app can't write to the directory in question.

That means that you can't create the file in a place that's only writeable by your application (for instance, something under getCacheDir()) Something under getExternalFilesDir() ought to work, however.

It would be nice if the camera app printed an error message to the logs if it could not write to the specified EXTRA_OUTPUT path, but I didn't find one.

Function pointer as a member of a C struct

Allocate memory to hold chars.

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

typedef struct PString {
        char *chars;
        int (*length)(PString *self);
} PString;

int length(PString *self) {
    return strlen(self->chars);
}

PString *initializeString(int n) {
    PString *str = malloc(sizeof(PString));

    str->chars = malloc(sizeof(char) * n);
    str->length = length;

    str->chars[0] = '\0'; //add a null terminator in case the string is used before any other initialization.

    return str;
}

int main() {
    PString *p = initializeString(30);
    strcpy(p->chars, "Hello");
    printf("\n%d", p->length(p));
    return 0;
}

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

<form method="post" action="servletName">   
     <input type="submit" id="btn1" name="btn1"/>
     <input type="submit" id="btn2" name="btn2"/>
</form>  

on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

Group By Eloquent ORM

Laravel 5

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray();

C++ catching all exceptions

  1. Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.

  2. Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?

  3. Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.

  4. There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

Do Git tags only apply to the current branch?

We can create a tag for some past commit:

git tag [tag_name] [reference_of_commit]

eg:

git tag v1.0 5fcdb03

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

Remove title in Toolbar in appcompat-v7

Just adding an empty string in the label of <application> (not <activity>) in AndroidMenifest.xmllike that -

<application
            android:label=""
            android:theme="@style/AppTheme">
            <activity
             .
             .
             .
             .
            </activity>
    </application>

Java 11 package javax.xml.bind does not exist

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

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

See JEP 320 for more info.

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

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

Jakarta EE 8 update (Mar 2020)

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

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

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

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

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

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

Run cron job only if it isn't already running

The way I am doing it when I am running php scripts is:

The crontab:

* * * * * php /path/to/php/script.php &

The php code:

<?php
if (shell_exec('ps aux | grep ' . __FILE__ . ' | wc  -l') > 1) {
    exit('already running...');
}
// do stuff

This command is searching in the system process list for the current php filename if it exists the line counter (wc -l) will be greater then one because the search command itself containing the filename

so if you running php crons add the above code to the start of your php code and it will run only once.

Is there a NumPy function to return the first index of something in an array?

l.index(x) returns the smallest i such that i is the index of the first occurrence of x in the list.

One can safely assume that the index() function in Python is implemented so that it stops after finding the first match, and this results in an optimal average performance.

For finding an element stopping after the first match in a NumPy array use an iterator (ndenumerate).

In [67]: l=range(100)

In [68]: l.index(2)
Out[68]: 2

NumPy array:

In [69]: a = np.arange(100)

In [70]: next((idx for idx, val in np.ndenumerate(a) if val==2))
Out[70]: (2L,)

Note that both methods index() and next return an error if the element is not found. With next, one can use a second argument to return a special value in case the element is not found, e.g.

In [77]: next((idx for idx, val in np.ndenumerate(a) if val==400),None)

There are other functions in NumPy (argmax, where, and nonzero) that can be used to find an element in an array, but they all have the drawback of going through the whole array looking for all occurrences, thus not being optimized for finding the first element. Note also that where and nonzero return arrays, so you need to select the first element to get the index.

In [71]: np.argmax(a==2)
Out[71]: 2

In [72]: np.where(a==2)
Out[72]: (array([2], dtype=int64),)

In [73]: np.nonzero(a==2)
Out[73]: (array([2], dtype=int64),)

Time comparison

Just checking that for large arrays the solution using an iterator is faster when the searched item is at the beginning of the array (using %timeit in the IPython shell):

In [285]: a = np.arange(100000)

In [286]: %timeit next((idx for idx, val in np.ndenumerate(a) if val==0))
100000 loops, best of 3: 17.6 µs per loop

In [287]: %timeit np.argmax(a==0)
1000 loops, best of 3: 254 µs per loop

In [288]: %timeit np.where(a==0)[0][0]
1000 loops, best of 3: 314 µs per loop

This is an open NumPy GitHub issue.

See also: Numpy: find first index of value fast

Date minus 1 year?

On my website, to check if registering people is 18 years old, I simply used the following :

$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.

Hope it could help someone.

How to add "Maven Managed Dependencies" library in build path eclipse?

Likely quite simple but best way is to edit manually the file .classpath at the root of your project folder with something like

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
        </attributes>
    </classpathentry>

when you want to have jar in your WEB-IN/lib folder (case for a web app)

JAVA_HOME should point to a JDK not a JRE

This worked for me for Windows 10, Java 8_144.

If the path contains spaces, use the shortened path name. For example, C:\Progra~1\Java\jdk1.8.0_65

How to replace values at specific indexes of a python list?

Why not just:

map(s.__setitem__, a, m)

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

How to use __doPostBack()

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

ScalaTest in sbt: is there a way to run a single test without tags?

Just to simplify the example of Tyler.

test:-prefix is not needed.

So according to his example:

In the sbt-console:

testOnly *LoginServiceSpec

And in the terminal:

sbt "testOnly *LoginServiceSpec"

How to pass arguments to a Button command in Tkinter?

You need to use lambda:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

How can I generate UUID in C#

Here is a client side "sequential guid" solution.

http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate

using System;
using System.Runtime.InteropServices;


namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
    public static class Guid
    {

        /*

        Original Reference for Code:
        http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html

        */


        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out System.Guid guid);

        public static System.Guid NewGuid()
        {
            return CreateSequentialUuid();
        }


        public static System.Guid CreateSequentialUuid()
        {
            const int RPC_S_OK = 0;
            System.Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException("UuidCreateSequential failed: " + hr);
            return g;
        }


        /*

        Text From URL above:

        UuidCreateSequential (rpcrt4)

        Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
        To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
        . Summary
        Creates a new UUID 
        C# Signature:
        [DllImport("rpcrt4.dll", SetLastError=true)]
        static extern int UuidCreateSequential(out Guid guid);


        VB Signature:
        Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer


        User-Defined Types:
        None.

        Notes:
        Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.

        CoCreateGuid generates random-looking GUIDs like these:

        92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
        BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
        28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
        EBD133A6-6CF3-4ADA-B723-A8177B70D268
        B10A35C0-F012-4EC1-9D24-3CC91D2B7122



        UuidCreateSequential generates sequential GUIDs like these:

        19F287B4-8830-11D9-8BFC-000CF1ADC5B7
        19F287B5-8830-11D9-8BFC-000CF1ADC5B7
        19F287B6-8830-11D9-8BFC-000CF1ADC5B7
        19F287B7-8830-11D9-8BFC-000CF1ADC5B7
        19F287B8-8830-11D9-8BFC-000CF1ADC5B7



        Here is a summary of the differences in the output of UuidCreateSequential:

        The last six bytes reveal your MAC address 
        Several GUIDs generated in a row are sequential 
        Tips & Tricks:
        Please add some!

        Sample Code in C#:
        static Guid UuidCreateSequential()
        {
           const int RPC_S_OK = 0;
           Guid g;
           int hr = UuidCreateSequential(out g);
           if (hr != RPC_S_OK)
             throw new ApplicationException
               ("UuidCreateSequential failed: " + hr);
           return g;
        }



        Sample Code in VB:
        Sub Main()
           Dim myId As Guid
           Dim code As Integer
           code = UuidCreateSequential(myId)
           If code <> 0 Then
             Console.WriteLine("UuidCreateSequential failed: {0}", code)
           Else
             Console.WriteLine(myId)
           End If
        End Sub




        */








    }
}

Keywords: CreateSequentialUUID SequentialUUID

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

"Initializing" variables in python?

I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.

Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.

In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.

I'll make some notes and corrections to your code:

def main():
   # doc to define the function
   # proper Python indentation
   # document significant variables, especially inputs and outputs
   # grade_1, grade_2, grade_3, average - id these
   # year - id this
   # fName, lName, ID, converted_ID 

   infile = open("studentinfo.txt", "r") 
   # you didn't 'intialize' this variable

   data = infile.read()  
   # nor this  

   fName, lName, ID, year = data.split(",")
   # this will produce an error if the file does not have the right number of strings
   # 'year' is now a string, even though you 'initialized' it as 0

   year = int(year)
   # now 'year' is an integer
   # a language that requires initialization would have raised an error
   # over this switch in type of this variable.

   # Prompt the user for three test scores
   grades = eval(input("Enter the three test scores separated by a comma: "))
   # 'eval' ouch!
   # you could have handled the input just like you did the file input.

   grade_1, grade_2, grade_3 = grades   
   # this would work only if the user gave you an 'iterable' with 3 values
   # eval() doesn't ensure that it is an iterable
   # and it does not ensure that the values are numbers. 
   # What would happen with this user input: "'one','two','three',4"?

   # Create a username 
   uName = (lName[:4] + fName[:2] + str(year)).lower()

   converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
   # earlier you 'initialized' converted_ID
   # initialization in a static typed language would have caught this typo
   # pseudo-initialization in Python does not catch typos
   ....

How to resize a VirtualBox vmdk file

Since this is a vmdk file, you could use VMWare's vdiskmanager, if it's available for your platform. VMWare has x86 Linux, Windows, and OS X versions here (see "Attachments" on the right rail).

And then you just do:

1023856-vdiskmanager-windows-7.0.1.exe -x 30720M Machine-disk1.vmdk

It avoids having to clone, then expand the disk. Now, the downside is you need the extra tool, and vmdk is VMWare's disk format, and you're still using Virtualbox, so there could be incompatibilities.

qemu-img might also work, but I'm not sure if it supports resizing vmdk files. It would look something like:

qemu-img resize Machine-disk1.vmdk +8G

And just a reminder, with both, you still have to grow the partition after resizing the underlying disk. All these tools are essentially dd if=/dev/old_disk of=/dev/new_disk bs=16M.

How to set ssh timeout?

ssh -o ConnectTimeout=10  <hostName>

Where 10 is time in seconds. This Timeout applies only to the creation of the connection.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Winand, Quality was also an issue for me so I did this:

For Each ws In ActiveWorkbook.Worksheets
    If ws.PageSetup.PrintArea <> "" Then
        'Reverse the effects of page zoom on the exported image
        zoom_coef = 100 / ws.Parent.Windows(1).Zoom
        areas = Split(ws.PageSetup.PrintArea, ",")
        areaNo = 0
        For Each a In areas
            Set area = ws.Range(a)
            ' Change xlPrinter to xlScreen to see zooming white space
            area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
            Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
            chartobj.Chart.Paste
            'scale the image before export
            ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
            ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
            chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
            chartobj.delete
            areaNo = areaNo + 1
        Next
    End If
Next

See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.

doc

Xcode error "Could not find Developer Disk Image"

I personally downloaded Xcode 6.4 beta and 7.0 beta and I was very happy to find the solution by searching "8.4" inside the application folder of the 6.4 beta. By doing this, I found the folder 8.4 (12H4125a) containing the iOS 8.4 image and I copied this folder to the same path of the 7.0 beta. The path is the following:

/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport 

When you will reopen Xcode 7 and choose your device, there will be an error message; just click on fix issue and that should do it!

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

Set opacity of background image without affecting child elements

#footer ul li
     {
       position:relative;
       list-style:none;
     }
    #footer ul li:before
     {
       background-image: url(imagesFolder/bg_demo.png);
       background-repeat:no-repeat;
       content: "";
       top: 5px;
       left: -10px;
       bottom: 0;
       right: 0;
       position: absolute;
       z-index: -1;
       opacity: 0.5;
    }

You can try this code. I think it will be worked. You can visit the demo

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

JAX-WS - Adding SOAP Headers

Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:

The portable way of doing this is that you create a SOAPHandler and mess with SAAJ, but the RI provides a better way of doing this.

When you create a proxy or dispatch object, they implement BindingProvider interface. When you use the JAX-WS RI, you can downcast to WSBindingProvider which defines a few more methods provided only by the JAX-WS RI.

This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on Headers class to create one.

import com.sun.xml.ws.developer.WSBindingProvider;

HelloPort port = helloService.getHelloPort();  // or something like that...
WSBindingProvider bp = (WSBindingProvider)port;

bp.setOutboundHeader(
  // simple string value as a header, like <simpleHeader>stringValue</simpleHeader>
  Headers.create(new QName("simpleHeader"),"stringValue"),
  // create a header from JAXB object
  Headers.create(jaxbContext,myJaxbObject)
);

Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.

Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.

How do I open port 22 in OS X 10.6.7

I'm using OSX 10.11.6 and this article works for me.

enter image description here

Invalid argument supplied for foreach()

If you're using php7 and you want to handle only undefined errors this is the cleanest IMHO

$array = [1,2,3,4];
foreach ( $array ?? [] as $item ) {
  echo $item;
}

Parsing JSON using C

You can have a look at Jansson

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:

  • Simple and intuitive API and data model
  • Can both encode to and decode from JSON
  • Comprehensive documentation
  • No dependencies on other libraries
  • Full Unicode support (UTF-8)
  • Extensive test suite

Remove characters from a string

You can use replace function.

str.replace(regexp|substr, newSubstr|function)

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

Find if a textbox is disabled or not using jquery

You can use $(":disabled") to select all disabled items in the current context.

To determine whether a single item is disabled you can use $("#textbox1").is(":disabled").

MySQL Fire Trigger for both Insert and Update

In response to @Zxaos request, since we can not have AND/OR operators for MySQL triggers, starting with your code, below is a complete example to achieve the same.

1. Define the INSERT trigger:

DELIMITER //
DROP TRIGGER IF EXISTS my_insert_trigger//
CREATE DEFINER=root@localhost TRIGGER my_insert_trigger
    AFTER INSERT ON `table`
    FOR EACH ROW

BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    -- NEW.id is an example parameter passed to the procedure but is not required
    -- if you do not need to pass anything to your procedure.
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

2. Define the UPDATE trigger

DELIMITER //
DROP TRIGGER IF EXISTS my_update_trigger//

CREATE DEFINER=root@localhost TRIGGER my_update_trigger
    AFTER UPDATE ON `table`
    FOR EACH ROW
BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

3. Define the common PROCEDURE used by both these triggers:

DELIMITER //
DROP PROCEDURE IF EXISTS procedure_to_run_processes_due_to_changes_on_table//

CREATE DEFINER=root@localhost PROCEDURE procedure_to_run_processes_due_to_changes_on_table(IN table_row_id VARCHAR(255))
READS SQL DATA
BEGIN

    -- Write your MySQL code to perform when a `table` row is inserted or updated here

END//
DELIMITER ;

You note that I take care to restore the delimiter when I am done with my business defining the triggers and procedure.

Why is using "for...in" for array iteration a bad idea?

Because it enumerates through object fields, not indexes. You can get value with index "length" and I doubt you want this.

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

DISTINCT for only one column

Try this:

SELECT ID, Email, ProductName, ProductModel FROM Products WHERE ID IN (SELECT MAX(ID) FROM Products GROUP BY Email)

What Process is using all of my disk IO

TL;DR

If you can use iotop, do so. Else this might help.


Use top, then use these shortcuts:

d 1 = set refresh time from 3 to 1 second

1   = show stats for each cpu, not cumulated

This has to show values > 1.0 wa for at least one core - if there are no diskwaits, there is simply no IO load and no need to look further. Significant loads usually start > 15.0 wa.

x       = highlight current sort column 
< and > = change sort column
R       = reverse sort order

Chose 'S', the process status column. Reverse the sort order so the 'R' (running) processes are shown on top. If you can spot 'D' processes (waiting for disk), you have an indicator what your culprit might be.

Send values from one form to another form

// In form 1
public static string Username = Me;

// In form 2's load block
string _UserName = Form1.Username;

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Is it possible for UIStackView to scroll?

Up to date for 2020.

100% storyboard OR 100% code.


Here's the simplest possible explanation:

  1. Have a blank full-screen scene

  2. Add a scroll view. Control-drag from the scroll view to the base view, add left-right-top-bottom, all zero.

  3. Add a stack view in the scroll view. Control-drag from the stack view to the scroll view, add left-right-top-bottom, all zero.

  4. Put two or three labels inside the stack view.

For clarity, make the background color of the label red. Set the label height to 100.

  1. Now set the width of each UILabel:

    Surprisingly, control-drag from the UILabel to the scroll view, not to the stack view, and select equal widths.

To repeat:

Don't control drag from the UILabel to the UILabel's parent - go to the grandparent. (In other words, go all the way to the scroll view, do not go to the stack view.)

It's that simple. That's the secret.

Secret tip - Apple bug:

It will not work with only one item! Add a few labels to make the demo work.

You're done.

Tip: You must add a height to every new item. Every item in any scrolling stack view must have either an intrinsic size (such as a label) or add an explicit height constraint.


The alternative approach:

In the above: surprisingly, set the widths of the UILabels to the width of the scroll view (not the stack view).

Alternately...

Drag from the stack view to the scroll view, and add a "width equal" constraint. This seems strange because you already pinned left-right, but that is how you do it. No matter how strange it seems that's the secret.

So you have two options:

  1. Surprisingly, set the width of each item in the stack view to the width of the scrollview grandparent (not the stackview parent).

or

  1. Surprisingly, set a "width equal" of the stackview to the scrollview - even though you do have the left and right edges of the stackview pinned to the scrollview anyway.

To be clear, do ONE of those methods, do NOT do both.

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

How do I keep Python print from adding newlines or spaces?

sys.stdout.write is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:

print "a",
print "b",

This will print a b, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:

print "a",
sys.stdout.write("0")
print "b",

This will print a0b. How do you explain that? Where have the spaces gone?

I still can't quite make out what's really going on here. Could somebody look over my best guess:

My attempt at deducing the rules when you have a trailing , on your print:

First, let's assume that print , (in Python 2) doesn't print any whitespace (spaces nor newlines).

Python 2 does, however, pay attention to how you are printing - are you using print, or sys.stdout.write, or something else? If you make two consecutive calls to print, then Python will insist on putting in a space in between the two.

Commenting out a set of lines in a shell script

What if you just wrap your code into function?

So this:

cd ~/documents
mkdir test
echo "useless script" > about.txt

Becomes this:

CommentedOutBlock() {
  cd ~/documents
  mkdir test
  echo "useless script" > about.txt
}

php static function

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

Convert Pixels to Points

Starting with the given:

  • There are 72 points in an inch (that is what a point is, 1/72 of an inch)
  • on a system set for 150dpi, there are 150 pixels per inch.
  • 1 in = 72pt = 150px (for 150dpi setting)

If you want to find points (pt) based on pixels (px):

 72 pt    x pt
------ = -----                  (1) for 150dpi system
150 px    y px

Rearranging:

x = (y/150) * 72                (2) for 150dpi system

so:

points = (pixels / 150) * 72    (3) for 150dpi system

How to get changes from another branch

  1. go to the master branch our-team

    • git checkout our-team
  2. pull all the new changes from our-team branch

    • git pull
  3. go to your branch featurex

    • git checkout featurex
  4. merge the changes of our-team branch into featurex branch

    • git merge our-team
    • or git cherry-pick {commit-hash} if you want to merge specific commits
  5. push your changes with the changes of our-team branch

    • git push

Note: probably you will have to fix conflicts after merging our-team branch into featurex branch before pushing

How to check if pytorch is using the GPU?

Create a tensor on the GPU as follows:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

Do not quit, open another terminal and check if the python process is using the GPU using:

$ nvidia-smi

HTML <input type='file'> File Selection Event

jQuery way:

$('input[name=myInputName]').change(function(ev) {

    // your code
});

Compare dates in MySQL

You can try below query,

select * from players
where 
    us_reg_date between '2000-07-05'
and
    DATE_ADD('2011-11-10',INTERVAL 1 DAY)

Check if a string is html or not

There are fancy solutions involving utilizing the browser itself to attempt to parse the text, identifying if any DOM nodes were constructed, which will be… slow. Or regular expressions which will be faster, but… potentially inaccurate. There are also two very distinct questions arising from this problem:

Q1: Does a string contain HTML fragments?

Is the string part of an HTML document, containing HTML element markup or encoded entities? This can be used as an indicator that the string may require bleaching / sanitization or entity decoding:

/</?[a-z][^>]*>|(\&(?:[\w\d]+|#\d+|#x[a-f\d]+);/

You can see this pattern in use against all of the examples from all existing answers at the time of this writing, plus some… rather hideous WYSIWYG- or Word-generated sample text and a variety of character entity references.

Q2: Is the string an HTML document?

The HTML specification is shockingly loose as to what it considers an HTML document. Browsers go to extreme lengths to parse almost any garbage text as HTML. Two approaches: either just consider everything HTML (since if delivered with a text/html Content-Type, great effort will be expended to try to interpret it as HTML by the user-agent) or look for the prefix marker:

<!DOCTYPE html>

In terms of "well-formedness", that, and almost nothing else is "required". The following is a 100% complete, fully valid HTML document containing every HTML element you think is being omitted:

<!DOCTYPE html>
<title>Yes, really.</title>
<p>This is everything you need.

Yup. There are explicit rules on how to form "missing" elements such as <html>, <head>, and <body>. Though I find it rather amusing that SO's syntax highlighting failed to detect that properly without an explicit hint.