Using DISTINCT along with GROUP BY in SQL Server
Use DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clause
In a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
Use DISTINCT
to find unique aggregate function values
In a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
Use DISTINCT
to remove duplicates with more than one GROUP BY
column
Another case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
Huge performance difference when using group by vs distinct
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
- Copy all
business_key
values to a temporary table
- Sort the temporary table
- Scan the temporary table, returning each item that is different from the one before it
The group by
could be executed like:
- Scan the full table, storing each value of
business key
in a hashtable
- Return the keys of the hashtable
The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
How to "select distinct" across multiple data frame columns in pandas?
There is no unique
method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique)
but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:
In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
d[col] = df[col].unique()
d
Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}
Distinct by property of class with LINQ
Another extension method for Linq-to-Objects, without using GroupBy:
/// <summary>
/// Returns the set of items, made distinct by the selected value.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="selector">A function that selects a value to determine unique results.</param>
/// <returns>IEnumerable<TSource>.</returns>
public static IEnumerable<TSource> Distinct<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
HashSet<TResult> set = new HashSet<TResult>();
foreach(var item in source)
{
var selectedValue = selector(item);
if (set.Add(selectedValue))
yield return item;
}
}
Using DISTINCT inner join in SQL
SELECT DISTINCT C.valueC
FROM C
LEFT JOIN B ON C.id = B.lookupC
LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL
I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.
EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.
There is no distinct join construct you could use so just stay with what you already have :)
mysql query: SELECT DISTINCT column1, GROUP BY column2
Replacing FROM tablename
with FROM (SELECT DISTINCT * FROM tablename)
should give you the result you want (ignoring duplicated rows) for example:
SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name
Result for your test data:
dave 2
mark 2
Removing duplicates from a SQL query (not just "use distinct")
Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.
Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.
If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:
USING CTE (Row, Name, PicID)
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
U.NAME, P.PIC_ID
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
ORDER BY U.NAME, P.PIC_ID
)
SELECT
CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
ON current.Row = previous.Row + 1
ORDER BY current.Row
The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.
MongoDB distinct aggregation
SQL Query: (group by & count of distinct)
select city,count(distinct(emailId)) from TransactionDetails group by city;
Equivalent mongo query would look like this:
db.TransactionDetails.aggregate([
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} }
]);
Distinct pair of values SQL
if you want to filter the tuples you can use on this way:
select distinct (case a > b then (a,b) else (b,a) end) from pairs
the good stuff is you don't have to use group by.
LINQ: Distinct values
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
SQL: Group by minimum value in one field while selecting distinct rows
I would like to add to some of the other answers here, if you don't need the first item but say the second number for example you can use rownumber in a subquery and base your result set off of that.
SELECT * FROM
(
SELECT
ROW_NUM() OVER (PARTITION BY Id ORDER BY record_date, other_cols) as rownum,
*
FROM products P
) INNER
WHERE rownum = 2
This also allows you to order off multiple columns in the subquery which may help if two record_dates have identical values. You can also partition off of multiple columns if needed by delimiting them with a comma
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Entity Framework select distinct name
Entity-Framework Select Distinct Name:
Suppose if you are want every first data of particular column of each group ;
var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();
foreach (var item in data)
{
var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();
//Eg.
{
ListBox1.Items.Add(data2.ColumnName);
}
}
How does DISTINCT work when using JPA and Hibernate
I agree with kazanaki's answer, and it helped me.
I wanted to select the whole entity, so I used
select DISTINCT(c) from Customer c
In my case I have many-to-many relationship, and I want to load entities with collections in one query.
I used LEFT JOIN FETCH and at the end I had to make the result distinct.
how to select rows based on distinct values of A COLUMN only
Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:
;WITH DistinctMails AS
(
SELECT ID, MailID, EMailAddress, NAME,
ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1
This works on SQL Server 2005 and newer (you didn't mention what version you're using...)
How do you create a Distinct query in HQL
You can simply add GROUP BY instead of Distinct
@Query(value = "from someTableEntity where entityCode in :entityCode" +
" group by entityCode, entityName, entityType")
List<someTableEntity > findNameByCode(@Param("entityCode") List<String> entityCode);
Select unique or distinct values from a list in UNIX shell script
Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)
bag2set () {
# Reduce a_bag to a_set.
local -i i j n=${#a_bag[@]}
for ((i=0; i < n; i++)); do
if [[ -n ${a_bag[i]} ]]; then
a_set[i]=${a_bag[i]}
a_bag[i]=$'\0'
for ((j=i+1; j < n; j++)); do
[[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
done
fi
done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
a_bag[i]=$e
i=$i+1
done
bag2set
echo "${a_set[@]}"
sql query distinct with Row_Number
This article covers an interesting relationship between ROW_NUMBER()
and DENSE_RANK()
(the RANK()
function is not treated specifically). When you need a generated ROW_NUMBER()
on a SELECT DISTINCT
statement, the ROW_NUMBER()
will produce distinct values before they are removed by the DISTINCT
keyword. E.g. this query
SELECT DISTINCT
v,
ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... might produce this result (DISTINCT
has no effect):
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| a | 2 |
| a | 3 |
| b | 4 |
| c | 5 |
| c | 6 |
| d | 7 |
| e | 8 |
+---+------------+
Whereas this query:
SELECT DISTINCT
v,
DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... produces what you probably want in this case:
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
| e | 5 |
+---+------------+
Note that the ORDER BY
clause of the DENSE_RANK()
function will need all other columns from the SELECT DISTINCT
clause to work properly.
All three functions in comparison
Using PostgreSQL / Sybase / SQL standard syntax (WINDOW
clause):
SELECT
v,
ROW_NUMBER() OVER (window) row_number,
RANK() OVER (window) rank,
DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v
... you'll get:
+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a | 1 | 1 | 1 |
| a | 2 | 1 | 1 |
| a | 3 | 1 | 1 |
| b | 4 | 4 | 2 |
| c | 5 | 5 | 3 |
| c | 6 | 5 | 3 |
| d | 7 | 7 | 4 |
| e | 8 | 8 | 5 |
+---+------------+------+------------+
How do I (or can I) SELECT DISTINCT on multiple columns?
SELECT DISTINCT a,b,c FROM t
is roughly equivalent to:
SELECT a,b,c FROM t GROUP BY a,b,c
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
Get a list of distinct values in List
Distinct the Note class by Author
var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());
foreach(var item in DistinctItems)
{
//Add to other List
}
Count the occurrences of DISTINCT values
What about something like this:
SELECT
name,
count(*) AS num
FROM
your_table
GROUP BY
name
ORDER BY
count(*)
DESC
You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.
Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.
How to get distinct results in hibernate with joins and row-based limiting (paging)?
NullPointerException
in some cases!
Without criteria.setProjection(Projections.distinct(Projections.property("id")))
all query goes well!
This solution is bad!
Another way is use SQLQuery. In my case following code works fine:
List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();
Distinction is done in data base! In opposite to:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
where distinction is done in memory, after load entities!
MySQL SELECT DISTINCT multiple columns
This will give DISTINCT values across all the columns:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
DISTINCT clause with WHERE
You can use ROW_NUMBER(). You can specify where conditions as well. (e.g. Name LIKE'MyName%
in the following query)
SELECT *
FROM (SELECT ID, Name, Email,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID) AS RowNumber
FROM MyTable
WHERE Name LIKE 'MyName%') AS a
WHERE a.RowNumber = 1
Eliminating duplicate values based on only one column of the table
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
SQL - select distinct only on one column
A very typical approach to this type of problem is to use row_number()
:
select t.*
from (select t.*,
row_number() over (partition by number order by id) as seqnum
from t
) t
where seqnum = 1;
This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid()
. You can select 2 rows by using where seqnum <= 2
.
Oracle 11g SQL to get unique values in one column of a multi-column query
This will be more efficient, plus you have control over the ordering it uses to pick a value:
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language
ORDER BY person)
,language
FROM tableA;
If you really don't care which person is picked for each language, you can omit the ORDER BY clause:
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language)
,language
FROM tableA;
How to use LINQ Distinct() with multiple fields
Distinct method returns distinct elements from a sequence.
If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator
for your anonymous type. Distinct iterator adds elements to Set
when enumerating over collection. This enumerator skips all elements which are already in Set
. Set
uses GetHashCode
and Equals
methods for defining if element already exists in Set
.
How GetHashCode
and Equals
implemented for anonymous type? As it stated on msdn:
Equals and GetHashCode methods on anonymous types are defined in terms
of the Equals and GetHashcode methods of the properties, two instances
of the same anonymous type are equal only if all their properties are
equal.
So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.
How to use DISTINCT and ORDER BY in same SELECT statement?
2) Order by CreationDate is very important
The original results indicated that "test3" had multiple results...
It's very easy to start using MAX all the time to remove duplicates in Group By's... and forget or ignore what the underlying question is...
The OP presumably realised that using MAX was giving him the last "created" and using MIN would give the first "created"...
postgresql COUNT(DISTINCT ...) very slow
-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';
\echo original
EXPLAIN ANALYZE
SELECT
COUNT (distinct val) as aantal
FROM one
;
\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
distinct val
-- , COUNT(*)
FROM one
GROUP BY val;
\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
SELECT distinct val
FROM one
GROUP BY val
)
SELECT COUNT (*) as aantal
FROM agg
;
Results:
original QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
Total runtime: 1766.642 ms
(3 rows)
group by+count(*)
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
Total runtime: 412.686 ms
(4 rows)
with CTE
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
CTE agg
-> HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
-> CTE Scan on agg (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
Total runtime: 408.300 ms
(7 rows)
The same plan as for the CTE could probably also be produced by other methods (window functions)
How can I put strings in an array, split by new line?
<anti-answer>
As other answers have specified, be sure to use explode
rather than split
because as of PHP 5.3.0 split
is deprecated. i.e. the following is NOT the way you want to do it:
$your_array = split(chr(10), $your_string);
LF = "\n" = chr(10), CR = "\r" = chr(13)
</anti-answer>
C# string replace
You need to escape the double-quotes inside the search string, like this:
string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");
Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res
will have the replacements.
How do CSS triangles work?
Try This:-
_x000D_
_x000D_
.triangle {_x000D_
border-color: transparent transparent red transparent;_x000D_
border-style: solid;_x000D_
border-width: 0px 200px 200px 200px;_x000D_
height: 0px;_x000D_
width: 0px;_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_
assign headers based on existing row in dataframe in R
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
How do I block or restrict special characters from input fields with jquery?
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input
event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Gather multiple sets of columns
With the recent update to melt.data.table
, we can now melt multiple columns. With that, we can do:
require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"),
value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
# id time loop_number Q3.2 Q3.3
# 1: 1 2009-01-01 1 -0.433978480 0.41227209
# 2: 2 2009-01-02 1 -0.567995351 0.30701144
# 3: 3 2009-01-03 1 -0.092041353 -0.96024077
# 4: 4 2009-01-04 1 1.137433487 0.60603396
# 5: 5 2009-01-05 1 -1.071498263 -0.01655584
# 6: 6 2009-01-06 1 -0.048376809 0.55889996
# 7: 7 2009-01-07 1 -0.007312176 0.69872938
You can get the development version from here.
How do I get to IIS Manager?
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit:
You should have something like this:
Showing an image from console in Python
Or simply execute the image through the shell, as in
import subprocess
subprocess.call([ fname ], shell=True)
and whatever program is installed to handle images will be launched.
Passing functions with arguments to another function in Python?
This is called partial functions and there are at least 3 ways to do this. My favorite way is using lambda because it avoids dependency on extra package and is the least verbose. Assume you have a function add(x, y)
and you want to pass add(3, y)
to some other function as parameter such that the other function decides the value for y
.
Use lambda
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
def main():
f = lambda y: add(3, y)
result = runOp(f, 1) # is 4
Create Your Own Wrapper
Here you need to create a function that returns the partial function. This is obviously lot more verbose.
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# declare partial function
def addPartial(x):
def _wrapper(y):
return add(x, y)
return _wrapper
# run example
def main():
f = addPartial(3)
result = runOp(f, 1) # is 4
Use partial from functools
This is almost identical to lambda
shown above. Then why do we need this? There are few reasons. In short, partial
might be bit faster in some cases (see its implementation) and that you can use it for early binding vs lambda's late binding.
from functools import partial
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
def main():
f = partial(add, 3)
result = runOp(f, 1) # is 4
Best practices for SQL varchar column length
The best value is the one that is right for the data as defined in the underlying domain.
For some domains, VARCHAR(10)
is right for the Name
attribute, for other domains VARCHAR(255)
might be the best choice.
Simple IEnumerator use (with example)
If i understand you correctly then in c# the yield return
compiler magic is all you need i think.
e.g.
IEnumerable<string> myMethod(IEnumerable<string> sequence)
{
foreach(string item in sequence)
{
yield return item + "roxxors";
}
}
How to validate a date?
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
Plot multiple boxplot in one graph
You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.
require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package.
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame
# Label variable value
# 1 Good F1 0.64778924
# 2 Good F1 0.54608791
# 3 Good F1 0.46134200
# 4 Good F1 0.79421221
# 5 Good F1 0.56919951
# 6 Good F1 0.73568570
# 7 Good F1 0.65094207
# 8 Good F1 0.45749702
# 9 Good F1 0.80861929
# 10 Good F1 0.67310067
# 11 Good F1 0.68781739
# 12 Good F1 0.47009455
# 13 Good F1 0.95859182
# 14 Good F1 1.00000000
# 15 Good F1 0.46908343
# 16 Bad F1 0.57875528
# 17 Bad F1 0.28938046
# 18 Bad F1 0.68511766
require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))
Edit: I realise that you might need to facet. Here's an implementation of that as well:
p <- ggplot(data = df.m, aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")
Edit 2: How to add x-labels
, y-labels
, title
, change legend heading
, add a jitter
?
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
Edit 3: How to align geom_point()
points to the center of box-plot? It could be done using position_dodge
. This should work.
require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
Titlecase all entries into a form_for text field
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
counting the number of lines in a text file
In C if you implement count line it will never fail.
Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
Is there an equivalent for var_dump (PHP) in Javascript?
I used the first answer, but I felt was missing a recursion in it.
The result was this:
function dump(obj) {
var out = '';
for (var i in obj) {
if(typeof obj[i] === 'object'){
dump(obj[i]);
}else{
out += i + ": " + obj[i] + "\n";
}
}
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
PL/SQL, how to escape single quote in a string?
Here's a blog post that should help with escaping ticks in strings.
Here's the simplest method from said post:
The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.
SELECT 'test single quote''' from dual;
The output of the above statement would be:
test single quote'
Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.
This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.
Cross-Origin Read Blocking (CORB)
There is an edge case worth mentioning in this context: Chrome (some versions, at least) checks CORS preflights using the algorithm set up for CORB. IMO, this is a bit silly because preflights don't seem to affect the CORB threat model, and CORB seems designed to be orthogonal to CORS. Also, the body of a CORS preflight is not accessible, so there is no negative consequence just an irritating warning.
Anyway, check that your CORS preflight responses (OPTIONS method responses) don't have a body (204). An empty 200 with content type application/octet-stream and length zero worked well here too.
You can confirm if this is the case you are hitting by counting CORB warnings vs. OPTIONS responses with a message body.
Last executed queries for a specific database
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
How to bind multiple values to a single WPF TextBlock?
Use a ValueConverter
[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}:{1}", (string) value, (string) parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
and in the markup
<src:MyConverter x:Key="MyConverter"/>
.
.
.
<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />
git push rejected
First use
git pull https://github.com/username/repository master
and then try
git push -u origin master
How to upload multiple files using PHP, jQuery and AJAX
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
Python strip() multiple characters?
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)
Here's the script:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Here are the results:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate
is not the most readable; the other three are more obvious, though slower to varying degrees.
Export a list into a CSV or TXT file in R
So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1
which is printed out (and which contains 4 more lists).
I think the easiest way to do this is to use lapply
with the addition of dataframe
(assuming that each list inside each element of the main list (like the lists in $f10010_1
) has the same length):
lapply(mylist, function(x) write.table( data.frame(x), 'test.csv' , append= T, sep=',' ))
The above will convert $f10010_1
into a dataframe then do the same with every other element and append one below the other in 'test.csv'
You can also type ?write.table
on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.
How to set data attributes in HTML elements
HTML
<div id="mydiv" data-myval="10"></div>
JS
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
Demo
Reference
From the reference:
jQuery itself uses the .data()
method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.
It should be noted that jQuery's data()
doesn't change the data
attribute in HTML.
So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
?JS:
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
See this demo
.trim() in JavaScript not working in IE
I don't think there's a native trim()
method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.
When to use extern in C++
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
header:
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
source 1:
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
source 2:
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}
How do I add a simple jQuery script to WordPress?
After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:
- Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
- Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
Make sure your custom jQuery .js looks like this:
(function($) {
$(document).ready(function() {
$('.your-class').addClass('do-my-bidding');
})
})(jQuery);
Go to the theme's directory, open up functions.php
Add some code near the top that looks like this:
//this goes in functions.php near the top
function my_scripts_method() {
// register your script location, dependencies and version
wp_register_script('custom_script',
get_template_directory_uri() . '/custom_js/jquery_test.js',
array('jquery'),
'1.0' );
// enqueue the script
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
- Check out your site to make sure it works!
In Chart.js set chart title, name of x axis and y axis?
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
How to read a line from the console in C?
As suggested, you can use getchar() to read from the console until an end-of-line or an EOF is returned, building your own buffer. Growing buffer dynamically can occur if you are unable to set a reasonable maximum line size.
You can use also use fgets as a safe way to obtain a line as a C null-terminated string:
#include <stdio.h>
char line[1024]; /* Generously large value for most situations */
char *eof;
line[0] = '\0'; /* Ensure empty line if no input delivered */
line[sizeof(line)-1] = ~'\0'; /* Ensure no false-null at end of buffer */
eof = fgets(line, sizeof(line), stdin);
If you have exhausted the console input or if the operation failed for some reason, eof == NULL is returned and the line buffer might be unchanged (which is why setting the first char to '\0' is handy).
fgets will not overfill line[] and it will ensure that there is a null after the last-accepted character on a successful return.
If end-of-line was reached, the character preceding the terminating '\0' will be a '\n'.
If there is no terminating '\n' before the ending '\0' it may be that there is more data or that the next request will report end-of-file. You'll have to do another fgets to determine which is which. (In this regard, looping with getchar() is easier.)
In the (updated) example code above, if line[sizeof(line)-1] == '\0' after successful fgets, you know that the buffer was filled completely. If that position is proceeded by a '\n' you know you were lucky. Otherwise, there is either more data or an end-of-file up ahead in stdin. (When the buffer is not filled completely, you could still be at an end-of-file and there also might not be a '\n' at the end of the current line. Since you have to scan the string to find and/or eliminate any '\n' before the end of the string (the first '\0' in the buffer), I am inclined to prefer using getchar() in the first place.)
Do what you need to do to deal with there still being more line than the amount you read as the first chunk. The examples of dynamically-growing a buffer can be made to work with either getchar or fgets. There are some tricky edge cases to watch out for (like remembering to have the next input start storing at the position of the '\0' that ended the previous input before the buffer was extended).
How to replace a character from a String in SQL?
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
AngularJS. How to call controller function from outside of controller component
I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:
angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()
I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.
Import numpy on pycharm
In PyCharm go to
- File ? Settings, or use Ctrl + Alt + S
- < project name > ? Project Interpreter ? gear symbol ? Add Local
- navigate to
C:\Miniconda3\envs\my_env\python.exe
, where my_env is the environment you want to use
Alternatively, in step 3 use C:\Miniconda3\python.exe
if you did not create any further environments (if you never invoked conda create -n my_env python=3
).
You can get a list of your current environments with conda info -e
and switch to one of them using activate my_env
.
What does FETCH_HEAD in Git mean?
git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.
jQuery when element becomes visible
(function() {
var ev = new $.Event('display'),
orig = $.fn.css;
$.fn.css = function() {
orig.apply(this, arguments);
$(this).trigger(ev);
}
})();
$('#element').bind('display', function(e) {
alert("display has changed to :" + $(this).attr('style') );
});
$('#element').css("display", "none")// i change the style in this line !!
$('#element').css("display", "block")// i change the style in this line !!
http://fiddle.jshell.net/prollygeek/gM8J2/3/
changes will be alerted.
How to disable CSS in Browser for testing purposes
In Chrome/Chromium you can do this in the developer console.
- Bring up the developer console by either ctrl-shift-j or Menu->Tools->Developer Console.
- Within the developer console browse to the Sources tab.
- In the top-left corner of this tab is an icon with a disclosure triangle. Click on it.
- Browse to <domain>→css→<css file you want to eliminate>
- Highlight all of the text and hit delete.
- Rinse and repeat for each stylesheet you want to disable.
Excel select a value from a cell having row number calculated
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
How to update std::map after using the find method?
If you already know the key, you can directly update the value at that key using m[key] = new_value
Here is a sample code that might help:
map<int, int> m;
for(int i=0; i<5; i++)
m[i] = i;
for(auto it=m.begin(); it!=m.end(); it++)
cout<<it->second<<" ";
//Output: 0 1 2 3 4
m[4] = 7; //updating value at key 4 here
cout<<"\n"; //Change line
for(auto it=m.begin(); it!=m.end(); it++)
cout<<it->second<<" ";
// Output: 0 1 2 3 7
How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?
in this scenario:
DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
aren't you missing the column you want to compare to? example:
DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.
www-data permissions?
sudo chown -R yourname:www-data cake
then
sudo chmod -R g+s cake
First command changes owner and group.
Second command adds s attribute which will keep new files and directories within cake having the same group permissions.
Can't Autowire @Repository annotated interface in Spring Boot
There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.
In a repository like:
@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{
}
If your entity UserEntity
does not have the @Entity
annotation on the class, you will have the same error.
This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answer may help you.
Plotting multiple curves same graph and same scale
I'm not sure what you want, but i'll use lattice.
x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)
Then, just plot
xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)
Using command line arguments in VBscript
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
How to declare empty list and then add string in scala?
If you need to mutate stuff, use ArrayBuffer
or LinkedBuffer
instead. However, it would be better to address this statement:
I need to declare empty list or empty
maps and some where later in the code
need to fill them.
Instead of doing that, fill the list with code that returns the elements. There are many ways of doing that, and I'll give some examples:
// Fill a list with the results of calls to a method
val l = List.fill(50)(scala.util.Random.nextInt)
// Fill a list with the results of calls to a method until you get something different
val l = Stream.continually(scala.util.Random.nextInt).takeWhile(x => x > 0).toList
// Fill a list based on its index
val l = List.tabulate(5)(x => x * 2)
// Fill a list of 10 elements based on computations made on the previous element
val l = List.iterate(1, 10)(x => x * 2)
// Fill a list based on computations made on previous element, until you get something
val l = Stream.iterate(0)(x => x * 2 + 1).takeWhile(x => x < 1000).toList
// Fill list based on input from a file
val l = (for (line <- scala.io.Source.fromFile("filename.txt").getLines) yield line.length).toList
What are the git concepts of HEAD, master, origin?
I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.
HEAD: the current commit your repo is on. Most of the time HEAD
points to the latest commit in your current branch, but that doesn't have to be the case. HEAD
really just means "what is my repo currently pointing at".
In the event that the commit HEAD
refers to is not the tip of any branch, this is called a "detached head".
master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.
origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.
HEAD
is an official notion in git. HEAD
always has a well-defined meaning. master
and origin
are common names usually used in git, but they don't have to be.
Run an OLS regression with Pandas Data Frame
This would require me to reformat the data into lists inside lists, which seems to defeat the purpose of using pandas in the first place.
No it doesn't, just convert to a NumPy array:
>>> data = np.asarray(df)
This takes constant time because it just creates a view on your data. Then feed it to scikit-learn:
>>> from sklearn.linear_model import LinearRegression
>>> lr = LinearRegression()
>>> X, y = data[:, 1:], data[:, 0]
>>> lr.fit(X, y)
LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
>>> lr.coef_
array([ 4.01182386e-01, 3.51587361e-04])
>>> lr.intercept_
14.952479503953672
Get index of a key/value pair in a C# dictionary based on the value
There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).
Obviously you can get the key from a KeyValuePair
just by using the Key
property, so that will let you use the indexer of the dictionary:
var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);
You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:
var key = dictionary.Where(pair => pair.Value == desiredValue)
.Select(pair => pair.Key)
.FirstOrDefault();
key
will be null if the entry doesn't exist.
This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.
Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.
How to get week number in Python?
You can get the week number directly from datetime as string.
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get different "types" of the week number of the year changing the strftime
parameter for:
%U
- Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53
%W
- Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53
[...]
(Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the strftime()
method.
[...]
%V
- ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53
from: datetime — Basic date and time types — Python 3.7.3 documentation
I've found out about it from here. It worked for me in Python 2.7.6
Detecting input change in jQuery?
As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:
$input.on('change keydown keypress keyup mousedown click mouseup', handler);
If you think it may fit, you can add focus
, blur
and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.
Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val()
method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).
Min / Max Validator in Angular 2 Final
I've added a max
validation to amd's great answer.
import { Directive, Input, forwardRef } from '@angular/core'
import { NG_VALIDATORS, Validator, AbstractControl, Validators } from '@angular/forms'
/*
* This is a wrapper for [min] and [max], used to work with template driven forms
*/
@Directive({
selector: '[min]',
providers: [{ provide: NG_VALIDATORS, useExisting: MinNumberValidator, multi: true }]
})
export class MinNumberValidator implements Validator {
@Input() min: number;
validate(control: AbstractControl): { [key: string]: any } {
return Validators.min(this.min)(control)
}
}
@Directive({
selector: '[max]',
providers: [{ provide: NG_VALIDATORS, useExisting: MaxNumberValidator, multi: true }]
})
export class MaxNumberValidator implements Validator {
@Input() max: number;
validate(control: AbstractControl): { [key: string]: any } {
return Validators.max(this.max)(control)
}
}
Detect end of ScrollView
scrollView = (ScrollView) findViewById(R.id.scrollView);
scrollView.getViewTreeObserver()
.addOnScrollChangedListener(new
ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (!scrollView.canScrollVertically(1)) {
// bottom of scroll view
}
if (!scrollView.canScrollVertically(-1)) {
// top of scroll view
}
}
});
How to resolve this System.IO.FileNotFoundException
I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.
To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:
Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.
Execute an action when an item on the combobox is selected
Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)
// WRONG
public class DataWrapper {
final Data data;
final String description;
public DataWrapper(Object data, String description) {
this.data = data;
this.description = description;
}
....
@Override
public String toString() {
return description;
}
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());
It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).
The driving forces for breaking of rules were:
- keep functionality of the default KeySelectionManager (which is broken by a custom renderer)
- reuse of the wrapper class (can be applied to any data type)
As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.
While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.
We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)
In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:
StringValue sv = new StringValue() {
@Override
public String getString(Object value) {
if (value instanceof Data) {
return ((Data) value).getSomeProperty();
}
return TO_STRING.getString(value);
}
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);
As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:
public BetterKeySelectionManager implements KeySelectionManager {
@Override
public int selectionForKey(char ch, ComboBoxModel model) {
....
if (getCellRenderer() instance of StringValue) {
String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
....
}
}
}
Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:
- some provider of a string representation
- a custom renderer which is configurable by that provider and guarantees to use it in configuring itself
- a well-behaved keySelectionManager with queries the renderer for its string represention
All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)
Copying from one text file to another using Python
f = open('list1.txt')
f1 = open('output.txt', 'a')
# doIHaveToCopyTheLine=False
for line in f.readlines():
if 'tests/file/myword' in line:
f1.write(line)
f1.close()
f.close()
Now Your code will work. Try This one.
Reading Xml with XmlReader in C#
We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account>
element, after parsing the reader will index the </Accounts>
closing tag.
The parsing code looks something like this:
public class Account
{
string _accountId;
string _nameOfKin;
Statements _statmentsAvailable;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read node attributes
_accountId = reader.GetAttribute( "accountId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
switch( reader.Name )
{
// Read element for a property of this class
case "NameOfKin":
_nameOfKin = reader.ReadElementContentAsString();
break;
// Starting sub-list
case "StatementsAvailable":
_statementsAvailable = new Statements();
_statementsAvailable.Read( reader );
break;
default:
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statements
class just reads in the <StatementsAvailable>
node
public class Statements
{
List<Statement> _statements = new List<Statement>();
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
if( reader.Name == "Statement" )
{
var statement = new Statement();
statement.ReadFromXml( reader );
_statements.Add( statement );
}
else
{
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statement
class would look very much the same
public class Statement
{
string _satementId;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read noe attributes
_statementId = reader.GetAttribute( "statementId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
....same basic loop
}
}
}
How do I PHP-unserialize a jQuery-serialized form?
Provided that your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()
):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params
should then be an array modeled how you would expect. Note this works also with HTML arrays.
See the following for more information:
http://www.php.net/manual/en/function.parse-str.php
AttributeError("'str' object has no attribute 'read'")
If you get a python error like this:
AttributeError: 'str' object has no attribute 'some_method'
You probably poisoned your object accidentally by overwriting your object with a string.
How to reproduce this error in python with a few lines of code:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
Run it, which prints:
AttributeError: 'str' object has no attribute 'loads'
But change the name of the variablename, and it works fine:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.
Finding all the subsets of a set
It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.
- For n=1, the set of subsets is {{}, {1}}
- For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies.
Edit To make it crystal clear:
- The set of subsets of {1} is {{}, {1}}
- For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
- Repeat till you reach n
How to join two tables by multiple columns in SQL?
Yes: You can use Inner Join
to join on multiple columns.
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
E.FileNum = V.FileNum AND
E.ActivityNum = V.ActivityNum
Create table
CREATE TABLE MyNewTab(CaseNum int, FileNum int,
ActivityNum int, Grade int, Score varchar(100))
Insert values
INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score)
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
E.FileNum = V.FileNum AND
E.ActivityNum = V.ActivityNum
best practice font size for mobile
Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px
. By declaring styles that lead to computed font-sizes of less than 12px
, like so:
html {
font-size: 8px;
}
p {
font-size: 1.4rem;
}
// Computed p size: 11px.
You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px
as 12px
. So, the following is true:
h6 {
font-size: 12px;
}
p {
font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.
// How unpleasant of a surprise.
I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.
I would instead, opt for something like this:
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2.25rem;
}
h3 {
font-size: 2rem;
}
h4 {
font-size: 1.75rem;
}
h5 {
font-size: 1.5rem;
}
h6 {
font-size: 1.25rem;
}
p {
font-size: 1rem;
}
@media (max-width: 480px) {
html {
font-size: 12px;
}
}
@media (min-width: 480px) {
html {
font-size: 13px;
}
}
@media (min-width: 768px) {
html {
font-size: 14px;
}
}
@media (min-width: 992px) {
html {
font-size: 15px;
}
}
@media (min-width: 1200px) {
html {
font-size: 16px;
}
}
You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p
elements.
As a side note, setting margin-bottom
equal to the font-size
usually also tends to be attractive, i.e.:
h1 {
font-size: 2.5rem;
margin-bottom: 2.5rem;
}
Good luck.
Remove empty strings from array while keeping record Without Loop?
i.e we need to take multiple email addresses separated by comma, spaces or newline as below.
var emails = EmailText.replace(","," ").replace("\n"," ").replace(" ","").split(" ");
for(var i in emails)
emails[i] = emails[i].replace(/(\r\n|\n|\r)/gm,"");
emails.filter(Boolean);
console.log(emails);
How to set <iframe src="..."> without causing `unsafe value` exception?
This one works for me.
import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';
@Component({
moduleId: module.id,
selector: 'player',
templateUrl: './player.component.html',
styleUrls:['./player.component.scss'],
})
export class PlayerComponent implements OnInit{
@Input()
id:string;
url: SafeResourceUrl;
constructor (public sanitizer:DomSanitizer) {
}
ngOnInit() {
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);
}
}
Styling a input type=number
I've been struggling with this on mobile and tablet. My solution was to use absolute
positioning on the spinners, so I'm just posting it in case it helps anyone else:
_x000D_
_x000D_
<html><head>_x000D_
<style>_x000D_
body {padding: 10px;margin: 10px}_x000D_
input[type=number] {_x000D_
/*for absolutely positioning spinners*/_x000D_
position: relative; _x000D_
padding: 5px;_x000D_
padding-right: 25px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button,_x000D_
input[type=number]::-webkit-outer-spin-button {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-outer-spin-button, _x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: inner-spin-button !important;_x000D_
width: 25px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
}_x000D_
</style>_x000D_
<meta name="apple-mobile-web-app-capable" content="yes"/>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0"/>_x000D_
</head>_x000D_
<body >_x000D_
<input type="number" value="1" step="1" />_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_
setting global sql_mode in mysql
In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf
change this under [mysqld
]
Paste this line on [mysqld
] portion
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
How to clear the entire array?
i fell into a case where clearing the entire array failed with dim/redim :
having 2 module-wide arrays, Private inside a userform,
One array is dynamic and uses a class module, the other is fixed and has a special type.
Option Explicit
Private Type Perso_Type
Nom As String
PV As Single 'Long 'max 1
Mana As Single 'Long
Classe1 As String
XP1 As Single
Classe2 As String
XP2 As Single
Classe3 As String
XP3 As Single
Classe4 As String
XP4 As Single
Buff(1 To 10) As IPicture 'Disp
BuffType(1 To 10) As String
Dances(1 To 10) As IPicture 'Disp
DancesType(1 To 10) As String
End Type
Private Data_Perso(1 To 9, 1 To 8) As Perso_Type
Dim ImgArray() As New ClsImage 'ClsImage is a Class module
And i have a sub declared as public to clear those arrays (and associated run-time created controls) from inside and outside the userform like this :
Public Sub EraseControlsCreatedAtRunTime()
Dim i As Long
On Error Resume Next
With Me.Controls 'removing all on run-time created controls of the Userform :
For i = .Count - 1 To 0 Step -1
.Remove i
Next i
End With
Err.Clear: On Error GoTo 0
Erase ImgArray, Data_Perso
'ReDim ImgArray() As ClsImage ' i tried this, no error but wouldn't work correctly
'ReDim Data_Perso(1 To 9, 1 To 8) As Perso_Type 'without the erase not working, with erase this line is not needed.
End Sub
note : this last sub was first called from outside (other form and class module) with Call FormName.SubName
but had to replace it with Application.Run FormName.SubName
, less errors, don't ask why...
How do I use a delimiter with Scanner.useDelimiter in Java?
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
- Using the Scanner method: useDelimiter(String pattern)
- Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
How to Inspect Element using Safari Browser
In your Safari menu bar click Safari > Preferences & then select the Advanced tab.
Select: "Show Develop menu in menu bar"
Now you can click Develop in your menu bar and choose Show Web Inspector
You can also right-click and press "Inspect element".
Connect to SQL Server through PDO using SQL Server Driver
This works for me, and in this case was a remote connection:
Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
How to check if an email address is real or valid using PHP
I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP
script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.
GitHub
here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master
<?php
# What to do if the class is being called directly and not being included in a script via PHP
# This allows the class/script to be called via other methods like JavaScript
if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();
if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
$return_array['error'] = 1;
$return_array['message'] = 'No email address was submitted for verification';
$return_array['domain_verified'] = 0;
$return_array['format_verified'] = 0;
}else{
$verify = new EmailVerify();
if($verify->verify_formatting($_GET['address_to_verify'])){
$return_array['format_verified'] = 1;
if($verify->verify_domain($_GET['address_to_verify'])){
$return_array['error'] = 0;
$return_array['domain_verified'] = 1;
$return_array['message'] = 'Formatting and domain have been verified';
}else{
$return_array['error'] = 1;
$return_array['domain_verified'] = 0;
$return_array['message'] = 'Formatting was verified, but verification of the domain has failed';
}
}else{
$return_array['error'] = 1;
$return_array['domain_verified'] = 0;
$return_array['format_verified'] = 0;
$return_array['message'] = 'Email was not formatted correctly';
}
}
echo json_encode($return_array);
exit();
}
class EmailVerify {
public function __construct(){
}
public function verify_domain($address_to_verify){
// an optional sender
$record = 'MX';
list($user, $domain) = explode('@', $address_to_verify);
return checkdnsrr($domain, $record);
}
public function verify_formatting($address_to_verify){
if(strstr($address_to_verify, "@") == FALSE){
return false;
}else{
list($user, $domain) = explode('@', $address_to_verify);
if(strstr($domain, '.') == FALSE){
return false;
}else{
return true;
}
}
}
}
?>
creating json object with variables
It's called on Object Literal
I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.
var formObject = {"formObject": [
{"firstName": firstName, "lastName": lastName},
{"phoneNumber": phone},
{"address": address},
]}
Although this seems to make more sense (Why do you have an array in the above literal?):
var formObject = {
firstName: firstName
...
}
android fragment- How to save states of views in a fragment when another fragment is pushed on top of it
The Best Solution I found is below:
onSavedInstanceState(): always called inside fragment when activity is going to shut down(Move activity from one to another or config changes).
So if we are calling multiple fragments on same activity then We have to use the following approach:
Use OnDestroyView() of the fragment and save the whole object inside that method.
Then
OnActivityCreated(): Check that if object is null or not(Because this method calls every time). Now restore state of an object here.
Its works always!
Push local Git repo to new remote including all branches and tags
In the case like me that you aquired a repo and are now switching the remote origin to a different repo, a new empty one...
So you have your repo and all the branches inside, but you still need to checkout those branches for the git push --all
command to actually push those too.
You should do this before you push:
for remote in `git branch -r | grep -v master `; do git checkout --track $remote ; done
Followed by
git push --all
Vue.js img src concatenate variable and text
You can't use curlies (moustache tags) in attributes. Use the following to concat data:
<img v-bind:src="imgPreUrl + 'img/logo.png'">
Or the short version:
<img :src="imgPreUrl + 'img/logo.png'">
Read more on dynamic attributes in the Vue docs.
Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport
You could also use the great laravel-cors package by barryvdh.
After you have the package installed, the easiest way to get CORS support for all your routes is to add the middleware like this in Http/Kernel.php:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Barryvdh\Cors\HandleCors::class,
];
If you dont want to have CORS support on all your routes you should make a new OPTIONS route for /oauth/token
and add the cors middleware to that route only.
Edit for Laravel 8
Laravel 8 already has CORS Support built in - HandleCors
middleware is defined in your global middleware stack by default and can be configured in your application's config/cors.php
config file.
If you update your Laravel application be sure to change out barryvdh's package with the supplied middleware: \Fruitcake\Cors\HandleCors::class
Most efficient way to create a zero filled JavaScript array?
My fastest function would be:
function newFilledArray(len, val) {
var a = [];
while(len--){
a.push(val);
}
return a;
}
var st = (new Date()).getTime();
newFilledArray(1000000, 0)
console.log((new Date()).getTime() - st); // returned 63, 65, 62 milliseconds
Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.
fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).
var a = [];
var len = 1000000;
var st = (new Date()).getTime();
while(len){
a.push(0);
len -= 1;
}
console.log((new Date()).getTime() - st); // returned 863, 894, 875 milliseconds
st = (new Date()).getTime();
len = 1000000;
a = [];
for(var i = 0; i < len; i++){
a.push(0);
}
console.log((new Date()).getTime() - st); // returned 1155, 1179, 1163 milliseconds
I'm interested to know what T.J. Crowder makes of that ? :-)
Center image in table td in CSS
Set a fixed with of your image in your css and add an auto
-margin/padding on the image to...
div.image img {
width: 100px;
margin: auto;
}
Or set the text-align
to center...
td {
text-align: center;
}
How do I hide an element when printing a web page?
The best practice is to use a style sheet specifically for printing, and and set its media
attribute to print
.
In it, show/hide the elements that you want to be printed on paper.
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
Example using Hyperlink in WPF
Note too that Hyperlink
does not have to be used for navigation. You can connect it to a command.
For example:
<TextBlock>
<Hyperlink Command="{Binding ClearCommand}">Clear</Hyperlink>
</TextBlock>
printf format specifiers for uint32_t and size_t
If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t
or uintmax_t
and use "%jd"
or %ju
, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t
.
How to set min-height for bootstrap container
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
How to create radio buttons and checkbox in swift (iOS)?
Solution for Radio Button in Swift 4.2 without using third-party libraries
Create RadioButtonController.swift file and place following code in it:
import UIKit
class RadioButtonController: NSObject {
var buttonsArray: [UIButton]! {
didSet {
for b in buttonsArray {
b.setImage(UIImage(named: "radio_off"), for: .normal)
b.setImage(UIImage(named: "radio_on"), for: .selected)
}
}
}
var selectedButton: UIButton?
var defaultButton: UIButton = UIButton() {
didSet {
buttonArrayUpdated(buttonSelected: self.defaultButton)
}
}
func buttonArrayUpdated(buttonSelected: UIButton) {
for b in buttonsArray {
if b == buttonSelected {
selectedButton = b
b.isSelected = true
} else {
b.isSelected = false
}
}
}
}
Use it as below in your view controller file:
import UIKit
class CheckoutVC: UIViewController {
@IBOutlet weak var btnPaytm: UIButton!
@IBOutlet weak var btnOnline: UIButton!
@IBOutlet weak var btnCOD: UIButton!
let radioController: RadioButtonController = RadioButtonController()
override func viewDidLoad() {
super.viewDidLoad()
radioController.buttonsArray = [btnPaytm,btnCOD,btnOnline]
radioController.defaultButton = btnPaytm
}
@IBAction func btnPaytmAction(_ sender: UIButton) {
radioController.buttonArrayUpdated(buttonSelected: sender)
}
@IBAction func btnOnlineAction(_ sender: UIButton) {
radioController.buttonArrayUpdated(buttonSelected: sender)
}
@IBAction func btnCodAction(_ sender: UIButton) {
radioController.buttonArrayUpdated(buttonSelected: sender)
}
}
Be sure to add radio_off and radio_on images in Assets.
Result:
Using intents to pass data between activities
I like to use this clean code to pass one value only:
startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));
This make more simple to write and understandable code.
Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery
Please check following snippet
_x000D_
_x000D_
/* DEBUG */_x000D_
.lwb-col {_x000D_
transition: box-shadow 0.5s ease;_x000D_
}_x000D_
.lwb-col:hover{_x000D_
box-shadow: 0 15px 30px -4px rgba(136, 155, 166, 0.4);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
.lwb-col--link {_x000D_
font-weight: 500;_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
.lwb-col--link::after{_x000D_
border-bottom: 2px solid;_x000D_
bottom: -3px;_x000D_
content: "";_x000D_
display: block;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
width: 100%;_x000D_
color: #E5E9EC;_x000D_
_x000D_
}_x000D_
.lwb-col--link::before{_x000D_
border-bottom: 2px solid;_x000D_
bottom: -3px;_x000D_
content: "";_x000D_
display: block;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
width: 100%;_x000D_
color: #57B0FB;_x000D_
transform: scaleX(0);_x000D_
_x000D_
_x000D_
}_x000D_
.lwb-col:hover .lwb-col--link::before {_x000D_
border-color: #57B0FB;_x000D_
display: block;_x000D_
z-index: 2;_x000D_
transition: transform 0.3s;_x000D_
transform: scaleX(1);_x000D_
transform-origin: left center;_x000D_
}
_x000D_
<div class="lwb-col">_x000D_
<h2>Webdesign</h2>_x000D_
<p>Steigern Sie Ihre Bekanntheit im Web mit individuellem & professionellem Webdesign. Organisierte Codestruktur, sowie perfekte SEO Optimierung und jahrelange Erfahrung sprechen für uns.</p>_x000D_
<span class="lwb-col--link">Mehr erfahren</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Ruby replace string with captured regex pattern
Try '\1'
for the replacement (single quotes are important, otherwise you need to escape the \
):
"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"
But since you only seem to be interested in the capture group, note that you can index a string with a regex:
"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"
How to set default font family for entire Android app
Just use this lib compile it in your grade file
complie'me.anwarshahriar:calligrapher:1.0'
and use it in the onCreate method in the main activity
Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "yourCustomFontHere.ttf", true);
This is the most elegant super fast way to do that.
How to vertically center a "div" element for all browsers using CSS?
The simplest way would be the following 3 lines of CSS:
1) position: relative;
2) top: 50%;
3) transform: translateY(-50%);
Following is an EXAMPLE:
_x000D_
_x000D_
div.outer-div {_x000D_
height: 170px;_x000D_
width: 300px;_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
div.middle-div {_x000D_
position: relative;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
-ms-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}
_x000D_
<div class='outer-div'>_x000D_
<div class='middle-div'>_x000D_
Test text_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
can't access mysql from command line mac
I think this is the more simpler approach:
- Install mySQL-Shell package from mySQL site
- Run mysqlsh (should be added to your path by default after install)
- Connect to your database server like so: MySQL JS > \connect --mysql [username]@[endpoint/server]:3306
- Switch to SQL Mode by typing "\sql" in your prompt
- The console should print out the following to let you know you are good to go:
Switching to SQL mode... Commands end with ;
Go forth and do great things! :)
vuetify center items into v-flex
<v-layout justify-center>
<v-card-actions>
<v-btn primary>
<span>SignUp</span>
</v-btn>`enter code here`
</v-card-actions>
</v-layout>
How to iterate for loop in reverse order in swift?
Swift 4.0
for i in stride(from: 5, to: 0, by: -1) {
print(i) // 5,4,3,2,1
}
If you want to include the to
value:
for i in stride(from: 5, through: 0, by: -1) {
print(i) // 5,4,3,2,1,0
}
Javascript Print iframe contents only
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
Word wrapping in phpstorm
In addition to Settings -> Editor -> Use soft wraps in editor I recommend Use soft wraps in console and Use custom soft wraps indent with a setting of 4 to make the wraps indented to match the line they started on.
how to get 2 digits after decimal point in tsql?
Try this one -
DECLARE @i FLOAT = 6.677756
SELECT
ROUND(@i, 2)
, FORMAT(@i, 'N2')
, CAST(@i AS DECIMAL(18,2))
, SUBSTRING(PARSENAME(CAST(@i AS VARCHAR(10)), 1), PATINDEX('%.%', CAST(@i AS VARCHAR(10))) - 1, 2)
, FLOOR((@i - FLOOR(@i)) * 100)
Output:
----------------------
6,68
6.68
6.68
67
67
Visual Studio 2017: Display method references
In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:
Tools ? Options ? Text Editor ? All Languages ? CodeLens
This is not available in the Community Edition
SQL JOIN and different types of JOINs
What is SQL JOIN
?
SQL JOIN
is a method to retrieve data from two or more database tables.
What are the different SQL JOIN
s ?
There are a total of five JOIN
s. They are :
1. JOIN or INNER JOIN
2. OUTER JOIN
2.1 LEFT OUTER JOIN or LEFT JOIN
2.2 RIGHT OUTER JOIN or RIGHT JOIN
2.3 FULL OUTER JOIN or FULL JOIN
3. NATURAL JOIN
4. CROSS JOIN
5. SELF JOIN
1. JOIN or INNER JOIN :
In this kind of a JOIN
, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.
In other words, INNER JOIN
is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.
Note that a JOIN
without any other JOIN
keywords (like INNER
, OUTER
, LEFT
, etc) is an INNER JOIN
. In other words, JOIN
is
a Syntactic sugar for INNER JOIN
(see: Difference between JOIN and INNER JOIN).
2. OUTER JOIN :
OUTER JOIN
retrieves
Either,
the matched rows from one table and all rows in the other table
Or,
all rows in all tables (it doesn't matter whether or not there is a match).
There are three kinds of Outer Join :
2.1 LEFT OUTER JOIN or LEFT JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the
right table. If there are no columns matching in the right table, it returns NULL
values.
2.2 RIGHT OUTER JOIN or RIGHT JOIN
This JOIN
returns all the rows from the right table in conjunction with the matching rows from the
left table. If there are no columns matching in the left table, it returns NULL
values.
2.3 FULL OUTER JOIN or FULL JOIN
This JOIN
combines LEFT OUTER JOIN
and RIGHT OUTER JOIN
. It returns rows from either table when the conditions are met and returns NULL
value when there is no match.
In other words, OUTER JOIN
is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.
Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.
3. NATURAL JOIN :
It is based on the two conditions :
- the
JOIN
is made on all the columns with the same name for equality.
- Removes duplicate columns from the result.
This seems to be more of theoretical in nature and as a result (probably) most DBMS
don't even bother supporting this.
4. CROSS JOIN :
It is the Cartesian product of the two tables involved. The result of a CROSS JOIN
will not make sense
in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).
5. SELF JOIN :
It is not a different form of JOIN
, rather it is a JOIN
(INNER
, OUTER
, etc) of a table to itself.
JOINs based on Operators
Depending on the operator used for a JOIN
clause, there can be two types of JOIN
s. They are
- Equi JOIN
- Theta JOIN
1. Equi JOIN :
For whatever JOIN
type (INNER
, OUTER
, etc), if we use ONLY the equality operator (=), then we say that
the JOIN
is an EQUI JOIN
.
2. Theta JOIN :
This is same as EQUI JOIN
but it allows all other operators like >, <, >= etc.
Many consider both EQUI JOIN
and Theta JOIN
similar to INNER
, OUTER
etc JOIN
s. But I strongly believe that its a mistake and makes the
ideas vague. Because INNER JOIN
, OUTER JOIN
etc are all connected with
the tables and their data whereas EQUI JOIN
and THETA JOIN
are only
connected with the operators we use in the former.
Again, there are many who consider NATURAL JOIN
as some sort of
"peculiar" EQUI JOIN
. In fact, it is true, because of the first
condition I mentioned for NATURAL JOIN
. However, we don't have to
restrict that simply to NATURAL JOIN
s alone. INNER JOIN
s, OUTER JOIN
s
etc could be an EQUI JOIN
too.
Accessing UI (Main) Thread safely in WPF
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
using System.Windows;
using System.Threading;
using System.Windows.Threading;
Step 2. Put the following line where you need to update UI
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
//Update UI here
}));
Syntax
[BrowsableAttribute(false)]
public object Invoke(
DispatcherPriority priority,
Delegate method
)
Parameters
priority
Type: System.Windows.Threading.DispatcherPriority
The priority, relative to the other pending operations in the
Dispatcher event queue, the specified method is invoked.
method
Type: System.Delegate
A delegate to a method that takes no arguments, which is pushed onto
the Dispatcher event queue.
Return Value
Type: System.Object
The return value from the delegate being invoked or null if the
delegate has no return value.
Version Information
Available since .NET Framework 3.0
Delete a database in phpMyAdmin
select database on the left side. Then on the right-central top you can find Operations. In that go for remove database (DROP). That's all.
How to compare two List<String> to each other?
I discovered that SequenceEqual
is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).
I wanted to test this myself so I created two methods:
/// <summary>
/// Compares two string lists using LINQ's SequenceEqual.
/// </summary>
public bool CompareLists1(List<string> list1, List<string> list2)
{
return list1.SequenceEqual(list2);
}
/// <summary>
/// Compares two string lists using a loop.
/// </summary>
public bool CompareLists2(List<string> list1, List<string> list2)
{
if (list1.Count != list2.Count)
return false;
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] != list2[i])
return false;
}
return true;
}
The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)
As it turns out, with two lists containing 32k strings, over 100 executions:
- Method 1 took an average of 6761.8 ticks
- Method 2 took an average of 3268.4 ticks
I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.
Edit:
I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):
- Method 1 took an average of 4227.2 ticks
- Method 2 took an average of 1831.9 ticks
Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920
JWT refresh token flow
Based in this implementation with Node.js of JWT with refresh token:
1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.
2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.
3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.
How do I turn off PHP Notices?
I believe commenting out display_errors in php.ini won't work because the default is On. You must set it to 'Off' instead.
Don't forget to restart Apache to apply configuration changes.
Also note that while you can set display_errors at runtime, changing it here does not affect FATAL errors.
As noted by others, ideally during development you should run with error_reporting at the highest level possible and display_errors enabled. While annoying when you first start out, these errors, warnings, notices and strict coding advice all add up and enable you to becoem a better coder.
SyntaxError: expected expression, got '<'
This code:
app.all('*', function (req, res) {
res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})
tells Express that no matter what the browser requests, your server should return index.html
. So when the browser requests JavaScript files like jquery-x.y.z.main.js
or angular.min.js
, your server is returning the contents of index.html
, which start with <!DOCTYPE html>
, which causes the JavaScript error.
Your code inside the callback should be looking at the request to determine which file to send back, and/or you should be using a different path pattern with app.all
. See the routing guide for details.
Should I use px or rem value units in my CSS?
I've found the best way to program the font sizes of a website are to define a base font size for the body
and then use em's (or rem's) for every other font-size
I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.
As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.
jQuery hover and class selector
Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:
HTML:
<ul id="menu">
<li><a href="#">Bla</a></li>
<li><a href="#">Bla</a></li>
<li><a href="#">Bla</a></li>
</ul>
CSS:
#menu {
margin: 0;
}
#menu li {
float: left;
list-style: none;
margin: 0;
}
#menu li a {
display: block;
line-height:30px;
width:100px;
background-color:#000;
}
#menu li a:hover {
background-color:#F00;
}
Can I hide the HTML5 number input’s spin box?
This is more better answer i would like to suggest on mouse over and without mouse over
input[type='number'] {
appearance: textfield;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button,
input[type='number']:hover::-webkit-inner-spin-button,
input[type='number']:hover::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0; }
How do I move focus to next input with jQuery?
You can do something like this:
$("input").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
The other answers posted here may not work for you since they depend on the next input being the very next sibling element, which often isn't the case. This approach goes up to the form and searches for the next input type element.
How can I convert a VBScript to an executable (EXE) file?
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
How do I change the title of the "back" button on a Navigation Bar
Here is the answer:
In viewDidAppear:animated
(NOT in viewDidLoad
) do the following
- (void)viewDidAppear:(BOOL)animated
{
[self.navigationController.navigationBar.backItem setTitle:@"anything"];
// then call the super
[super viewDidAppear:animated];
}
That if you want to keep the shape of the back button.
jquery function setInterval
// simple example using the concept of setInterval
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
What does AND 0xFF do?
if byte1
is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value:
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
& 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
-------------------------------
0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1
Multiple separate IF conditions in SQL Server
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
How to add a line break in an Android TextView?
There are two ways around this.
If you use your string as a raw string, you need to use the newline
character. If you use it as html, e.g. by parsing it with Html.fromString
,
the second variant is better.
1) Newline character \n
<string name="sample">This\nis a sample</string>
2) Html newline tag <br>
or <br />
<string name="sample">This<br>is a sample</string>
How to capture a backspace on the onkeydown event
Nowadays, code to do this should look something like:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
// Call event.preventDefault() to stop the character before the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
// Call event.preventDefault() to stop the character after the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
});
although in the future, once they are broadly supported in browsers, you may want to use the .key
or .code
attributes of the KeyboardEvent
instead of the deprecated .keyCode
.
Details worth knowing:
Calling event.preventDefault()
in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document
instead of a text field).
Documentation on how the value of the keyCode
attribute is determined can be found in section B.2.1 How to determine keyCode
for keydown
and keyup
events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.
There is an effort underway to deprecate the .keyCode
attribute in favour of .key
and .code
. The W3 describe the .keyCode
property as "legacy", and MDN as "deprecated".
One benefit of the change to .key
and .code
is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace"
and "Delete"
and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.
On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.
The .key
attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete"
. The .code
attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace"
.
Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode
attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
How to inject Javascript in WebBrowser control?
I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.
In this example the javascript code is injected and executed at global scope:
var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
If you want to delay execution, inject functions and call them after:
var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});
This is valid for Windows Forms and WPF WebBrowser controls.
This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.
For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).
var jsCode="alert('hello world');";
(new Function(code))();
Of course, you can delay execution:
var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();
Hope it helps
Importing JSON into an Eclipse project
on linux
pip install library_that_you_need
Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project
Check if the file exists using VBA
Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0
each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)
Private Function FileExists(fullFileName As String) As Boolean
FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
What is the use of the @Temporal annotation in Hibernate?
We use @Temporal annotation to insert date, time or both in database table.Using TemporalType we can insert data, time or both int table.
@Temporal(TemporalType.DATE) // insert date
@Temporal(TemporalType.TIME) // insert time
@Temporal(TemporalType.TIMESTAMP) // insert both time and date.
Variable not accessible when initialized outside function
My guess is that the system-status
element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?
You should declare it only, then assign its value from an onLoad
handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.
You could also try putting the script at the bottom of the page (or at least somewhere after the system-status
element is declared) but it's not guaranteed to always work.
Allow multiple roles to access controller action
Better code with adding a subclass AuthorizeRole.cs
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params Rolenames[] roles)
{
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Unauthorized" },
{ "controller", "Home" },
{ "area", "" }
}
);
//base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Login" },
{ "controller", "Account" },
{ "area", "" },
{ "returnUrl", HttpContext.Current.Request.Url }
}
);
}
}
}
How to use this
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
public ActionResult Index()
{
return View();
}
How to ping multiple servers and return IP address and Hostnames using batch script?
the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.
better do it this way
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)
this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping
overall this looks like this:
@echo off
SetLocal
set log=path/to/logfile.txt
set check=path/to/checkfile.txt
:start
echo. some echo date >>%log%
:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof
:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)
:error
echo. some errormessage to >>%log%
echo. some blat to mail?
:eof
echo. some good message to >>%log%
Insert Data Into Tables Linked by Foreign Key
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
What is the proper way to re-throw an exception in C#?
I found that if the exception is thrown in the same method that it is caught, the stack trace is not preserved, for what it's worth.
void testExceptionHandling()
{
try
{
throw new ArithmeticException("illegal expression");
}
catch (Exception ex)
{
throw;
}
finally
{
System.Diagnostics.Debug.WriteLine("finally called.");
}
}
Python Save to file
myFile = open('today','r')
ips = {}
for line in myFile:
parts = line.split()
if parts[1] == 'Failure':
ips.setdefault(parts[0], 0)
ips[parts[0]] += 1
of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
of.write(k+'\n')
Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.
Can you force Visual Studio to always run as an Administrator in Windows 8?
I know this is a little late, but I just figured out how to do this by modifying (read, "hacking") the manifest of the devenv.exe file. I should have come here first because the stated solutions seem a little easier, and probably more supported by Microsoft. :)
Here's how I did it:
- Create a project in VS called "Exe Manifests". (I think any version will work, but I used 2013 Pro. Also, it doesn't really matter what you name it.)
- "Add existing item" to the project, browse to the Visual Studio exe, and click Okay. In my case, it was "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe".
- Double-click on the "devenv.exe" file that should now be listed as a file in your project. It should bring up the exe in a resource editor.
- Expand the "RT_MANIFEST" node, then double-click on "1" under that. This will open up the executable's manifest in the binary editor.
- Find the requestedExecutionLevel tag and replace "asInvoker" with "requireAdministrator". A la:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>
- Save the file.
You've just saved the copy of the executable that was added to your project. Now you need to back up the original and copy your modified exe to your installation directory.
As I said, this is probably not the right way to do it, but it seems to work. If anyone knows of any negative fallout or requisite wrist-slapping that needs to happen, please chime in!
How do I drop table variables in SQL-Server? Should I even do this?
Indeed, you don't need to drop a @local_variable
.
But if you use #local_table
, it can be done, e.g. it's convenient to be able to re-execute a query several times.
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
/*
can DROP here, otherwise will fail with the following error
on re-execution in the same window (I use SSMS DB client):
Msg 2714, Level ..., State ..., Line ...
There is already an object named '#recent_records' in the database.
*/
DROP TABLE #recent_records
;
You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:
BEGIN TRANSACTION
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
ROLLBACK
How to determine if object is in array
You could use jQuery's grep method:
$.grep(carBrands, function(obj) { return obj.name == "ford"; });
But as you specify no jQuery, you could just make a derivative of the function. From the source code:
function grepArray( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
if ( !inv !== !callback( elems[ i ], i ) ) {
ret.push( elems[ i ] );
}
}
return ret;
}
grepArray(carBrands, function(obj) { return obj.name == "ford"; });
Using Java to pull data from a webpage?
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
Setting a width and height on an A tag
All these suggestions work unless you put the anchors inside an UL list.
<ul>
<li>
<a>click me</a>>
</li>
</ul>
Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.
How to set time to a date object in java
I should like to contribute the modern answer. This involves using java.time
, the modern Java date and time API, and not the old Date
nor Calendar
except where there’s no way to avoid it.
Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).
LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
System.out.println(utcDateDime);
This prints
2018-02-27T00:00Z
Z
means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate
from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date
object for that, convert just before handing the Date
on:
Date oldfashionedDate = Date.from(utcDateDime.toInstant());
System.out.println(oldfashionedDate);
On my computer this prints
Tue Feb 27 01:00:00 CET 2018
Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString()
grabbing the JVMs time zone and using it for producing the string.
How can I set it to something like 5:30 pm?
To answer your direct question directly, if you have a ZonedDateTime
, OffsetDateTime
or LocalDateTime
, in all of these cases the following will accomplish what you asked for:
yourDateTime = yourDateTime.with(LocalTime.of(17, 30));
If yourDateTime
was a LocalDateTime
of 2018-02-27T00:00
, it will now be 2018-02-27T17:30
. Similarly for the other types, only they include offset and time zone too as appropriate.
If you only had a date, as in the first snippet above, you can also add time-of-day information to it:
LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));
For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example
ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
.atZone(ZoneId.of("Asia/Kolkata"));
This yields 2018-02-27T17:30+05:30[Asia/Kolkata]
.
Date
and Calendar
vs java.time
The Date
class that you use as well as Calendar
and SimpleDateFormat
used in the other answers are long outdated, and SimpleDateFormat
in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.
Link: Oracle Tutorial Date Time, explaining how to use java.time
.
AngularJS - How to use $routeParams in generating the templateUrl?
Alright, think I got it...
Little background first:
The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.
So here's whatchya gotta do...
(drink beer and spend 20+ hours on it first!!!)...
When you set up your module, save the $routeProvider
globally:
// app.js:
var routeProvider
, app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){
routeProvider = $routeProvider;
$routeProvider
.when('/', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/home', {templateUrl: '/', controller: 'AppCtrl'})
.when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
.when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
.when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
.when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
.when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
.when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
.when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
.when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
.when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
.when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
.otherwise({redirectTo: '/login'});
});
// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){
var idParam = $routeParams.id;
routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
$location.path('/tasks/' + idParam + '/edit/');
});
...
That may be more info than what was needed...
Basically, you'll wanna store your Module's $routeProvider
var globally, eg as routeProvider
so that it can be accessed by your Controllers.
Then you can just use routeProvider
and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.
Then (inside your Controller), set the templateUrl
to the view you want to hit.
Take out the controller
property of the .when()
object, lest you get an infinite request loop.
And finally (still inside the Controller), use $location.path()
to redirect to the route that was just created.
If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.
And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}
.
If you clone this at this time, you'll need mongoDB on your machine to run it.
Hope this solves this issue!
Cody
Don't drink your bathwater.
Convert PDF to clean SVG?
You can use Inkscape on the commandline only, without opening a GUI. Try this:
inkscape \
--without-gui \
--file=input.pdf \
--export-plain-svg=output.svg
For a complete list of all commandline options, run inkscape --help
.
How to install PostgreSQL's pg gem on Ubuntu?
For those trying to install Redmine, I missed sudo apt-get install ruby-all-dev
after trying all of the above.
Initial error being mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h
.
Blue and Purple Default links, how to remove?
If you wants display anchors in your own choice of colors than you should define the color in anchor tag property in CSS like this:-
a { text-decoration: none; color:red; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }
see the demo:- http://jsfiddle.net/zSWbD/7/
Initialize static variables in C++ class?
Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.
// MyClass.cpp
#include "MyClass.h"
// anonymous namespace
namespace
{
string RE_ANY = "([^\\n]*)";
string RE_ANY_RELUCTANT = "([^\\n]*?)";
}
// member function (static or not)
bool MyClass::foo()
{
// logic that uses constants
return RE_ANY_RELUCTANT.size() > 0;
}
C non-blocking keyboard input
As already stated, you can use sigaction
to trap ctrl-c, or select
to trap any standard input.
Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode. The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.
You'd need to use the tcsetattr()
function to turn off ICANON mode, and probably also disable ECHO too. From memory, you also have to set the terminal back into ICANON mode when the program exits!
Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h>
functions kbhit()
and getch()
:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>
struct termios orig_termios;
void reset_terminal_mode()
{
tcsetattr(0, TCSANOW, &orig_termios);
}
void set_conio_terminal_mode()
{
struct termios new_termios;
/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);
}
int kbhit()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv);
}
int getch()
{
int r;
unsigned char c;
if ((r = read(0, &c, sizeof(c))) < 0) {
return r;
} else {
return c;
}
}
int main(int argc, char *argv[])
{
set_conio_terminal_mode();
while (!kbhit()) {
/* do some work */
}
(void)getch(); /* consume the character */
}
MySQL Install: ERROR: Failed to build gem native extension
on OSX mountain Lion: If you have brew
installed, then brew install mysql
and follow the instructions
on creating a test database with mysql on your machine.
You don't have to go all the way through, I didn't need to
After I did that I was able to bundle install and rake.
jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit:
If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
Iterating over and deleting from Hashtable in Java
You can use a temporary deletion list:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
Using multiple .cpp files in c++ program?
You can simply place a forward declaration of your second()
function in your main.cpp
above main()
. If your second.cpp
has more than one function and you want all of it in main()
, put all the forward declarations of your functions in second.cpp
into a header file and #include
it in main.cpp
.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h"
in second.cpp
. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.
matplotlib: Group boxplots
Mock data:
df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]
Group Apple Orange
0 A 0.465636 0.537723
1 A 0.560537 0.727238
2 A 0.268154 0.648927
3 B 0.722644 0.115550
4 C 0.586346 0.042896
5 B 0.562881 0.369686
6 B 0.395236 0.672477
7 C 0.577949 0.358801
8 A 0.764069 0.642724
9 C 0.731076 0.302369
You can use the Seaborn library for these plots. First melt
the dataframe to format data and then create the boxplot of your choice.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')
No Main class found in NetBeans
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class:
box until you see the connections. (Note that the class containing the main
method need not necessarily be named Main
but the main
method can have no other name.)