Note the tilda that reverses the selection. It uses pandas methods (i.e. is faster than if
/else
).
df.loc[(df['c1'] == 'Value'), 'c2'] = 10
df.loc[~(df['c1'] == 'Value'), 'c2'] = df['c3']
If origin
points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example
$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.
Pulling once from the new origin
solves the problem:
$ git stash
$ git pull origin master
$ git stash pop
Run:
docker version
If docker is running you will see:
Client: Docker Engine - Community
Version: ...
[omitted]
Server: Docker Engine - Community
Engine:
Version: ...
[omitted]
If docker is not running you will see:
Client: Docker Engine - Community
Version: ...
[omitted]
Error response from daemon: Bad response from Docker engine
The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any]
, which will make everything clunky as all hell.
return [
"title": title,
"is_draft": isDraft,
"difficulty": difficulty,
"duration": duration,
"cost": cost,
"user_id": userId,
"description": description,
"to_sell": toSell,
"images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]
This is a job for a struct. It'll vastly simplify working with this data structure.
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
If there is not substantial history on one end (aka if it is just a single readme commit on the github end), I often find it easier to manually copy the readme to my local repo and do a git push -f
to make my version the new root commit.
I find it is slightly less complicated, doesn't require remembering an obscure flag, and keeps the history a bit cleaner.
Xcode 8 and Swift 3.0
Using URLSession:
let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()
URLSession Delegate call:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
}
Using Block GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
Working fine for me.. try it 100% result guarantee
While we submit spark jobs using spark-submit utility, there is an option --jars
. Using this option, we can pass jar file to spark applications.
This excellent answer explains very well what is happening and provides a solution. I would like to add another solution that might be suitable in similar cases: using the query
method:
result = result.query("(var > 0.25) or (var < -0.25)")
See also http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-query.
(Some tests with a dataframe I'm currently working with suggest that this method is a bit slower than using the bitwise operators on series of booleans: 2 ms vs. 870 µs)
A piece of warning: At least one situation where this is not straightforward is when column names happen to be python expressions. I had columns named WT_38hph_IP_2
, WT_38hph_input_2
and log2(WT_38hph_IP_2/WT_38hph_input_2)
and wanted to perform the following query: "(log2(WT_38hph_IP_2/WT_38hph_input_2) > 1) and (WT_38hph_IP_2 > 20)"
I obtained the following exception cascade:
KeyError: 'log2'
UndefinedVariableError: name 'log2' is not defined
ValueError: "log2" is not a supported function
I guess this happened because the query parser was trying to make something from the first two columns instead of identifying the expression with the name of the third column.
A possible workaround is proposed here.
You can see if object has shape or not
def check_array(x):
try:
x.shape
return True
except:
return False
How to show uncommitted changes in Git
The command you are looking for is git diff
.
git diff
- Show changes between commits, commit and working tree, etc
Here are some of the options it expose which you can use
git diff
(no parameters)
Print out differences between your working directory and the index.
git diff --cached
:
Print out differences between the index and HEAD (current commit).
git diff HEAD
:
Print out differences between your working directory and the HEAD.
git diff --name-only
Show only names of changed files.
git diff --name-status
Show only names and status of changed files.
git diff --color-words
Word by word diff instead of line by line.
Here is a sample of the output for git diff --color-words
:
If you take a look at the result of valeur <= 0.6
, you can see what’s causing this ambiguity:
>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)
So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?
That’s exactly what numpy.any
and numpy.all
do. The former requires at least one true value, the latter requires that all values are true:
>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False
You can use def drop(col: Column)
method to drop the duplicated column,for example:
DataFrame:df1
+-------+-----+
| a | f |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+
DataFrame:df2
+-------+-----+
| a | f |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+
when I join df1 with df2, the DataFrame will be like below:
val newDf = df1.join(df2,df1("a")===df2("a"))
DataFrame:newDf
+-------+-----+-------+-----+
| a | f | a | f |
+-------+-----+-------+-----+
|107831 | ... |107831 | ... |
|107831 | ... |107831 | ... |
+-------+-----+-------+-----+
Now, we can use def drop(col: Column)
method to drop the duplicated column 'a' or 'f', just like as follows:
val newDfWithoutDuplicate = df1.join(df2,df1("a")===df2("a")).drop(df2("a")).drop(df2("f"))
you can also use .between()
method
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp[emp["Salary"].between(60000, 61000)]
Output
If there is any chance that you will need to search for empty strings,
a['Names'].str.contains('')
will NOT work, as it will always return True.
Instead, use
if '' in a["Names"].values
to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.
From the docs:
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
Try:
alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
So if you are on branch release/2.5 and you merge branch feature/new-buttons into it, then the content as found in release/2.5 is what ours refers to and the content as found on feature/new-buttons is what theirs refers to. During a merge action this is pretty straight forward.
The only problem most people fall for is the rebase case. If you do a re-base instead of a normal merge, the roles are swapped. How's that? Well, that's caused solely by the way rebasing works. Think of rebase to work like that:
Of course, that's not really what is going on but it's a nice mind model for me. And if you look at 2 and 3, you will understand why the roles are swapped now. As of 2, your current branch is now the branch from the server without any of your changes, so this is ours (the branch you are on). The changes you made are now on a different branch that is not your current one (BranchX) and thus these changes (despite being the changes you made) are theirs (the other branch used in your action).
That means if you merge and you want your changes to always win, you'd tell git to always choose "ours" but if you rebase and you want all your changes to always win, you tell git to always choose "theirs".
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Spring Boot by default has a “whitelabel” error page which you can see in a browser if you encounter a server error. Whitelabel Error Page is a generic Spring Boot error page which is displayed when no custom error page is found.
Set “server.error.whitelabel.enabled=false” to switch of the default error page
Good question. Similar to the observation you have about examples 1 and 4 (or should I say 1 & 4 :) ) over logical and
bitwise &
operators, I experienced on sum
operator. The numpy sum
and py sum
behave differently as well. For example:
Suppose "mat" is a numpy 5x5 2d array such as:
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
Then numpy.sum(mat) gives total sum of the entire matrix. Whereas the built-in sum from Python such as sum(mat) totals along the axis only. See below:
np.sum(mat) ## --> gives 325
sum(mat) ## --> gives array([55, 60, 65, 70, 75])
For some time now, you can also only rely on the data.table
package and its IDate
class plus associated functions. (Check ?as.IDate()
). So, no need to additionally install lubridate
.
require(data.table)
some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions
The error message explains it pretty well:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
What should bool(np.array([False, False, True]))
return? You can make several plausible arguments:
(1) True
, because bool(np.array(x))
should return the same as bool(list(x))
, and non-empty lists are truelike;
(2) True
, because at least one element is True
;
(3) False
, because not all elements are True
;
and that's not even considering the complexity of the N-d case.
So, since "the truth value of an array with more than one element is ambiguous", you should use .any()
or .all()
, for example:
>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True, True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False
and you might want to consider np.allclose
if you're comparing arrays of floats:
>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True
&
, |
and ~
, and parentheses (...)
is important!Python's and
, or
and not
logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.
So the following in python (exp1
and exp2
are expressions which evaluate to a boolean result)...
exp1 and exp2 # Logical AND
exp1 or exp2 # Logical OR
not exp1 # Logical NOT
...will translate to...
exp1 & exp2 # Element-wise logical AND
exp1 | exp2 # Element-wise logical OR
~exp1 # Element-wise logical NOT
for pandas.
If in the process of performing logical operation you get a ValueError
, then you need to use parentheses for grouping:
(exp1) op (exp2)
For example,
(df['col1'] == x) & (df['col2'] == y)
And so on.
Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: &
for logical AND, |
for logical OR, and ~
for logical NOT.
Consider the following setup:
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df
A B C
0 5 0 3
1 3 7 9
2 3 5 2
3 4 7 6
4 8 8 1
For df
above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.
Overloaded Bitwise &
Operator
Before continuing, please take note of this particular excerpt of the docs, which state
Another common operation is the use of boolean vectors to filter the data. The operators are:
|
foror
,&
forand
, and~
fornot
. These must be grouped by using parentheses, since by default Python will evaluate an expression such asdf.A > 2 & df.B < 3
asdf.A > (2 & df.B) < 3
, while the desired evaluation order is(df.A > 2) & (df.B < 3)
.
So, with this in mind, element wise logical AND can be implemented with the bitwise operator &
:
df['A'] < 5
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'] > 5
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
(df['A'] < 5) & (df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
And the subsequent filtering step is simply,
df[(df['A'] < 5) & (df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators <
and >
. See the section of Operator Precedence in the python docs.
If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as
df['A'] < 5 & df['B'] > 5
It is parsed as
df['A'] < (5 & df['B']) > 5
Which becomes,
df['A'] < something_you_dont_want > 5
Which becomes (see the python docs on chained operator comparison),
(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)
Which becomes,
# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2
Which throws
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
So, don't make that mistake!1
Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:
df['A'].lt(5)
0 True
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'].gt(5)
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
df['A'].lt(5) & df['B'].gt(5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
See the section on Flexible Comparisons.. To summarise, we have
+------------------------------+
¦ ¦ Operator ¦ Function ¦
¦----+------------+------------¦
¦ 0 ¦ > ¦ gt ¦
+----+------------+------------¦
¦ 1 ¦ >= ¦ ge ¦
+----+------------+------------¦
¦ 2 ¦ < ¦ lt ¦
+----+------------+------------¦
¦ 3 ¦ <= ¦ le ¦
+----+------------+------------¦
¦ 4 ¦ == ¦ eq ¦
+----+------------+------------¦
¦ 5 ¦ != ¦ ne ¦
+------------------------------+
Another option for avoiding parentheses is to use DataFrame.query
(or eval
):
df.query('A < 5 and B > 5')
A B C
1 3 7 9
3 4 7 6
I have extensively documented query
and eval
in Dynamic Expression Evaluation in pandas using pd.eval().
operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__
which corresponds to the bitwise operator.
import operator
operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
df[operator.and_(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
You won't usually need this, but it is useful to know.
Generalizing: np.logical_and
(and logical_and.reduce
)
Another alternative is using np.logical_and
, which also does not need parentheses grouping:
np.logical_and(df['A'] < 5, df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
Name: A, dtype: bool
df[np.logical_and(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
np.logical_and
is a ufunc (Universal Functions), and most ufuncs have a reduce
method. This means it is easier to generalise with logical_and
if you have multiple masks to AND. For example, to AND masks m1
and m2
and m3
with &
, you would have to do
m1 & m2 & m3
However, an easier option is
np.logical_and.reduce([m1, m2, m3])
This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):
import operator
cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]
m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m
# array([False, True, False, True, False])
df[m]
A B C
1 3 7 9
3 4 7 6
1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.
For the df
above, say you'd like to return all rows where A == 3 or B == 7.
Overloaded Bitwise |
df['A'] == 3
0 False
1 True
2 True
3 False
4 False
Name: A, dtype: bool
df['B'] == 7
0 False
1 True
2 False
3 True
4 False
Name: B, dtype: bool
(df['A'] == 3) | (df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[(df['A'] == 3) | (df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
If you haven't yet, please also read the section on Logical AND above, all caveats apply here.
Alternatively, this operation can be specified with
df[df['A'].eq(3) | df['B'].eq(7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
operator.or_
Calls Series.__or__
under the hood.
operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[operator.or_(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
np.logical_or
For two conditions, use logical_or
:
np.logical_or(df['A'] == 3, df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df[np.logical_or(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
For multiple masks, use logical_or.reduce
:
np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False, True, True, True, False])
df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
Given a mask, such as
mask = pd.Series([True, True, False])
If you need to invert every boolean value (so that the end result is [False, False, True]
), then you can use any of the methods below.
Bitwise ~
~mask
0 False
1 False
2 True
dtype: bool
Again, expressions need to be parenthesised.
~(df['A'] == 3)
0 True
1 False
2 False
3 True
4 True
Name: A, dtype: bool
This internally calls
mask.__invert__()
0 False
1 False
2 True
dtype: bool
But don't use it directly.
operator.inv
Internally calls __invert__
on the Series.
operator.inv(mask)
0 False
1 False
2 True
dtype: bool
np.logical_not
This is the numpy variant.
np.logical_not(mask)
0 False
1 False
2 True
dtype: bool
Note, np.logical_and
can be substituted for np.bitwise_and
, logical_or
with bitwise_or
, and logical_not
with invert
.
you may be create function before so, update your function again using.
Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO
In cs file:
private DataTable _dataTable;
public DataTable DataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this._dataTable = new DataTable("table");
this._dataTable.Columns.Add("col0");
this._dataTable.Columns.Add("col1");
this._dataTable.Columns.Add("col2");
this._dataTable.Rows.Add("data00", "data01", "data02");
this._dataTable.Rows.Add("data10", "data11", "data22");
this._dataTable.Rows.Add("data20", "data21", "data22");
this.grid1.DataContext = this;
}
In Xaml file:
<DataGrid x:Name="grid1"
Margin="10"
AutoGenerateColumns="True"
ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />
You can try yourself:
>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
0 1
0 1 2
1 5 6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
0 1
0 3 4
1 5 6
It is not a direct answer, but you can (if your server permit):
1) Create a model for your Organization; extra: It will be easier to populate your HTML.
2) Create a factory (FactoryGirl) for your model;
3) Create a list (create_list) with the factory;
4) 'pick' (sample) a Organization from the list with:
# Random select
option = Organization.all.sample
# Select the FIRST(0) by id
option = Organization.all[0]
# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on...
I had the same issue. Untick this checkbox. Since you are setting the content size in code.
origin is a name for remote git url. There can be many more remotes example below.
bangalore => bangalore.example.com:project.git boston => boston.example.com:project.git
as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.
It is possible that remote bangalore has advanced since you have done "fetch" or "pull"
You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
On Windows Powershell I run this:
git stash apply "stash@{1}"
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
For those using ConstraintLayout, android:windowSoftInputMode="adjustPan|adjustResize"
will not work.
What you can do is use a soft keyboard listener, set constraints of the views from bottom to bottom of the upper views, then set a vertical bias for each view (as a positional percentage between constraints) to a horizontal guideline (also positioned by percentage, but to the parent).
For each view, we just need to change app:layout_constraintBottom_toBottomOf
to @+id/guideline
when the keyboard is shown, programmatically of course.
<ImageView
android:id="@+id/loginLogo"
...
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.15" />
<RelativeLayout
android:id="@+id/loginFields"
...
app:layout_constraintVertical_bias=".15"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/loginLogo">
<Button
android:id="@+id/login_btn"
...
app:layout_constraintVertical_bias=".25"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/loginFields"/>
Generally a soft keyboard takes up no more than 50% of the height of the screen. Thus, you can set the guideline at 0.5.
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
Now programmatically, when the keyboard is not shown, we can set all the app:layout_constraintBottom_toBottomOf
back to parent, vice-versa.
unregistrar = KeyboardVisibilityEvent.registerEventListener(this, isOpen -> {
loginLayout.startAnimation(AnimationManager.getFade(200));
if (isOpen) {
setSoftKeyViewParams(loginLogo, R.id.guideline, ConstraintLayout.LayoutParams.PARENT_ID, -1, "235:64", 0.15f,
63, 0, 63, 0);
setSoftKeyViewParams(loginFields, R.id.guideline, -1, R.id.loginLogo, null, 0.15f,
32, 0, 32, 0);
setSoftKeyViewParams(loginBtn, R.id.guideline, -1, R.id.useFingerPrintIdText, null, 0.5f,
32, 0, 32, 0);
} else {
setSoftKeyViewParams(loginLogo, ConstraintLayout.LayoutParams.PARENT_ID, ConstraintLayout.LayoutParams.PARENT_ID, -1, "235:64", 0.15f,
63, 0, 63, 0);
setSoftKeyViewParams(loginFields, ConstraintLayout.LayoutParams.PARENT_ID, -1, R.id.loginLogo,null, 0.15f,
32, 0, 32, 0);
setSoftKeyViewParams(loginBtn, ConstraintLayout.LayoutParams.PARENT_ID, -1, R.id.useFingerPrintIdText,null, 0.25f,
32, 0, 32, 0);
}
});
Call this method:
private void setSoftKeyViewParams(View view, int bottomToBottom, int topToTop, int topToBottom, String ratio, float verticalBias,
int left, int top, int right, int bottom) {
ConstraintLayout.LayoutParams viewParams = new ConstraintLayout.LayoutParams(view.getLayoutParams().width, view.getLayoutParams().height);
viewParams.dimensionRatio = ratio;
viewParams.bottomToBottom = bottomToBottom;
viewParams.topToTop = topToTop;
viewParams.topToBottom = topToBottom;
viewParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
viewParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
viewParams.verticalBias = verticalBias;
viewParams.setMargins(Dimensions.dpToPx(left), Dimensions.dpToPx(top), Dimensions.dpToPx(right), Dimensions.dpToPx(bottom));
view.setLayoutParams(viewParams);
}
The important thing is to be sure to set the vertical bias in a way that would scale correctly when the keyboard is shown and not shown.
This is documented behavior. From ?as.Date
:
format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.
as.Date("01 Jan 2000")
yields an error because the format isn't one of the two listed above. as.Date("01/01/2000")
yields an incorrect answer because the date isn't in one of the two formats listed above.
I take "standard unambiguous" to mean "ISO-8601" (even though as.Date
isn't that strict, as "%m/%d/%Y" isn't ISO-8601).
If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime
. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime
and read ?LC_TIME
).
For EF Core migrationBuilder.RenameColumn
usually works fine but sometimes you have to handle indexes as well.
migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
Example error message when updating database:
Microsoft.Data.SqlClient.SqlException (0x80131904): The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.
The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.
RENAME COLUMN Identifier failed because one or more objects access this column.
In this case you have to do the rename like this:
migrationBuilder.DropIndex(
name: "IX_Questions_Identifier",
table: "Questions");
migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
migrationBuilder.CreateIndex(
name: "IX_Questions_ChangedIdentifier",
table: "Questions",
column: "ChangedIdentifier",
unique: true,
filter: "[ChangedIdentifier] IS NOT NULL");
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException
from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions
with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.
Jacob Helwig mentions in his answer that:
It looks like rev-parse is being used without sufficient error checking before-hand
Commit 62f162f from Jeff King (peff
) should improve the robustness of git rev-parse
in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):
For cases where we do not match (e.g., "
doesnotexist..HEAD
"), we would then want to try to treat the argument as a filename.
try_difference()
gets this right, and always unmunges in this case.
However,try_parent_shorthand()
never unmunges, leading to incorrect error messages, or even incorrect results:
$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
r
is a numpy (rec)array. So r["dt"] >= startdate
is also a (boolean)
array. For numpy arrays the &
operation returns the elementwise-and of the two
boolean arrays.
The NumPy developers felt there was no one commonly understood way to evaluate
an array in boolean context: it could mean True
if any element is
True
, or it could mean True
if all elements are True
, or True
if the array has non-zero length, just to name three possibilities.
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError
whenever one tries to evaluate an array in boolean context. Applying and
to
two numpy arrays causes the two arrays to be evaluated in boolean context (by
calling __bool__
in Python3 or __nonzero__
in Python2).
Your original code
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]
looks correct. However, if you do want and
, then instead of a and b
use (a-b).any()
or (a-b).all()
.
You need the table name/alias in the SELECT
part (maybe (vg.id, name)
) :
SELECT (vg.id, name) FROM v_groups vg
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;
;with C as
(
select Rel.t2ID,
Rel.t1ID,
t1.Price,
row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
from @t1 as T1
inner join @relation as Rel
on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
T2.Name as T2Name,
T2.Orders,
T1.ID as T1ID,
T1.Name as T1Name,
T1Sum.Price
from @t2 as T2
inner join (
select C1.t2ID,
sum(C1.Price) as Price,
C2.t1ID
from C as C1
inner join C as C2
on C1.t2ID = C2.t2ID and
C2.rn = 1
group by C1.t2ID, C2.t1ID
) as T1Sum
on T2.ID = T1Sum.t2ID
inner join @t1 as T1
on T1.ID = T1Sum.t1ID
In the SQL Server Management Studio, to find out details of the active transaction, execute following command
DBCC opentran()
You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands
exec sp_who2 <SPID>
exec sp_lock <SPID>
For example, if SPID is 69 then execute the command as
exec sp_who2 69
exec sp_lock 69
Now , you can kill that process using the following command
KILL 69
I hope this helps :)
You can create a custom encoder that returns a list
when it encounters a set
. Here's an example:
>>> import json
>>> class SetEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, set):
... return list(obj)
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(set([1,2,3,4,5]), cls=SetEncoder)
'[1, 2, 3, 4, 5]'
You can detect other types this way too. If you need to retain that the list was actually a set, you could use a custom encoding. Something like return {'type':'set', 'list':list(obj)}
might work.
To illustrated nested types, consider serializing this:
>>> class Something(object):
... pass
>>> json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)
This raises the following error:
TypeError: <__main__.Something object at 0x1691c50> is not JSON serializable
This indicates that the encoder will take the list
result returned and recursively call the serializer on its children. To add a custom serializer for multiple types, you can do this:
>>> class SetEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, set):
... return list(obj)
... if isinstance(obj, Something):
... return 'CustomSomethingRepresentation'
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)
'[1, 2, 3, 4, 5, "CustomSomethingRepresentation"]'
Can do the following
PRINT dbo.[FunctionName] ( [Parameter/Argument] )
E.g.:
PRINT dbo.StringSplit('77,54')
You would do that by providing a fully qualified name, e.g.:
SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id
Which would give you the id of tbl_names
You just need to delete the branch you are on. You can't use git branch -D
as this has a safety check against doing this. You can use update-ref
to do this.
git update-ref -d HEAD
Do not use rm -rf .git
or anything like this as this will completely wipe your entire repository including all other branches as well as the branch that you are trying to reset.
You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:
SELECT DISTINCT
coaches.id,
people.*,
users.*,
coaches.*
FROM "COACHES"
INNER JOIN people ON people.id = coaches.person_id
INNER JOIN users ON coaches.person_id = users.person_id
LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
rownum <= 25
It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.
You can't cast a base object to a derived type - it isn't of that type.
If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:
DerivedType D;
BaseType B;
BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type
DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL
The literal 0
has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.
As your setval
function can accept either an int
or a char*
, the compiler can not decide which overload you meant.
The easiest solution is to just cast the 0
to the right type.
Another option is to ensure the int
overload is preferred, for example by making the other one a template:
class huge
{
private:
unsigned char data[BYTES];
public:
void setval(unsigned int);
template <class T> void setval(const T *); // not implemented
template <> void setval(const char*);
};
public string FirstLetterToUpper(string str)
{
if (str == null)
return null;
if (str.Length > 1)
return char.ToUpper(str[0]) + str.Substring(1);
return str.ToUpper();
}
Old answer: This makes every first letter to upper case
public string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
Another way to get the same result:
date <- strptime(v,format="%Y%m%d")
Actually, vim does allow what you're looking for. Enter vim, and type the following commands:
:args **/*.java
:argdo set ff=unix | update | next
The first of these commands sets the argument list to every file matching **/*.java
, which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:
In my view the main difference is who says if the tests succeed or fail.
A functional test tests that the system meets predefined requirements. It is carried out and checked by the people responsible for developing the system.
An acceptance test is signed off by the users. Ideally the users will say what they want to test but in practice it is likely to be a sunset of a functional test as users don't invest enough time. Note that this view is from the business users I deal with other sets of users e.g. aviation and other safety critical might well not have this difference,
This works
EXEC sp_rename
@objname = 'ENG_TEst."[ENG_Test_A/C_TYPE]"',
@newname = 'ENG_Test_A/C_TYPE',
@objtype = 'COLUMN'
Update:
This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.
<a href="#" onclick="FB.logout();">Logout</a>
Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}"
(using quotes).
(You may also want to consider renaming your variable to ${OUTPUT_RESULTS}
)
It's a table-valued function, but you're using it as a scalar function.
Try:
where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)
But... also consider changing your function into an inline TVF, as it'll perform better.
With unqualified imported identifiers you need external search tools like grep to find out where identifiers are declared. This makes reasoning about program correctness harder.
In my cases, I solved the problem when using the labs()
instead of abs()
.
Let me present to you a glorious but terrifying hack:
import types
def _obj():
return lambda: None
def LET(bindings, body, env=None):
'''Introduce local bindings.
ex: LET(('a', 1,
'b', 2),
lambda o: [o.a, o.b])
gives: [1, 2]
Bindings down the chain can depend on
the ones above them through a lambda.
ex: LET(('a', 1,
'b', lambda o: o.a + 1),
lambda o: o.b)
gives: 2
'''
if len(bindings) == 0:
return body(env)
env = env or _obj()
k, v = bindings[:2]
if isinstance(v, types.FunctionType):
v = v(env)
setattr(env, k, v)
return LET(bindings[2:], body, env)
You can now use this LET
form as such:
map(lambda x: LET(('y', x + 1,
'z', x - 1),
lambda o: o.y * o.z),
[1, 2, 3])
which gives: [0, 3, 8]
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Delete") {
// Do things
}
});
Another important difference is that the Hashtable type supports lock-free multiple readers and a single writer at the same time, while Dictionary does not.
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
"yyyy-MM-dd hh:mm:ss.000" format does not work in all locales. For some (at least Danish) "yyyy-MM-dd hh:mm:ss,000" will work better.
I had the same problem,
what you have to do is declare the second cursor as: DECLARE [second_cursor] Cursor LOCAL For
You see"CURSOR LOCAL FOR" instead of "CURSOR FOR"
'repr' means represention. First,we create an instance of class coordinate.
x = Coordinate(3, 4)
Then if we input x into console,th output is
<__main__.Coordinate at 0x7fcd40ab27b8>
If you use repr():
>>> repr(x)
Coordinate(3, 4)
the output is as same as 'Coordinate(3, 4)',except it is a string.You can use it to recreate a instance of coordinate.
In conclusion,repr() meathod is print out a string,which is the representation of the obeject.
If this is an attempt to use one GET action for several views that POST to several actions with different models, then try add a GET action for each POST action that redirects to the first GET to prevent 404 on refresh.
Long shot but common scenario.
You can set aliases for the columns that you are selecting:
$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'
Any of the above answers are valid, or an alternative way is to expand the table name to include the database name as well - eg:
SELECT * from us_music, de_music where `us_music.genre` = 'punk' AND `de_music.genre` = 'punk'
.NET Core 2.0 has Path.GetRelativePath
, else, use this.
/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static String MakeRelativePath(String fromPath, String toPath)
{
if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
String relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
At first create multi string.xml for different languages; then use this block of code in onCreate()
method:
super.onCreate(savedInstanceState);
String languageToLoad = "fr"; // change your language here
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.main);
You can set your test properties in src/test/resources/config/application.yml
file. Spring Boot test cases will take properties from application.yml
file in test directory.
The config
folder is predefined in Spring Boot.
As per documentation:
If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
The same works for application.yml
Documentation:
Starting with Vue2, the triple braces were deprecated, you are to use v-html
.
<div v-html="task.html_content"> </div>
It is unclear from the documentation link as to what we are supposed to place inside v-html
, your variables goes inside v-html
.
Also, v-html
works only with <div>
or <span>
but not with <template>
.
If you want to see this live in an app, click here.
You can use SQL Server recursive CTE
DECLARE
@MinDate DATE = '2020-01-01',
@MaxDate DATE = '2020-02-01';
WITH Dates(day) AS
(
SELECT CAST(@MinDate as Date) as day
UNION ALL
SELECT CAST(DATEADD(day, 1, day) as Date) as day
FROM Dates
WHERE CAST(DATEADD(day, 1, day) as Date) < @MaxDate
)
SELECT* FROM dates;
The problem could be on this line:
var selectedText2 = $("#SelectedCountryId:selected").text();
It's looking for the item with id of SelectedCountryId
that is selected, where you really want the option that's selected under SelectedCountryId
, so try:
$('#SelectedCountryId option:selected').text()
My solution was replacing the MSCOMCTL.OCX on windows 10 box with one from a Windows 7 box that also had MS Access installed. For some reason, there are different MSCOMCTL.OCX 2.0 controls with the same name.
I know this sounds crazy, and might not help anyone else, but we have saved this MSCOMCTL.OCX with a readme file and it has fixed our new install errors every time.
we unregister the current MSCOMCTL.OCX that came with Windows 10 box, delete it, and register the old one we have saved.
From here:
The
versionKey
is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is__v
.If this conflicts with your application you can configure as such:
new Schema({..}, { versionKey: '_somethingElse' })
Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:
def foo(x):
return x+1
print "last"
although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.
This answer is unrelated, but if you wanted to get rid of warning and get following warning from requests:
InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
You can disable it by adding the following line to your python code:
requests.packages.urllib3.disable_warnings()
Wouldn't you be better off with
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="CMS_1.aspx"
Target="_blank">
Click here
</asp:HyperLink>
Because, to replicate your desired behavior on an asp:Button
, you have to call window.open
on the OnClientClick
event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink
is there to handle scenarios like this.
If you want to replicate this using an asp:Button
, do this.
<asp:Button ID="btn" runat="Server"
Text="SUBMIT"
OnClientClick="javascript:return openRequestedPopup();"/>
JavaScript function.
var windowObjectReference;
function openRequestedPopup() {
windowObjectReference = window.open("CMS_1.aspx",
"DescriptiveWindowName",
"menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}
For SQL Server, if using a newer version, you can use
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection
's GetSchema
method or the DataReader
'sGetSchemaTable
method.
Provided that you have a reader for the for the query, you can do something like this:
using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
var schema = reader.GetSchemaTable();
foreach(DataRow row in schema.Rows)
{
Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
}
}
See this article for further details.
@media print {
.noPrint{
display:none;
}
}
h1{
color:#f6f6;
}
_x000D_
<h1>
print me
</h1>
<h1 class="noPrint">
no print
</h1>
<button onclick="window.print();" class="noPrint">
Print Me
</button>
_x000D_
I came across another elegant solution for this:
Place your printable part inside a div with an id like this:
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
Now let's create a really simple javascript:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
SOURCE : SO Answer
If you can, go for JSON. Android comes with the complete org.json package
Enter here:
https: //console.firebase.google.com/project/your-project-name/overview
(replace your-project
with your project-name
)
and click in "Add firebase in your web app"(the red circle icon) this action show you a dialog with:
Think of a user as you normally do (username/password with access to log in and access some objects in the system) and a schema as the database version of a user's home directory. User "foo" generally creates things under schema "foo" for example, if user "foo" creates or refers to table "bar" then Oracle will assume that the user means "foo.bar".
If you are getting this error on the WordPress website, check the below solution.
For folks who ended up here and are using CYGWIN
, install following packages in cygwin and re-run:
jQuery comes with the following options which could fulfil your need in this case:
append
is used to add an element at the end of the parent div
specified in the selector:
$('ul.tabs').append('<li>An element</li>');
prepend
is used to add an element at the top/start of the parent div
specified in the selector:
$('ul.tabs').prepend('<li>An element</li>');
insertAfter
lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:
$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>
insertBefore
will do the opposite of the above:
$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
To get current language used in your app (different than preferred languages)
NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;
$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));
If user inputs
<img src="#">
In the database table just insert character this #
Works for me
Add this code in css:
select, input[type="text"]{
width:100%;
box-sizing:border-box;
}
With arrow:
>>> import arrow
>>> arrow.now().isoformat()
'2015-04-17T06:36:49.463207-05:00'
>>> arrow.utcnow().isoformat()
'2015-04-17T11:37:17.042330+00:00'
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();
I wrote small library ssl-utils-android to trust particular certificate on Android.
You can simply load any certificate by giving the filename from assets directory.
Usage:
OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());
This is the initial database of the data source when you connect.
Edited for clarity:
If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.
Here are some ways of doing this:
For example, for using Roboto, install the package using
yarn add typeface-roboto
or
npm install typeface-roboto --save
In index.js:
import "typeface-roboto";
There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.
For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html
It'll be like
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Montserrat');
</style>
Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.
Move the font to fonts
directory in your src
directory
src
|
`----fonts
| |
| `-Lato/Lato-Black.ttf
| -Lato/Lato-BlackItalic.ttf
| -Lato/Lato-Bold.ttf
| -Lato/Lato-BoldItalic.ttf
| -Lato/Lato-Italic.ttf
| -Lato/Lato-Light.ttf
| -Lato/Lato-LightItalic.ttf
| -Lato/Lato-Regular.ttf
| -Lato/Lato-Thin.ttf
| -Lato/Lato-ThinItalic.ttf
|
`----App.css
Now, in App.css
, add this
@font-face {
font-family: 'Lato';
src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
}
For ttf
format, you have to mention format('truetype')
. For woff
, format('woff')
Now you can use the font in classes.
.modal-title {
font-family: Lato, Arial, serif;
font-weight: black;
}
Install package using
yarn add webfontloader
or
npm install webfontloader --save
In src/index.js
, you can import this and specify the fonts needed
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
Not a lot of the answers here are practical for every day use. Since it is very difficult to do this properly in pure bash, I suggest the following, reliable solution (similar to one suggestion buried in a comment):
function relpath() {
python -c "import os,sys;print(os.path.relpath(*(sys.argv[1:])))" "$@";
}
Then, you can get the relative path based upon the current directory:
echo $(relpath somepath)
or you can specify that the path be relative to a given directory:
echo $(relpath somepath /etc) # relative to /etc
The one disadvantage is this requires python, but:
Note that solutions which include basename
or dirname
may not necessarily be better, as they require that coreutils
be installed. If somebody has a pure bash
solution that is reliable and simple (rather than a convoluted curiosity), I'd be surprised.
In addition to what the other replies said, if you have to parse very large files with hundreds of thousands of timestamps, date_parser
can prove to be a huge performance bottleneck, as it's a Python function called once per row. You can get a sizeable performance improvements by instead keeping the dates as text while parsing the CSV file and then converting the entire column into dates in one go:
# For a data column
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']})
df['mydatetime'] = pd.to_datetime(df['mydatetime'], exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
# For a DateTimeIndex
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']}, index_col='mydatetime')
df.index = pd.to_datetime(df.index, exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
# For a MultiIndex
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']}, index_col=['mydatetime', 'num'])
idx_mydatetime = df.index.get_level_values(0)
idx_num = df.index.get_level_values(1)
idx_mydatetime = pd.to_datetime(idx_mydatetime, exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
df.index = pd.MultiIndex.from_arrays([idx_mydatetime, idx_num])
For my use case on a file with 200k rows (one timestamp per row), that cut down processing time from about a minute to less than a second.
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
Check check for only spaces and newlines characters in text
extension String
{
var isBlank:Bool {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
}
}
using
if text.isBlank
{
//text is blank do smth
}
Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.
See here:
You would need to install the charles.crt certificate to your device.
You can also use these ways:
EXEC sp_helpdb
and:
SELECT name FROM sys.sysdatabases
Recommended Read:
Don't forget to have a look at sysdatabases VS sys.sysdatabases
A similar thread.
Try this
/.*[^a]$/
The []
denotes a character class, and the ^
inverts the character class to match everything but an a
.
For Java 8:
You can use inbuilt java.time.format.DateTimeFormatter
to reduce any chance of typos,
like
DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
ISO_ZONED_DATE_TIME represents 2011-12-03T10:15:30+01:00[Europe/Paris]
is one of the bundled standard DateTime formats provided by Oracle link
This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).
Your html will look pretty similar to the normal radio button:
<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second
In your controller you'll have declared the mValue
that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope
variable associated with the group to the desired input's value:
$scope.mValue="second"
This makes the "second" radio button selected on loading the page.
EDIT: Since AngularJS 2.x
The above approach does not work if you're using version 2.x and above. Instead use ng-checked
attribute as follows:
<input type='radio' name='gender' ng-model='genderValue' value='male' ng-checked='genderValue === male'/>Male
<input type='radio' name='gender' ng-model='genderValue' value='female' ng-checked='genderValue === female'/> Female
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154
Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.
Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)
/^(?:www\.)?(.*?)\.(?:com|au\.uk|co\.in)$/
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
I use this:
<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />
You probably mean heap memory, not memory heap.
Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.
It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
Disabling certificate checking is the wrong solution, and radically insecure.
The correct solution is to import the self-signed certificate into your truststore. An even more correct solution is to get the certificate signed by a CA.
If this is 'only for testing' it is still necessary to test the production configuration. Testing something else isn't a test at all, it's just a waste of time.
OK realized a mistake .. it has to be /:id/:id2
Anyway didn't find this in any tutorial or other StackOverflow question.
@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
onClick(){
this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
}
}
In my case I had to add the boundary to the header like the following:
const form = new FormData();
form.append(item.name, fs.createReadStream(pathToFile));
const response = await axios({
method: 'post',
url: 'http://www.yourserver.com/upload',
data: form,
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
},
});
This solution is also useful if you're working with React Native.
You can effectively remove scientific notation in printing with this code:
options(scipen=999)
You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.
Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.
Here is the working code:
#include <iostream>
#include <string> // <-- you need this if you want to use string type
using namespace std;
class name {
public:
string first;
string last;
name(string a, string b){
first = a;
last = b;
}
name () // <-- this is your explicit parameterless constructor
{}
};
int main (int argc, const char * argv[])
{
const int howManyNames = 3;
name someName[howManyNames];
return 0;
}
(BTW, you need to include to make the code compilable.)
An alternative way is to initialize your instances explicitly on declaration
name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };
Change your FirstyActivity to:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
btn_go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
MainActivity.this,
MainActivity2.class);
startActivity(i);
}
}
});
}
Hope it will help you.
My answer might be late for this post. It can be achieved through inline css within anchor tag only.
<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>
Considering isDisabled
is a property in component which can be true
or false
.
Plunker for it: https://embed.plnkr.co/TOh8LM/
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
For the first non-paste()
answer, we can look at stringr::str_c()
(and then toString()
below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.
Very simple to use, as you can see.
tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"
From its documentation file description, it fits this problem nicely.
To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.
Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString()
is basically a version of paste()
with collapse = ", "
hard-coded, so you can do
toString(tmp)
# [1] "GAD, AB"
You need to do this:
var scope = {
splitterStyle: {
height: 100
}
};
And then apply this styling to the required elements:
<div id="horizontal" style={splitterStyle}>
In your code you are doing this (which is incorrect):
<div id="horizontal" style={height}>
Where height = 100
.
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
You can't use PHP to prevent a timeout issued by nginx.
To configure nginx to allow more time see the proxy_read_timeout
directive.
I use this cross-platform one-liner:
date -d @1267619929 2>/dev/null || date -r 1267619929
It should work in both macOS and later versions of popular Linux distributions.
// check if ch is a letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
// ...
// check if ch is a digit
if (ch >= '0' && ch <= '9')
// ...
// check if ch is a whitespace
if ((ch == ' ') || (ch =='\n') || (ch == '\t'))
// ...
Source: https://docs.oracle.com/javase/tutorial/i18n/text/charintro.html
It is also possible to receive this error from a select component if the query fails in an unusual manner (eg: a sub-query returns multiple rows in an oracle oledb connection)
m2e is only included in the Java developer version of Eclipse, as you can see on this page ("Maven" topic): http://www.eclipse.org/downloads/compare.php
However, an easy way to get m2e is through the Eclipse Marketplace:
Go to Help -> Eclipse Marketplace and look for m2e. Click "Maven Integration for Eclipse", then on Install (or drag and drop the install link to your running Eclipse workspace if you opened the marketplace in a browser), et voila!
Direct browser access: http://marketplace.eclipse.org/content/maven-integration-eclipse
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
Rails 6 added an upsert
and upsert_all
methods that deliver this functionality.
Model.upsert(column_name: value)
[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.
Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.
Otherwise, you can use: find_or_initialize_by
or find_or_create_by
, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.
For example, if no user is found with the name "Roger", a new user instance is instantiated with its name
set to "Roger".
user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save
Alternatively, you can use find_or_initialize_by
.
user = User.find_or_initialize_by(name: "Roger")
In Rails 3.
user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save
You can use a block, but the block only runs if the record is new.
User.where(name: "Roger").first_or_initialize do |user|
# this won't run if a user with name "Roger" is found
user.save
end
User.find_or_initialize_by(name: "Roger") do |user|
# this also won't run if a user with name "Roger" is found
user.save
end
If you want to use a block regardless of the record's persistence, use tap
on the result:
User.where(name: "Roger").first_or_initialize.tap do |user|
user.email = "[email protected]"
user.save
end
First, make an ifstream
:
#include <fstream>
std::ifstream infile("thefile.txt");
The two standard methods are:
Assume that every line consists of two numbers and read token by token:
int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
Line-based parsing, using string streams:
#include <sstream>
#include <string>
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; } // error
// process pair (a,b)
}
You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline()
after token-based extraction got you to the end of a line already.
You have no combinator (space, >
, +
...) so no children will get involved, ever.
However, you could avoid the need for jQuery by using an ID
and getElementById
, or you could use the old getElementsByName("frmSave")[0]
or the even older document.forms['frmSave']
. jQuery is unnecessary here.
All the answers here are as expected, programmer centric, however what happens if your company uses revision control outside of source code? There are plenty of documents which aren't source code which benefit from version control, and should live close to code and not in another CMS. Most programmers don't work in isolation - we work for companies as part of a team.
With that in mind, compare ease of use, in both client tooling and training, between Subversion and git. I can't see a scenario where any distributed revision control system is going to be easier to use or explain to a non-programmer. I'd love to be proven wrong, because then I'd be able to evaluate git and actually have a hope of it being accepted by people who need version control who aren't programmers.
Even then, if asked by management why we should move from a centralised to distributed revision control system, I'd be hard pressed to give an honest answer, because we don't need it.
Disclaimer: I became interested in Subversion early on (around v0.29) so obviously I'm biased, but the companies I've worked for since that time are benefiting from my enthusiasm because I've encouraged and supported its use. I suspect this is how it happens with most software companies. With so many programmers jumping on the git bandwagon, I wonder how many companies are going to miss out on the benefits of using version control outside of source code? Even if you have separate systems for different teams, you're missing out on some of the benefits, such as (unified) issue tracking integration, whilst increasing maintenance, hardware and training requirements.
TL;DR use buffers to not use tons of memory.
We get to the crux of your problem, I believe, when we consider the memory implications of working with very large files. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as pasztorpisti points out, we gotta deal with those bigger files in chunks!
import sys
import hashlib
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536 # lets read stuff in 64kb chunks!
md5 = hashlib.md5()
sha1 = hashlib.sha1()
with open(sys.argv[1], 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(data)
sha1.update(data)
print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))
What we've done is we're updating our hashes of this bad boy in 64kb chunks as we go along with hashlib's handy dandy update method. This way we use a lot less memory than the 2gb it would take to hash the guy all at once!
You can test this with:
$ mkfile 2g bigfile
$ python hashes.py bigfile
MD5: a981130cf2b7e09f4686dc273cf7187e
SHA1: 91d50642dd930e9542c39d36f0516d45f4e1af0d
$ md5 bigfile
MD5 (bigfile) = a981130cf2b7e09f4686dc273cf7187e
$ shasum bigfile
91d50642dd930e9542c39d36f0516d45f4e1af0d bigfile
Hope that helps!
Also all of this is outlined in the linked question on the right hand side: Get MD5 hash of big files in Python
In general when writing python it helps to get into the habit of following pep-8. For example, in python variables are typically underscore separated not camelCased. But that's just style and no one really cares about those things except people who have to read bad style... which might be you reading this code years from now.
You can try using the find
function:
string str ("There are two needles in this haystack.");
string str2 ("needle");
if (str.find(str2) != string::npos) {
//.. found.
}
You are placing your result in the RETURN
value instead of in the passed @r
value.
From MSDN
(RETURN) Is the integer value that is returned. Stored procedures can return an integer value to a calling procedure or an application.
ALTER procedure S_Comp(@str1 varchar(20),@r varchar(100) out) as
declare @str2 varchar(100)
set @str2 ='welcome to sql server. Sql server is a product of Microsoft'
if(PATINDEX('%'+@str1 +'%',@str2)>0)
SELECT @r = @str1+' present in the string'
else
SELECT @r = @str1+' not present'
DECLARE @r VARCHAR(100)
EXEC S_Comp 'Test', @r OUTPUT
SELECT @r
Use ng-only-number
to allow only numbers, for example:
<input type="text" ng-only-number data-max-length=5>
You could also get this error when JRE is not set. If so, try adding JRE System Library to your project.
Under Eclipse IDE:
This happens because you put bracket of return
on the next line. That might be a common mistake if you write js without semicolons and use a style where you put opened braces on the next line.
Interpreter thinks that you return undefined and doesn't check your next line. That's the return
operator thing.
Put your opened bracket on the same line with the return
.
It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.
Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.
As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.
UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.
For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.
UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :
Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :
Find around the line 29 where it says :
isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
and replace it by (EDITED March 19, 2013: more accurate filter):
isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
UPDATE (March 19, 2013): Also replace $.browser.msie
by navigator.userAgent.match(/msie [6]/i)
around line 615 (and/or replace all $.browser.msie
instances, if any), thanks joofow
... that's it!
Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)
NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)
Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.
I just had this issue, and moving the JS references and code towards the bottom of the page before the </body>
tag fixed it for me.
Use the zzz
format specifier to get the timezone offset as hours and minutes. You also want to use the HH
format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
You don't need regex for this.
Add apache commons lang to your project (http://commons.apache.org/proper/commons-lang/), then use:
String dataYouWant = StringUtils.substringBetween(mydata, "'");
Or you can use androidx.core.text.HtmlCompat
:
HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)
Let me offer a textbook definition on "clustering index", which is taken from 15.6.1 from Database Systems: The Complete Book:
We may also speak of clustering indexes, which are indexes on an attribute or attributes such that all of tuples with a fixed value for the search key of this index appear on roughly as few blocks as can hold them.
To understand the definition, let's take a look at Example 15.10 provided by the textbook:
A relation
R(a,b)
that is sorted on attributea
and stored in that order, packed into blocks, is surely clusterd. An index ona
is a clustering index, since for a givena
-value a1, all the tuples with that value fora
are consecutive. They thus appear packed into blocks, execept possibly for the first and last blocks that containa
-value a1, as suggested in Fig.15.14. However, an index on b is unlikely to be clustering, since the tuples with a fixedb
-value will be spread all over the file unless the values ofa
andb
are very closely correlated.
Note that the definition does not enforce the data blocks have to be contiguous on the disk; it only says tuples with the search key are packed into as few data blocks as possible.
A related concept is clustered relation. A relation is "clustered" if its tuples are packed into roughly as few blocks as can possibly hold those tuples. In other words, from a disk block perspective, if it contains tuples from different relations, then those relations cannot be clustered (i.e., there is a more packed way to store such relation by swapping the tuples of that relation from other disk blocks with the tuples the doesn't belong to the relation in the current disk block). Clearly, R(a,b)
in example above is clustered.
To connect two concepts together, a clustered relation can have a clustering index and nonclustering index. However, for non-clustered relation, clustering index is not possible unless the index is built on top of the primary key of the relation.
"Cluster" as a word is spammed across all abstraction levels of database storage side (three levels of abstraction: tuples, blocks, file). A concept called "clustered file", which describes whether a file (an abstraction for a group of blocks (one or more disk blocks)) contains tuples from one relation or different relations. It doesn't relate to the clustering index concept as it is on file level.
However, some teaching material likes to define clustering index based on the clustered file definition. Those two types of definitions are the same on clustered relation level, no matter whether they define clustered relation in terms of data disk block or file. From the link in this paragraph,
An index on attribute(s) A on a file is a clustering index when: All tuples with attribute value A = a are stored sequentially (= consecutively) in the data file
Storing tuples consecutively is the same as saying "tuples are packed into roughly as few blocks as can possibly hold those tuples" (with minor difference on one talking about file, the other talking about disk). It's because storing tuple consecutively is the way to achieve "packed into roughly as few blocks as can possibly hold those tuples".
The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.
{
"config": {
"vendor-dir": "../vendor/"
},
"autoload": {
"psr-0": {"AppName": "src/"}
}
}
Or isn't this possible in your project?
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
I just found this quite impressive tutorial about jquery to javascript conversion from Jeffrey Way on Jan 19th 2012 *Copyright © 2014 Envato*
:
http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/
Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!
In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.
I proposed it in a comment to OP, and after his suggestion, i publish it has an answer for everyone to refer to.
Also, Jeffrey Way mentioned about his inspiration witch seems to be a good primer for understanding : http://sharedfil.es/js-48hIfQE4XK.html
Has a teaser, this document comparison of jQuery to javascript :
$(document).ready(function() {
// code…
});
document.addEventListener("DOMContentLoaded", function() {
// code…
});
$("a").click(function() {
// code…
})
[].forEach.call(document.querySelectorAll("a"), function(el) {
el.addEventListener("click", function() {
// code…
});
});
You should take a look.
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
You can easily make your own 'AlertView' and use it everywhere.
alertView("You really want this?");
Implement it once:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialoginterface, int i) {
// dialoginterface.cancel();
// }})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
Apart from the Distinct
extension method of LINQ, you could use a HashSet<T>
object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode
) rather than an IEqualityComparer
).
In fact, if it's appropiate for your situation, I would just use a HashSet
for storing the items in the first place.
You can use the split
command with the -b
option:
split -b 1024m file.tar.gz
It can be reassembled on a Windows machine using @Joshua's answer.
copy /b file1 + file2 + file3 + file4 filetogether
Edit: As @Charlie stated in the comment below, you might want to set a prefix explicitly because it will use x
otherwise, which can be confusing.
split -b 1024m "file.tar.gz" "file.tar.gz.part-"
// Creates files: file.tar.gz.part-aa, file.tar.gz.part-ab, file.tar.gz.part-ac, ...
Edit: Editing the post because question is closed and the most effective solution is very close to the content of this answer:
# create archives
$ tar cz my_large_file_1 my_large_file_2 | split -b 1024MiB - myfiles_split.tgz_
# uncompress
$ cat myfiles_split.tgz_* | tar xz
This solution avoids the need to use an intermediate large file when (de)compressing. Use the tar -C option to use a different directory for the resulting files. btw if the archive consists from only a single file, tar could be avoided and only gzip used:
# create archives
$ gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
# uncompress
$ cat myfile_split.gz_* | gunzip -c > my_large_file
For windows you can download ported versions of the same commands or use cygwin.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system. Replaces AT.exe.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task immediately.
/End Stops the currently running scheduled task.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
+-------------------------------------+
¦ Executed Wed 02/29/2012 10:48:36.65 ¦
+-------------------------------------+
It's quite interesting and makes me feel so powerful. :)
You don't even need to do the check manually, File.Open does it for you. Try:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Sometimes it is just a matter of closing Visual Studio 2015 and then open again.
Update: Visual Studio 2017 apparently as well.
I have had this happen on a few machines.
This does happen.
"Have you tried to delete the "Your_Solution_FileName.suo" file?"
Also computer crashing like e.g. power outage etc...
Applies to Update 2 and Update 3 as well as fresh base without any updates...
I had this problem. I had the DLL included into the project and the setting to Copy Local was true by default. Don't know why it started, since that DLL was in the project for a long while. I've heard some mentions of ReSharper possibly removing it, but I can't say I've ran a unused reference removal.
What helped me was: - Running "Update-Package Microsoft.Web.Infrastructure -Reinstall" on the project, which updated the whole solution, but didn't end up helping in and of itself. - Then I went through the projects' references and set the Copy Local to false, and then back to true. This actually resulted in a line being added into CSPROJ file under the DLL reference: True. Or something along the lines... Either way, now the build was copying the files as expected.
Running ng serve --open after creating and going into my new project "frontend" gave this error:
After creating the project, you need to run
npm install
to install all the dependencies listed in package.json
If you need to have a good and updated database, for having more performance and not requesting external services from your website, here there is a good place to download updated and accurate databases.
I'm recommending this because in my experience it was working excellent even including city and country location for my IP which most of other databases/apis failed to include/report my location except this service which directed me to this database.
(My ip location was from "Rasht" City in "Iran" when I was testing and the ip was: 2.187.21.235
equal to 45815275
)
Therefore I recommend to use these services if you're unsure about which service is more accurate:
Database:
http://lite.ip2location.com/databases
API Service:
http://ipinfodb.com/ip_location_api.php
It is pretty short using Array destructuring and String templates:
const n = 12345678;_x000D_
const digits = [...`${n}`];_x000D_
console.log(digits);
_x000D_
I optimized Allain Lalonde answer (https://stackoverflow.com/a/436676/412368). Numeric values are still supported. Should be roughly 4-5 times faster (1:03 vs 4:30), tested on a desktop with a 7GB database. http://developer.azurewebsites.net/2015/01/mssql-searchalltables/
IF OBJECT_ID ('dbo.SearchAllTables', 'P') IS NOT NULL
DROP PROCEDURE dbo.SearchAllTables;
GO
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Customized and modified: 2014-01-21
-- Tested on: SQL Server 2008 R2
DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256)
DECLARE @ColumnName nvarchar(128)
DECLARE @DataType nvarchar(128)
DECLARE @SearchStr2 nvarchar(110)
DECLARE @SearchDecimal decimal(38,19)
DECLARE @Query nvarchar(4000)
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%', '''')
SET @SearchDecimal = CASE WHEN ISNUMERIC(@SearchStr) = 1 THEN CONVERT(decimal(38,19), @SearchStr) ELSE NULL END
PRINT '@SearchStr2: ' + @SearchStr2
PRINT '@SearchDecimal: ' + CAST(@SearchDecimal AS nvarchar)
SET @TableName = ''
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar',
'int', 'bigint', 'tinyint', 'numeric', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
SET @DataType =
(
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND QUOTENAME(COLUMN_NAME) = @ColumnName
)
PRINT @TableName + '.' + @ColumnName + ' (' + @DataType + ')'
IF @ColumnName IS NOT NULL
BEGIN
IF @DataType IN ('int', 'bigint', 'tinyint', 'numeric', 'decimal')
BEGIN
IF @SearchDecimal IS NOT NULL
BEGIN
SET @Query = 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CAST(' + @ColumnName + ' AS nvarchar(110)), 3630) ' +
'FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' = ' + CAST(@SearchDecimal AS nvarchar)
PRINT ' ' + @Query
INSERT INTO @Results
EXEC (@Query)
END
END
ELSE
BEGIN
SET @Query = 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) ' +
'FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
PRINT ' ' + @Query
INSERT INTO @Results
EXEC (@Query)
END
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
END
imports
are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.
declarations
are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.
Providers
are used for injecting the services required by components, directives, pipes in the module.
In the case where just the top few commits have bad authors, you can do this all inside git rebase -i
using the exec
command and the --amend
commit, as follows:
git rebase -i HEAD~6 # as required
which presents you with the editable list of commits:
pick abcd Someone else's commit
pick defg my bad commit 1
pick 1234 my bad commit 2
Then add exec ... --author="..."
lines after all lines with bad authors:
pick abcd Someone else's commit
pick defg my bad commit 1
exec git commit --amend --author="New Author Name <[email protected]>" -C HEAD
pick 1234 my bad commit 2
exec git commit --amend --author="New Author Name <[email protected]>" -C HEAD
save and exit editor (to run).
This solution may be longer to type than some others, but it's highly controllable - I know exactly what commits it hits.
Thanks to @asmeurer for the inspiration.
try: ctrl + P
type: @
followed by the name of the class,method or variable name you search for.
private fun sendWhatsappMessage(phoneNumber:String, text:String) {
val url = if (Intent().setPackage("com.whatsapp").resolveActivity(packageManager) != null) {
"whatsapp://send?text=Hello&phone=$phoneNumber"
} else {
"https://api.whatsapp.com/send?phone=$phoneNumber&text=$text"
}
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
}
This is a much easier way to achieve this. This code checks if whatsapp is installed on the device. If it is installed, it bypasses the system picker and goes to the contact on whatsapp and prefields the text in the chat. If not installed it opens whatsapp link on your web browser.
Just in case you guys need it, Here a couple of links that can help you:
Cheers
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
Remove the text decoration for the anchor tag
<a name="Section 1" style="text-decoration : none">Section</a>
Postgres has few types of timestamps:
timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.
timestamp with timezone - The timezone offset is already included in the timestamp.
In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g. https://www.timeanddate.com/time/zone/romania/bucharest)
To add timezone you can use this example and replace the timezone offset with yours.
"your_date_column" at time zone '+03'
To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.
If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:
SELECT
"id", "Product", "Sale",
date_trunc('month',
CASE WHEN
Extract(month from t."date") > 03 AND
Extract(day from t."date") > 26 AND
Extract(hour from t."date") > 3 AND
Extract(month from t."date") < 10 AND
Extract(day from t."date") < 29 AND
Extract(hour from t."date") < 4
THEN
t."date" at time zone '+03' -- Romania TimeZone offset + DST
ELSE
t."date" at time zone '+02' -- Romania TimeZone offset
END) as "date"
FROM
public."Table" AS t
WHERE 1=1
AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month',
CASE WHEN
Extract(month from t."date") > 03 AND
Extract(day from t."date") > 26 AND
Extract(hour from t."date") > 3 AND
Extract(month from t."date") < 10 AND
Extract(day from t."date") < 29 AND
Extract(hour from t."date") < 4
THEN
t."date" at time zone '+03' -- Romania TimeZone offset + DST
ELSE
t."date" at time zone '+02' -- Romania TimeZone offset
END)
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
You get this behavior, because int array [ROW][COLUMN] = {1};
does not mean "set all items to one". Let me try to explain how this works step by step.
The explicit, overly clear way of initializing your array would be like this:
#define ROW 2
#define COLUMN 2
int array [ROW][COLUMN] =
{
{0, 0},
{0, 0}
};
However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:
int array [ROW][COLUMN] =
{
{1, 2}
};
This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.
So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.
Next, there is a rule in C allowing lax brace style. The first example could as well be written as
int array [ROW][COLUMN] = {0, 0, 0, 0};
although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write
int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."
therefore, if you attempt
int array [ROW][COLUMN] = {1};
it means "initialize the very first column in the first row to 1 and set all other items to zero".
You can run that script as a service, restart every 30 seconds
Register a service
sudo vim /etc/systemd/system/YOUR_SERVICE_NAME.service
Paste in the command below
Description=GIVE_YOUR_SERVICE_A_DESCRIPTION
Wants=network.target
After=syslog.target network-online.target
[Service]
Type=simple
ExecStart=YOUR_COMMAND_HERE
Restart=always
RestartSec=10
KillMode=process
[Install]
WantedBy=multi-user.target
Reload services
sudo systemctl daemon-reload
Enable the service
sudo systemctl enable YOUR_SERVICE_NAME
Start the service
sudo systemctl start YOUR_SERVICE_NAME
Check the status of your service
systemctl status YOUR_SERVICE_NAME
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
A div is a block element and by default 100% wide. You should just have to set the textarea width to 100%.
git add -u
-u --update Only match against already tracked files in the index rather than the working tree. That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.
If no is given, default to "."; in other words, update all tracked files in the current directory and its subdirectories.
I did have the same problem and at first I added:
<activity
android:name="com.companyname.applicationname"
android:windowSoftInputMode="adjustPan">
to my manifest file. But this alone did not solve the issue. Then as mentioned by Artem Russakovskii, I added:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="false">
</ScrollView>
in the scrollview.
This is what worked for me.
An array in C is just a memory location, so indeed, your my_custom_data[0] = '\0';
assignment simply sets the first element to zero and leaves the other elements intact.
If you want to clear all the elements of the array, you'll have to visit each element. That is what memset
is for:
memset(&arr[0], 0, sizeof(arr));
This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:
char *begin = &arr;
char *end = begin + sizeof(arr);
std::fill(begin, end, 0);
Other Alternatives from just renaming the file to .doc.....
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx
Here is a good place to start. You can also try using this Office Open XML.
http://www.ecma-international.org/publications/standards/Ecma-376.htm
If you're doing this through cygwin, you may need to use cygpath:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge `cygpath -w $BASE` `cygpath -w $LOCAL` `cygpath -w $REMOTE` `cygpath -w $MERGED`'
The performance difference between a switch
and if...else if...else
is small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switch
while it's evaluated for each if
. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.
The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.
As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.
If your path contains comma's, putting quotes around the path will work when using Process.Start(ProcessStartInfo).
It will NOT work when using Process.Start(string, string) however. It seems like Process.Start(string, string) actually removes the quotes inside of your args.
Here is a simple example that works for me.
string p = @"C:\tmp\this path contains spaces, and,commas\target.txt";
string args = string.Format("/e, /select, \"{0}\"", p);
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "explorer";
info.Arguments = args;
Process.Start(info);
You can use AWK:
$ awk '{$1=$1}1' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
$ sed 's|^[[:blank:]]*||g' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
while
/read
loopwhile read -r line
do
echo $line
done <"file"
If you're using a framework like Twitter bootstrap you could simply add class "btn" to an a tag -- I just had a user call in about this problem apparently my checkout button wasn't working because I had a button inside an a tag... instead I just added the btn class to it and it works perfectly now.. Big mistake, one that probably cost customers -- and I sometimes forget to code check everything works in IE..
E.g.
<a href="link.com" class="btn" >Checkout</a>
Based on @Attaque great answer, I propose a shorter simplified version of the datetime difference calculator:
seconds_mapping = {
'y': 31536000,
'm': 2628002.88, # this is approximate, 365 / 12; use with caution
'w': 604800,
'd': 86400,
'h': 3600,
'min': 60,
's': 1,
'mil': 0.001,
}
def get_duration(d1, d2, interval, with_reminder=False):
if with_reminder:
return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
else:
return (d2 - d1).total_seconds() / seconds_mapping[interval]
I've changed it to avoid declaring repetetive functions, removed the pretty print default interval and added support for milliseconds, weeks and ISO months (bare in mind months are just approximate, based on assumption that each month is equal to 365/12
).
Which produces:
d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)
print(get_duration(d1, d2, 'y', True)) # => (0.0, 2678400.0015)
print(get_duration(d1, d2, 'm', True)) # => (1.0, 50397.12149999989)
print(get_duration(d1, d2, 'w', True)) # => (4.0, 259200.00149999978)
print(get_duration(d1, d2, 'd', True)) # => (31.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'h', True)) # => (744.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'min', True)) # => (44640.0, 0.0014999997802078724)
print(get_duration(d1, d2, 's', True)) # => (2678400.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'mil', True)) # => (2678400001.0, 0.0004999997244524721)
print(get_duration(d1, d2, 'y', False)) # => 0.08493150689687975
print(get_duration(d1, d2, 'm', False)) # => 1.019176965856293
print(get_duration(d1, d2, 'w', False)) # => 4.428571431051587
print(get_duration(d1, d2, 'd', False)) # => 31.00000001736111
print(get_duration(d1, d2, 'h', False)) # => 744.0000004166666
print(get_duration(d1, d2, 'min', False)) # => 44640.000024999994
print(get_duration(d1, d2, 's', False)) # => 2678400.0015
print(get_duration(d1, d2, 'mil', False)) # => 2678400001.4999995
If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0
After this rebuild the solution.
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
Isn't this as simple as adding your git install to your Windows path?
E.g. Win+R rundll32.exe sysdm.cpl,EditEnvironmentVariables
Edit...PATH appending your Mysysgit install path e.g. ;C:\Program Files (x86)\Git\bin
. Re-run Cygwin and voila. As Cygwin automatically loads in the Windows environment, so too will your native install of Git.
Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.
echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y
The "/Y" parameter at the end overwrites the destination file, if it exists.
You can push with using different account. For example, if your account is A which is stored in .gitconfig and you want to use account B which is the owner of the repo you want to push.
Account B: B_user_name, B_password
Example of SSH link: https://github.com/B_user_name/project.git
The push with B account is:
$ git push https://'B_user_name':'B_password'@github.com/B_user_name/project.git
To see the account in .gitconfig
$git config --global --list
$git config --global -e
(to change account also)One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).
Change your code to:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ = "PM"; // <--
} else {
TimeOfDayStringQ = "AM"; // <--
}
Hours = 1;
}
}
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
Elaborating on @Jonathan Ray I think this does the trick a bit better
import time
import inspect
def timed(f:callable):
start = time.time()
ret = f()
elapsed = 1000*(time.time() - start)
source_code=inspect.getsource(f).strip('\n')
logger.info(source_code+": "+str(elapsed)+" seconds")
return ret
It allows to take a regular line of code, say a = np.sin(np.pi)
and transform it rather simply into
a = timed(lambda: np.sin(np.pi))
so that the timing is printed onto the logger and you can keep the same assignment of the result to a variable you might need for further work.
I suppose in Python 3.8 one could use the :=
but I do not have 3.8 yet
Install nmap,
sudo apt-get install nmap
then
nmap -sP 192.168.1.*
or more commonly
nmap -sn 192.168.1.0/24
will scan the entire .1 to .254 range
This does a simple ping scan in the entire subnet to see which hosts are online.
This will retrun you distinct Ids
var distinctIds = datatable.AsEnumerable()
.Select(s=> new {
id = s.Field<string>("id"),
})
.Distinct().ToList();
Use a DecimalFormat object with a format string of "0.#".
Or change it to height: 0.1em;
orso, minimal size of anything displayable is 1px.
The 0.05 em you are using means, get the current font size in pixels of this elements and give me 5% of it. Which for 12 pixels returns 0.6 pixels which is too little to display. if you would turn up the font size of the div to atleast 20pixels it would display fine. I suppose Chrome doesnt round up sizes to be atleast 1pixel where other browsers do.
Java Heap Memory is part of memory allocated to JVM by Operating System.
Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.
You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:
Young , Tenured and Perm generation
PermGen has been replaced with Metaspace since Java 8 release.
Regarding your queries:
Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.
Now we can easily do this using the aspect-ratio
ref property
.container {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
Also like below where we can have a variable number of columns
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
If you intend to use combination of several keys as one, then perhaps apache commnons MultiKey is your friend. I don't think it would work one by one though..
Check for open loop devices mapped to a file on the filesystem with "losetup -a". They wont show up with either lsof or fuser.
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
In my case, while setting up a Github action I just forgot to add the env variables to the yml file:
jobs:
build:
env:
VAR1: 1
VAR2: 5
Have you considered simply using System.Drawing namespace? For example:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();
Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
I had the same problem (NetBeans 6.9.1) and the fix is so simple :)
I realized NetBeans didn't create a META-INF folder and thus no context.xml
was found, so I create the META-INF folder under the main project folder and create file context.xml
with the following content.
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/home"/>
And it runs :)
Runtime rt = Runtime.getRuntime();
rt.maxMemory()
value is b
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.getMemoryClass()
value is MB
From oracle Sql developer, execute the below in sql worksheet:
create user lctest identified by lctest;
grant dba to lctest;
then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.
The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).
So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)
first of all: as far as i know placing dialog inside a tabview is a bad practice... you better take it out...
and now to your question:
sorry, took me some time to get what exactly you wanted to implement,
did at my web app myself just now, and it works
as I sayed before place the p:dialog out side the `p:tabView ,
leave the p:dialog as you initially suggested :
<p:dialog modal="true" widgetVar="dlg">
<h:panelGrid id="display">
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
and the p:commandlink should look like this (all i did is to change the update attribute)
<p:commandLink update="display" oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
the same works in my web app, and if it does not work for you , then i guess there is something wrong in your java bean code...
SELECT * from table where field in (SELECT distinct field from table)
You also need to make sure what is in the .bashrc file of the user.
I've also got this ridiculous error because I put cd
and ls
commands in there, as it was mean to let them see the current files & directories when the user is has logged in from ssh.
In MSVC there is a Microsoft specific keyword for that: __super
MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
Simply creating a filter will do the trick. (Answered for Angular 1.6)
.filter('trustHtml', [
'$sce',
function($sce) {
return function(value) {
return $sce.trustAs('html', value);
}
}
]);
And use this as follow in the html.
<h2 ng-bind-html="someScopeValue | trustHtml"></h2>
try {
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
List<User> lstUser = null;
JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
lstUser = mapper.readValue(jp, tRef);
for (User user : lstUser) {
System.out.println(user.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Appsamuck iPhone tutorials is aiming for 31 days of tutorials ending in 31 small apps developed for the iPhone all the source code for which is available to download. They also provide a commercial service to build apps!
If you want to know if you can do the coding, well at least you can download the code and see if anything there is helpful for your needs. On the flip side you can also get a quote from them for developing the app for you, so you can try both sides of the coin, outsource and in-house. Of course it all depends on how much time you have too! It's certainly worth a look!
(OK, after my last disastrous attempt to try and post a useful piece of help, I went off hunting around!)
If you are trying to use the null coalescing operator ??
in a version of PHP prior to PHP 7 you will get this error.
<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP
A similar error can occur for nullable types, as in:
function add(?int $sum): ?int {
Which again indicates an outdated PHP version being used (either the CLI version php -v
or the webserver bound one phpinfo();
).
The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.
On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.
As mentioned above @NotNull
does nothing on its own. A good way of using @NotNull
would be using it with Objects.requireNonNull
public class Foo {
private final Bar bar;
public Foo(@NotNull Bar bar) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
}
}
Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:
// ...
string payload = JsonConvert.SerializeObject(new
{
agent = new
{
name = "Agent Name",
version = 1,
},
username = "username",
password = "password",
token = "xxxxx",
});
var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
// ...
You can use this code to find correct browser and you can make changes for any target browser.....
function myFunction() { _x000D_
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
alert('Opera');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
alert('Chrome');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
alert('Safari');_x000D_
}_x000D_
else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
alert('Firefox');_x000D_
}_x000D_
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
alert('IE'); _x000D_
} _x000D_
else{_x000D_
alert('unknown');_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
Your problem is that you are NOT testing the length of the array until it is too late.
But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.
The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.
Chances are, you'll have cut
as well. If so:
[me@home]$ echo "pid: 1234" | cut -d" " -f2
1234
What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.
Using the same key you can generate, & reverify, edit, etc.
For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.
Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length
you can use online generator, or manually write
I prefer using openssl
C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg
generate, then encode with base 64
C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20
The generated value is saved inside the file named "openssl-secret.txt"
generate, & store into a file.
One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.
I recommend reading this article
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
You can split the string with no separator arg, which will treat consecutive whitespace as a single separator (including newlines and tabs). Then join using a space:
In : " ".join("\n\nsome text \r\n with multiple whitespace".split())
Out: 'some text with multiple whitespace'
I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.
@echo off
@break off
@title Create folder with batch but only if it doesn't already exist - D3F4ULT
@color 0a
@cls
setlocal EnableDelayedExpansion
if not exist "C:\VTS\" (
mkdir "C:\VTS\"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)
pause
exit
Check below code may will help you, Using stroke can make border in edit text and change it's color too as shown below...
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="@color/secondary" />
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
Add this as background in to edit text. Thanks!
That may be overhead but should work.
double yourDouble = 1.05;
string stringForm = yourDouble.ToString();
int dotPosition = stringForm.IndexOf(".");
decimal decimalPart = Decimal.Parse("0" + stringForm.Substring(dotPosition));
Console.WriteLine(decimalPart); // 0.05
You shouldn't launch as an IIS server. check your launch setting, make sure it switched to your project name( change this name in your launchSettings.json
file ), not the IIS.
If infinity is a possible value, I would use numpy.isfinite
numpy.isfinite(myarray).all()
If the above evaluates to True
, then myarray
contains no, numpy.nan
, numpy.inf
or -numpy.inf
values.
numpy.nan
will be OK with numpy.inf
values, for example:
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
You can also restrict keys to permissible commands (in the authorized_keys file).
I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")
According to my practice, I use the 40 x 40 for standard iPad tab bar item icon, 80 X 80 for retina.
From the Apple reference. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1
If you want to create a bar icon that looks like it's related to the iOS 7 icon family, use a very thin stroke to draw it. Specifically, a 2-pixel stroke (high resolution) works well for detailed icons and a 3-pixel stroke works well for less detailed icons.
Regardless of the icon’s visual style, create a toolbar or navigation bar icon in the following sizes:
About 44 x 44 pixels About 22 x 22 pixels (standard resolution) Regardless of the icon’s visual style, create a tab bar icon in the following sizes:
About 50 x 50 pixels (96 x 64 pixels maximum) About 25 x 25 pixels (48 x 32 pixels maximum) for standard resolution
select * from table where value % 2 = 1
works fine in mysql.
a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([0,5,4]))
It provides true output.
a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([1,3]))
It provides false output.
Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
if (e1.getKey().equals(e2.getKey())) {
return res; // Code will now handle equality properly
} else {
return res != 0 ? res : 1; // While still adding all entries
}
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)
Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.
First of all, it is a waste of an executor slot to wrap the build
step in node
. Your upstream executor will just be sitting idle for no reason.
Second, from a multibranch project, you can use the environment variable BRANCH_NAME
to make logic conditional on the current branch.
Third, the job
parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.
Thus what you meant to write is probably
if (env.BRANCH_NAME == 'master') {
build '../other-repo/master'
}
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent
so you don't need to wrap it with a call to Html.Raw()
.
It should be as simple as:
<script>
var json = @Json.Serialize(Model.CollegeInformationlist);
</script>
In MySQL, the word 'type' is a Reserved Word.
For big file use the following code (you are less memory hungry)
Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
//Your stuff
});
The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.
Unfortunately the switch option to mount a volume is only found in the run
command.
docker run --help
-v, --volume list Bind mount a volume (default [])
There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.
docker container export -o ./myimage.docker mycontainer
docker import ./myimage.docker myimage
docker run -i -t -v /somedir --name mycontainer myimage /bin/bash
SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995
You can use and implement Secure Licensing API from very easily in your Software Projects using it,(you need to download the desktop application for creating secure license from https://www.systemsoulsoftwares.com/)
I faced similar issues with POST Request where GET Request was working fine on my backend which i am passing my variables etc. The problem lies in there that the backend does a lot of redirects, which didnt work with fopen or the php header methods.
So the only way i got it working was to put a hidden form and push over the values with a POST submit when the page is loaded.
echo
'<body onload="document.redirectform.submit()">
<form method="POST" action="http://someurl/todo.php" name="redirectform" style="display:none">
<input name="var1" value=' . $var1. '>
<input name="var2" value=' . $var2. '>
<input name="var3" value=' . $var3. '>
</form>
</body>';
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
To expand this question into the realm of use outside of Excel s own VBA, the ActiveWindow property must be addressed as a child of the Excel.Application object.
Example for creating an Excel workbook from Access:
Using the Excel.Application object in another Office application's VBA project will require you to add Microsoft Excel 15.0 Object library (or equivalent for your own version).
Option Explicit
Sub xls_Build__Report()
Dim xlApp As Excel.Application, ws As Worksheet, wb As Workbook
Dim fn As String
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
xlApp.Visible = True
Set wb = xlApp.Workbooks.Add
With wb
.Sheets(1).Name = "Report"
With .Sheets("Report")
'report generation here
End With
'This is where the Freeze Pane is dealt with
'Freezes top row
With xlApp.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
fn = CurrentProject.Path & "\Reports\Report_" & Format(Date, "yyyymmdd") & ".xlsx"
If CBool(Len(Dir(fn, vbNormal))) Then Kill fn
.SaveAs FileName:=fn, FileFormat:=xlOpenXMLWorkbook
End With
Close_and_Quit:
wb.Close False
xlApp.Quit
End Sub
The core process is really just a reiteration of previously submitted answers but I thought it was important to demonstrate how to deal with ActiveWindow when you are not within Excel's own VBA. While the code here is VBA, it should be directly transcribable to other languages and platforms.
It seems this is true but, personally, it seems to me to be poor design. Sure, have a default name (with extension) but allow other names and have a way of specifying the name of the docker file for commands.
Having an extension is also nice because it allows one to associate applications to that extension type. When I click on a Dockerfile in MacOSX it treats it as a Unix executable and tries to run it.
If Docker files had an extension I could tell the OS to start them with a particular application, e.g. my text editor application. I'm not sure but the current behaviour may also be related to the file permisssions.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
The opposite of Raymond's solution:
sed -n '/^#/!p'
"don't print anything, except for lines that DON'T start with #"
Try using ifconfig -a
. Look for "inet xxx.xxx.xxx.xxx", that is your IP address
I'm answering on specific to this error code(08s01).
usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".
1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.
2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days
3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.
This is how I solved it for my website. I redirected all the pages without www to www.site.com. This way, it will always take localstorage of www.site.com
Add the following to your .htacess, (create one if you already don't have it) in root directory
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Yes this is possible. kizzie is correct with the session_start();
having to go first.
another observation I made is that you need to filter your form data using:
strip_tags($value);
and/or
stripslashes($value);