I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called?
You can use a macro function instead of return statement in the specific function.
For example, instead of using return,
int foo(...)
{
if (error happened)
return -1;
... do something ...
return 0
}
You can use a macro function.
#include "c-callstack.h"
int foo(...)
{
if (error happened)
NL_RETURN(-1);
... do something ...
NL_RETURN(0);
}
Whenever an error happens in a function, you will see Java-style call stack as shown below.
Error(code:-1) at : so_topless_ranking_server (sample.c:23)
Error(code:-1) at : nanolat_database (sample.c:31)
Error(code:-1) at : nanolat_message_queue (sample.c:39)
Error(code:-1) at : main (sample.c:47)
Full source code is available here.
The stack is just a way that programs and functions use memory.
The stack always confused me, so I made an illustration:
Hope it's more helpful than confusing.
Feel free to use the SVG image (CC0 licensed).
you can find your recursive function in crome browser,press ctrl+shift+j and then source tab, which gives you code compilation flow and you can find using break point in code.
Try accessing this:
arguments.callee.caller.name
A quick wrap up. Maybe someone has a better explanation.
A call stack is composed of 1 or many several stack frames. Each stack frame corresponds to a call to a function or procedure which has not yet terminated with a return.
To use a stack frame, a thread keeps two pointers, one is called the Stack Pointer (SP), and the other is called the Frame Pointer (FP). SP always points to the "top" of the stack, and FP always points to the "top" of the frame. Additionally, the thread also maintains a program counter (PC) which points to the next instruction to be executed.
The following are stored on the stack: local variables and temporaries, actual parameters of the current instruction (procedure, function, etc.)
There are different calling conventions regarding the cleaning of the stack.
The answer with for
is correct, but if you really want to use functional style avoiding for
statement - you can use the following instead of your expression:
Array.from(Array(1000000), () => Math.random());
The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.
Following the same idea you can rewrite it using ES2015 Spread operator:
[...Array(1000000)].map(() => Math.random())
In both examples you can get an index of the iteration if you need, for example:
[...Array(1000000)].map((_, i) => i + Math.random())
In some languages this can be solved with tail call optimization, where the recursion call is transformed under the hood into a loop so no maximum stack size reached error exists.
But in javascript the current engines don't support this, it's foreseen for new version of the language Ecmascript 6.
Node.js has some flags to enable ES6 features but tail call is not yet available.
So you can refactor your code to implement a technique called trampolining, or refactor in order to transform recursion into a loop.
Excel's interface for SQL Server queries will not let you have a custom parameters. A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties. Here are the detailed steps for Excel 2010:
There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
Then switch the button state to Selected:
[btnCheckButton setSelected:YES];
Then switch the button state to Normal:
[btnCheckButton setSelected:NO];
In my case, I've just downloaded the missing file directly from here: https://gitlab.com/mailman/mailman-website/raw/a97d6b4c5b29594004e3855f1ab1222449d0c211/content/fonts/glyphicons-halflings-regular.woff2
Following up @Tim Mahy - There's two possible ways to feed SqlBulkCopy: a DataReader or via DataTable. Here the code for DataTable:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
foreach (Entry entry in entries)
dt.Rows.Add(new string[] { entry.Id, entry.Name });
using (SqlBulkCopy bc = new SqlBulkCopy(connection))
{ // the following 3 lines might not be neccessary
bc.DestinationTableName = "Entries";
bc.ColumnMappings.Add("Id", "Id");
bc.ColumnMappings.Add("Name", "Name");
bc.WriteToServer(dt);
}
I tried an above answer and didn't work until I switched the statements. This is what worked for me:
myEditText.setSelectAllOnFocus(true);
myEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickMyEditText();
}
});
private void onClickMyEditText() {
if(myEditText.isFocused()){
myEditText.clearFocus();
myEditText.requestFocus();
}else{
myEditText.requestFocus();
myEditText.clearFocus();
}
}
I had to ask if the focus is on the EditText, and if not request the focus first and then clear it. Otherwise the next times I clicked on the EditText the virtual keyboard would never appear
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
Check Database Size in SQL Server for both Azure and On-Premises-
Method 1 – Using ‘sys.database_files’ System View
SELECT
DB_NAME() AS [database_name],
CONCAT(CAST(SUM(
CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;
Method 2 – Using ‘sp_spaceused’ System Stored Procedure
EXEC sp_spaceused ;
There is a trick to push postgres to prefer a seqscan adding a OFFSET 0
in the subquery
This is handy for optimizing requests linking big/huge tables when all you need is only the n first/last elements.
Lets say you are looking for first/last 20 elements involving multiple tables having 100k (or more) entries, no point building/linking up all the query over all the data when what you'll be looking for is in the first 100 or 1000 entries. In this scenario for example, it turns out to be over 10x faster to do a sequential scan.
I'd consider using a nullable types.
DateTime? myDate
instead of DateTime myDate
.
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
If you have forked a repository fro Delete your forked copy and fork it again from master.
Shortly:
$("#selectBox").attr("selectedIndex",index)
where index is the selected index as integer.
The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).
Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s
On a server using a logon script, tell the logon to run the batch file. Jason
I had the same error after I installed new packages or updated them:
...
npm ERR! code ELIFECYCLE
npm ERR! errno 1
...
It helped me to run installation command once again or a couple of times. After that, the error disappeared.
auto: The browser sets the margin. The result of this is dependant of the browser
margin:0 auto specifies
* top and bottom margins are 0
* right and left margins are auto
useHistory
hook:If you have React >= 16.8
and functional components you can use the useHistory
hook from react-router.
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
withRouter
HOC:As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
browserHistory
You can achieve this functionality using react-router BrowserHistory
. Code below:
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
connected-react-router
If you have connected your component with redux, and have configured connected-react-router all you have to do is
this.props.history.push("/new/url");
ie, you don't need withRouter
HOC to inject history
to the component props.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
if test -e "$file_name";then
...
fi
if grep -q "poet" $file_name; then
..
fi
Another late to the party, using the preprocessor:
1 #define MY_ENUM_LIST \
2 DEFINE_ENUM_ELEMENT(First) \
3 DEFINE_ENUM_ELEMENT(Second) \
4 DEFINE_ENUM_ELEMENT(Third) \
5
6 //--------------------------------------
7 #define DEFINE_ENUM_ELEMENT(name) , name
8 enum MyEnum {
9 Zeroth = 0
10 MY_ENUM_LIST
11 };
12 #undef DEFINE_ENUM_ELEMENT
13
14 #define DEFINE_ENUM_ELEMENT(name) , #name
15 const char* MyEnumToString[] = {
16 "Zeroth"
17 MY_ENUM_LIST
18 };
19 #undef DEFINE_ENUM_ELEMENT
20
21 #define DEFINE_ENUM_ELEMENT(name) else if (strcmp(s, #name)==0) return name;
22 enum MyEnum StringToMyEnum(const char* s){
23 if (strcmp(s, "Zeroth")==0) return Zeroth;
24 MY_ENUM_LIST
25 return NULL;
26 }
27 #undef DEFINE_ENUM_ELEMENT
(I just put in line numbers so it's easier to talk about.) Lines 1-4 are what you edit to define the elements of the enum. (I have called it a "list macro", because it's a macro that makes a list of things. @Lundin informs me these are a well-known technique called X-macros.)
Line 7 defines the inner macro so as to fill in the actual enum declaration in lines 8-11. Line 12 undefines the inner macro (just to silence the compiler warning).
Line 14 defines the inner macro so as to create a string version of the enum element name. Then lines 15-18 generate an array that can convert an enum value to the corresponding string.
Lines 21-27 generate a function that converts a string to the enum value, or returns NULL if the string doesn't match any.
This is a little cumbersome in the way it handles the 0th element. I've actually worked around that in the past.
I admit this technique bothers people who don't want to think the preprocessor itself can be programmed to write code for you. I think it strongly illustrates the difference between readability and maintainability. The code is difficult to read, but if the enum has a few hundred elements, you can add, remove, or rearrange elements and still be sure the generated code has no errors.
For the hell of it...
This solution is different to all earlier solutions, viz:
But first - note the question does not specify where such strings are stored. In my solution below, I create a CTE as a quick and dirty way to put these strings into some kind of "source table".
Note also - this solution uses a recursive common table expression (CTE) - so don't get confused by the usage of two CTEs here. The first is simply to make the data avaliable to the solution - but it is only the second CTE that is required in order to solve this problem. You can adapt the code to make this second CTE query your existing table, view, etc.
Lastly - my coding is verbose, trying to use column and CTE names that explain what is going on and you might be able to simplify this solution a little. I've added in a few pseudo phone numbers with some (expected and atypical, as the case may be) formatting for the fun of it.
with SOURCE_TABLE as (
select '003Preliminary Examination Plan' as numberString
union all select 'Coordination005' as numberString
union all select 'Balance1000sheet' as numberString
union all select '1300 456 678' as numberString
union all select '(012) 995 8322 ' as numberString
union all select '073263 6122,' as numberString
),
FIRST_CHAR_PROCESSED as (
select
len(numberString) as currentStringLength,
isNull(cast(try_cast(replace(left(numberString, 1),' ','z') as tinyint) as nvarchar),'') as firstCharAsNumeric,
cast(isNull(cast(try_cast(nullIf(left(numberString, 1),'') as tinyint) as nvarchar),'') as nvarchar(4000)) as newString,
cast(substring(numberString,2,len(numberString)) as nvarchar) as remainingString
from SOURCE_TABLE
union all
select
len(remainingString) as currentStringLength,
cast(try_cast(replace(left(remainingString, 1),' ','z') as tinyint) as nvarchar) as firstCharAsNumeric,
cast(isNull(newString,'') as nvarchar(3999)) + isNull(cast(try_cast(nullIf(left(remainingString, 1),'') as tinyint) as nvarchar(1)),'') as newString,
substring(remainingString,2,len(remainingString)) as remainingString
from FIRST_CHAR_PROCESSED fcp2
where fcp2.currentStringLength > 1
)
select
newString
,* -- comment this out when required
from FIRST_CHAR_PROCESSED
where currentStringLength = 1
So what's going on here?
Basically in our CTE we are selecting the first character and using try_cast
(see docs) to cast it to a tinyint
(which is a large enough data type for a single-digit numeral). Note that the type-casting rules in SQL Server say that an empty string (or a space, for that matter) will resolve to zero, so the nullif
is added to force spaces and empty strings to resolve to null (see discussion) (otherwise our result would include a zero character any time a space is encountered in the source data).
The CTE also returns everything after the first character - and that becomes the input to our recursive call on the CTE; in other words: now let's process the next character.
Lastly, the field newString
in the CTE is generated (in the second SELECT
) via concatenation. With recursive CTEs the data type must match between the two SELECT
statements for any given column - including the column size. Because we know we are adding (at most) a single character, we are casting that character to nvarchar(1) and we are casting the newString
(so far) as nvarchar(3999). Concatenated, the result will be nvarchar(4000) - which matches the type casting we carry out in the first SELECT
.
If you run this query and exclude the WHERE
clause, you'll get a sense of what's going on - but the rows may be in a strange order. (You won't necessarily see all rows relating to a single input value grouped together - but you should still be able to follow).
Hope it's an interesting option that may help a few people wanting a strictly expression-based solution.
Your curl
command is entirely wrong. You should be using the following
curl -H 'Authorization: token <MYTOKEN>' ...
That aside, that doesn't authorize your computer to clone the repository if in fact it is private. (Taking a look, however, indicates that it is not.) What you would normally do is the following:
git clone https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git --branch=gh-pages gh-pages
That will add your credentials to the remote created when cloning the repository. Unfortunately, however, you have no control over how Travis clones your repository, so you have to edit the remote like so.
# After cloning
cd gh-pages
git remote set-url origin https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git
That will fix your project to use a remote with credentials built in.
Warning: Tokens have read/write access and should be treated like passwords. If you enter your token into the clone URL when cloning or adding a remote,
Git writes it to your .git/config file in plain text, which is a security risk.
As @gfullam stated in a comment to @BoffinbraiN's answer, the <dir>
you are deleting itself might not be the one which contains files: there might be subdirectories in <dir>
that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm
from UNIX. rm.exe
comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.
Batch script example:
set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"
Found all the windows binaries here :
https://github.com/ojdkbuild/ojdkbuild
These Windows binaries are built to keep them as close as possible in behaviour to java-x-openjdk CentOS packages.
If you need an os independent method, works across Windows and Linux. Use python
$ python -c 'import multiprocessing as m; print m.cpu_count()'
16
By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com
it will use GET. If you use -d
or -F
curl will use POST, -I
will cause a HEAD and -T
will make it a PUT.
If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]
. This way you can for example send a DELETE by doing curl -X DELETE [URL]
.
It is thus pointless to do curl -X GET [URL]
as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]...
But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL]
.
curl -GET
(using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G
, -E
and -T
options and that will do something completely different.
There's also a curl option called --get
to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d
into a GET request instead of a POST.
(I subsequently used my own answer here to populate the curl FAQ to cover this.)
Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v
) - to make users aware. Further explained and motivated in this blog post.
You can ask curl to convert a set of -d
options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:
curl -d name=daniel -d grumpy=yes -G https://example.com/
data1.reset_index(inplace=True)
select 'i like' || type_column || ' with' ect....
date -d "yesterday" '+%Y-%m-%d'
To use this later:
date=$(date -d "yesterday" '+%Y-%m-%d')
<parent>
<groupId>com.test.vaquar.khan</groupId>
<artifactId>vk-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../projectname/pom.xml</relativePath>
</parent>
Add following line in parent
<relativePath>../projectname/pom.xml</relativePath>
You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path
Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/
The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.
You can try and do this:
myLabel.setText("<html>" + myString.replaceAll("<","<").replaceAll(">", ">").replaceAll("\n", "<br/>") + "</html>")
The advantages of doing this are:
<br/>
, without fail.<
and >
with <
and >
respectively, preventing some render havoc.What it does is:
"<html>" +
adds an opening html
tag at the beginning.replaceAll("<", "<").replaceAll(">", ">")
escapes <
and >
for convenience.replaceAll("\n", "<br/>")
replaces all newlines by br
(HTML line break) tags for what you wanted+ "</html>"
closes our html
tag at the end.P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
I have the same problem with spring 3.0.2 and spring-beans-3.0.xsd.
My solution:
Create a file META-INF/spring.schemas in the source folder and copy all necesary definitions. Create spring.handlers too.
I think that the class PluggableSchemaResolver is not working correctly.
from the javadoc:
"By default, this class will look for mapping files in the classpath using the pattern: META-INF/spring.schemas allowing for multiple files to exist on the classpath at any one time."
but in my case, this class only read the first spring.schemas finded.
Grettings. pacovr
I've created a stored function for this text comparison purpose:
CREATE OR REPLACE FUNCTION TextCompare(vOperand1 IN VARCHAR2, vOperator IN VARCHAR2, vOperand2 IN VARCHAR2) RETURN NUMBER DETERMINISTIC AS
BEGIN
IF vOperator = '=' THEN
RETURN CASE WHEN vOperand1 = vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '<>' THEN
RETURN CASE WHEN vOperand1 <> vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
ELSIF vOperator = '<=' THEN
RETURN CASE WHEN vOperand1 <= vOperand2 OR vOperand1 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '>=' THEN
RETURN CASE WHEN vOperand1 >= vOperand2 OR vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '<' THEN
RETURN CASE WHEN vOperand1 < vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NOT NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '>' THEN
RETURN CASE WHEN vOperand1 > vOperand2 OR vOperand1 IS NOT NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = 'LIKE' THEN
RETURN CASE WHEN vOperand1 LIKE vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = 'NOT LIKE' THEN
RETURN CASE WHEN vOperand1 NOT LIKE vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
ELSE
RAISE VALUE_ERROR;
END IF;
END;
In example:
SELECT * FROM MyTable WHERE TextCompare(MyTable.a, '>=', MyTable.b) = 1;
TCP has "open" and a "close" procedures in the protocol. Once "opened", a connection is held until "closed". But there are lots of things that can stop the data flow abnormally. That being said, the techniques to determine if it is possible to use a link are highly dependent on the layers of software between the protocol and the application program. The ones mentioned above focus on a programmer attempting to use a socket in a non-invasive way (read or write 0 bytes) are perhaps the most common. Some layers in libraries will supply the "polling" for a programmer. For example Win32 asych (delayed) calls can Start a read that will return with no errors and 0 bytes to signal a socket that cannot be read any more (presumably a TCP FIN procedure). Other environments might use "events" as defined in their wrapping layers. There is no single answer to this question. The mechanism to detect when a socket cannot be used and should be closed depends on the wrappers supplied in the libraries. It is also worthy to note that sockets themselves can be reused by layers below an application library so it is wise to figure out how your environment deals with the Berkley Sockets interface.
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
One obvious and straightforward possibility is to use "if-else conditions". In that example
x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)
** For the additional question in the edit** Is that what you expect ?
> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
>
> w <- ifelse((d1 == "e") & (d2 == "e"), 1,
+ ifelse((d1=="a") & (d2 == "b"), 2,
+ ifelse((d1 == "e"), 3, 99)))
>
> data.frame(d1, d2, w)
d1 d2 w
1 e e 1
2 c a 99
3 a b 2
If you do not feel comfortable with the ifelse
function, you can also work with the if
and else
statements for such applications.
You can handle this by :
class Box {
x: number;
y: number;
height: number;
width: number;
constructor(obj?: Partial<Box>) {
assign(this, obj);
}
}
Partial will make your fields (x,y, height, width) optionals, allowing multiple constructors
eg: you can do new Box({x,y})
without height, and width.
$ git branch -D <branch-name>
[NOTE]:
-D
is a shortcut for --delete --force
.
There are many Oracle components that run a web service, so it's not clear which you are referring to.
For example, the web site port for standalone OC4J is configured in the j2ee/home/config/default-web-site.xml file:
<web-site xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/web-site-10_0.xsd"
port="8888" display-name="OC4J 10g (10.1.3) Default Web Site"
schema-major-version="10" schema-minor-version="0" >
By default, variables created within a script are only available to the current shell; child processes (sub-shells) will not have access to values that have been set or modified. Allowing child processes to see the values, requires use of the export command.
i know this is way too late. but i had the same requirement. i solved like this
<android.support.v7.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardUseCompatPadding="true"
app:cardElevation="4dp"
app:cardCornerRadius="3dp" >
<!-- put whatever you want -->
</android.support.v7.widget.CardView>
you need to add dependency:
compile 'com.android.support:cardview-v7:25.0.1'
There is another way to do this:
//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck
In my case it seems the problem was a weird caching problem. The solutions above didn't work.
If your code was working fine and you added a column to one of your tables and it gives the 'invalid column name' error, and the solutions above doesn't work, try this: First run only the section of code for creating that modified table and then run the whole code.
This way you can set the initial day of the week.
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
Make sure to use it with moment().weekday(1);
instead of moment.isoWeekday(1)
Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent
However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent
Make sure to remove the line "<requestFocus />"
from the EditText
tag in xml.
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<requestFocus /> <!-- remove this line -->
</EditText>
I find very useful to understand how to organize code in Golang this chapter http://www.golang-book.com/11 of the book written by Caleb Doxsey
In my case it was my AVG anti-virus that triggered the exception.
I added my VS Projects directory to the "Allowed" list. And I had to add the executable to the AVG exceptions list after I copied the .exe
to my App directory.
The following works for me in Firefox and Chrome. In Firefox it even works from file:///
models/course.js
export function Course() {
this.id = '';
this.name = '';
};
models/student.js
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
index.html
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
Even I had also observed the similar problem. I had closed my eclipse project because of some reason and on restart some of my file added were not visible in explorer even though corresponding file were existing.
Following solution worked for me: Select whole workspace (Ctrl+A) ==> Righ click and press Refresh.
To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:
strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring(), strid])
Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.
In short, the following are the steps to generate flame graphs
yum -y install perf
wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz
tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64
echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict
JAVA_PID=`pgrep java`
./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg
flame-graph.svg
can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.
There are few other approaches to generating them
-XX:+PreserveFramePointer
as the JVM options as described here-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
as described hereBut using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.
Their wiki provides details on how to leverage it. And more about flame graphs can be found here
Suppose you want to show (50% OFF) and enter 50 at runtime. Here is the code:
<string name="format_discount"> (
<xliff:g id="discount">%1$s</xliff:g>
<xliff:g id="percentage_sign">%2$s</xliff:g>
OFF)</string>
In the java class use this code:
String formattedString=String.format(context.getString(R.string.format_discount),discountString,"%");
holder1.mTextViewDiscount.setText(formattedString);
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
Help
Install New Software
---> Add
Add Repository
write the Name: ADT
(or whatever you want)https://dl-ssl.google.com/android/eclipse/
Developer Tools
and NDK Plugins
Developer Tool
onlyNext
Finish
openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx
Create two dates: one in June, one in January. Compare their getTimezoneOffset()
values.
Now check getTimezoneOffset()
of the current date.
You can escape the space by using single quotations and a backtick before the space:
$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
cordova build android --release
I was able to resolve this, after trying so so many different things, by simply doing :
npm install cordova -g # to upgrade to version 10.0.0
cordova platform rm android
cordova platform add android # to upgrade to android version 9.0.0
Run it like this on the command line:
java -jar /path/to/your/jar/jarFile.jar
This is the shortest way:
myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");
I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.
Install express
npm install express
Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server
Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');
// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
app.listen(8000);
console.log('Listening on port 8000');
After you've saved server.js, you can run the server using:
node server.js
http://localhost:8000/FILENAME
and you should see the HTML file you were trying to loadThe HttpRequest
class represents the request made to the server and has various properties associated with it, such as QueryString
.
The ASP.NET run-time parses a request to the server and populates this information for you.
Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.
Note: not all properties will be populated, for instance if your request has no query string, then the QueryString
will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:
if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
// Query string value is there so now use it
int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
If you launch the VM with the the launchpad (genymotion binary where you download the VMs) and you set the Android SDK path into the application parameters the connection is automatic and you don't need to run adb connect
You can find the information in the Genymotion Docs.
Insert into table(col1,col2) select col1,col2 from table_2;
Please refer to MySQL documentation on INSERT Statement
You might be missing a DNS server conf in /etc/resolv.conf
make sure u can ping to: ping pypi.python.org
if you're not getting a ping try to add a DNS server to file...something like:
nameserver xxx.xxx.xxx.xxx
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
You can't have optional path variables, but you can have two controller methods which call the same service code:
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return getTestBean(type);
}
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
HttpServletRequest req,
@RequestParam("track") String track) {
return getTestBean();
}
import csv
with open(filename) as f:
csvreader = csv.reader(f)
for line in csvreader:
print(line[0])
The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.
However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.
The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.
String regex, updatedXml;
// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );
// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.
This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.
Remove file .git/logs/refs/remotes/origin/[Locked Branch Name]
It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.
But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync()
in those cases.
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
There's a convenient method for this in MySql called GROUP_CONCAT. An equivalent for SQL Server doesn't exist, but you can write your own using the SQLCLR. Luckily someone already did that for you.
Your query then turns into this (which btw is a much nicer syntax):
SELECT CUSTOMFIELD, ISSUE, dbo.GROUP_CONCAT(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602
GROUP BY CUSTOMFIELD, ISSUE
But please note that this method is good for at the most 100 rows within a group. Beyond that, you'll have major performance problems. SQLCLR aggregates have to serialize any intermediate results and that quickly piles up to quite a lot of work. Keep this in mind!
Interestingly the FOR XML
doesn't suffer from the same problem but instead uses that horrendous syntax.
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
curl {url for downloading zip file} | 7z a -tzip {project name}-{branch name}/{folder path in that branch}
for example:
curl https://github.com/hnvn/flutter_shimmer/archive/master.zip | 7z a -tzip flutter_shimmer-master/examples
While the answers with List<T>.ForEach
are very good.
I found String.Join<T>(string separator, IEnumerable<T> values)
method more useful.
Example :
List<string> numbersStrLst = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
Remarks :
If separator is null, an empty string (String.Empty
) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>)
is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.
This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])
Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx
PyAutoGui also lets you press a button multiple times:
pyautogui.press('tab', presses=5) # press TAB five times in a row
pyautogui.press('A', presses=1000) # press A a thousand times in a row
This code works for me:
import groovy.io.FileType
def list = []
def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:
list.each {
println it.path
}
Try this MSDN blog
Also, try the following example:
Xaml:
<DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
<DataGrid.Columns>
<DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Account" IsReadOnly="True" Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
CS:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var data = new Test { Test1 = "Test1", Test2 = "Test2" };
DataGridTest.Items.Add(data);
}
}
public class Test
{
public string Test1 { get; set; }
public string Test2 { get; set; }
}
Note for Chrome Browser released in 2020.
A future release of Chrome will only deliver cookies with cross-site requests if they are set with
SameSite=None
andSecure
.
So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.
More info https://www.chromium.org/updates/same-site.
Firefox and Edge developers also want to release this feature in the future.
Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8
It indicates that the servlet won't be started until a request tries to access it.
If load-on-startup is greater than or equal to zero then when the container starts it will start that servlet in ascending order of the load on startup value you put there (ie 0, 1 then 2 then 5 then 10 and so on).
On windows type either startup
or startup.bat
On unix type ./startup.sh
(assuming you are located in tomcat/bin directory)
The "error_page" parameter makes a redirect, converting the request method to "GET", it is not a custom response page.
The easiest solution is
server{
root /var/www/html;
location ~ \.php {
if (!-f $document_root/$fastcgi_script_name){
return 404;
}
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params.default;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
By the way, if you want Nginx to process 404 status returned by PHP scripts, you need to add
[fastcgi_intercept_errors][1] on;
E.g.
location ~ \.php {
#...
error_page 404 404.html;
fastcgi_intercept_errors on;
}
For Visual Studio users:
To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.
To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.
var rotated = false;
document.getElementById('button').onclick = function() {
var div = document.getElementById('div'),
deg = rotated ? 0 : 66;
div.style.webkitTransform = 'rotate('+deg+'deg)';
div.style.mozTransform = 'rotate('+deg+'deg)';
div.style.msTransform = 'rotate('+deg+'deg)';
div.style.oTransform = 'rotate('+deg+'deg)';
div.style.transform = 'rotate('+deg+'deg)';
rotated = !rotated;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
To add some animation to the rotation all we have to do is add CSS transitions
div {
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript
document.getElementById('button').onclick = function() {
document.getElementById('div').classList.toggle('rotated');
}
document.getElementById('button').onclick = function() {_x000D_
document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
-webkit-transform : rotate(66deg); _x000D_
-moz-transform : rotate(66deg); _x000D_
-ms-transform : rotate(66deg); _x000D_
-o-transform : rotate(66deg); _x000D_
transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
Check for null
$column is null
isnull($column)
Check for empty
$column != ""
However, you should always set NOT NULL for column,
mysql optimization can handle only one IS NULL level
What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages
appeared in your log
run this command
npm install express-generator -g
Now, create new Express.js starter application by type this command in your Node projects folder
.
express node-express-app
That command tell express to generate new Node.js application with the name node-express-app
.
then Go to the newly created project directory
, install npm packages
and start the app
using the command
cd node-express-app && npm install && npm start
simple difference between for and foreach
for loop is working with values.it must have condition then increment and intialization also.you have to knowledge about 'how many times loop repeated'.
foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.
You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).
If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:
function test() {
// function code
}
test();
Or, use a PHP include:
include 'functions.php'; // functions.php has the test function
test();
Unless you are already using CollectionUtils I would go for List.isEmpty()
, less dependencies.
Performance wise CollectionUtils will be a tad slower. Because it basically follows the same logic but has additional overhead.
So it would be readability vs. performance vs. dependencies. Not much of a big difference though.
I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST)
puts label number X in LIST
with the line corresponding to the Xth time plot
was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
If you would like to use System.Data instead of System.LINQ, then you can do something like this.
List<string> BrandsInDataTable = new List<string>();
DataTable g = Access._ME_G_BrandsInPop();
if (g.Rows.Count > 0)
{
for (int x = 0; x < g.Rows.Count; x++)
BrandsInDataTable.Add(g.Rows[x]["Name"].ToString());
}
else return;
We can now in C# 7.0 and above write this:
if (int.TryParse(inputString, out _))
{
//do stuff
}
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"
Then make sure to access the Observable
class as Rx.Observable
.
With multiple joins, use something like this code:
$someId = 44;
Event::with(["owner", "participants" => function($q) use($someId){
$q->where('participants.IdUser', '=', 1);
//$q->where('some other field', $someId);
}])
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
var place = document.getElementById('textfield');_x000D_
var commentBox = document.createElement('textarea');_x000D_
place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
comment[i].onclick = function() {_x000D_
showComment();_x000D_
};_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
You can overwrite the existing jenkins.war
file with the new one and then restart Jenkins.
This file is usually located in /usr/share/jenkins
.
If this is not the case for your system, in Manage Jenkins -> System Information
, it will display the path to the .war
file under executable-war
.
As shaishab roy says, in the cheat sheet you can find the answer.
But in his answer, the given response was :
{path: '/home/...', name: 'Home', component: HomeComponent} {path: '/', redirectTo: ['Home']}, {path: '/user/...', name: 'User', component: UserComponent}, {path: '/404', name: 'NotFound', component: NotFoundComponent}, {path: '/*path', redirectTo: ['NotFound']}
For some reasons, it doesn't works on my side, so I tried instead :
{path: '/**', redirectTo: ['NotFound']}
and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).
Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height
rule, some won't.
You can try line-height
(may need display:block;
or display:inline-block;
) or top
and bottom padding
also. If none of those work, that's pretty much it - use a graphic, position the input
in the center and set border:none;
so it looks like the form control is big but it actually isn't...
<html>
<head>
</head>
<body>
<script>
function demo(){
var d=document.getElementById('s1');
var e=document.getElementById('show_f').value;
var f=document.getElementById('show_f').type;
if(d.value=="show"){
var f= document.getElementById('show_f').type="text";
var g=document.getElementById('show_f').value=e;
d.value="Hide";
} else{
var f= document.getElementById('show_f').type="password";
var g=document.getElementById('show_f').value=e;
d.value="show";
}
}
</script>
<form method='post'>
Password: <input type='password' name='pass_f' maxlength='30' id='show_f'><input type="button" onclick="demo()" id="s1" value="show" style="height:25px; margin-left:5px;margin-top:3px;"><br><br>
<input type='submit' name='sub' value='Submit Now'>
</form>
</body>
</html>
As mentioned in Yoshua Wuyts' answer, using git branch
:
git branch --unset-upstream
You don't have to delete your local branch.
Simply delete the local branch that is tracking the remote branch:
git branch -d -r origin/<remote branch name>
-r, --remotes
tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!
See "Having a hard time understanding git-fetch"
there's no such concept of local tracking branches, only remote tracking branches.
Soorigin/master
is a remote tracking branch formaster
in theorigin
repo
As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:
git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge
Remove the upstream information for
<branchname>
.
If no branch is specified it defaults to the current branch.
(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn
))
That will make any push/pull completely unaware of origin/<remote branch name>
.
Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.
Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.
Let's take the Purchase Order schema for example. Here's a fragment:
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
You can compile this schema using the provided command-line tool:
java -jar jsonix-schema-compiler-full.jar
-generateJsonSchema
-p PO
schemas/purchaseorder.xsd
The compiler generates Jsonix mappings as well the matching JSON Schema.
Here's what the result looks like (edited for brevity):
{
"id":"PurchaseOrder.jsonschema#",
"definitions":{
"PurchaseOrderType":{
"type":"object",
"title":"PurchaseOrderType",
"properties":{
"shipTo":{
"title":"shipTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
},
"billTo":{
"title":"billTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
}, ...
}
},
"USAddress":{ ... }, ...
},
"anyOf":[
{
"type":"object",
"properties":{
"name":{
"$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
},
"value":{
"$ref":"#/definitions/PurchaseOrderType"
}
},
"elementName":{
"localPart":"purchaseOrder",
"namespaceURI":""
}
}
]
}
Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.
The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).
Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.
Links:
npm install
No record matched means no record returned. There's no place for the "value" of 0 to go if no records are found. You could create a crazy UNION query to do what you want but much, much, much better simply to check the number of records in the result set.
A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.
Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.
But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401
"unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.
TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)
An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401
if not provided.
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
If the files already have the +x flag set, git update-index --chmod=+x
does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.
You must first remove the flag, run the git command, then put the flag back:
chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>
then git sees a change and will allow you to commit the change.
To stop just some cells being selected use:
cell.userInteractionEnabled = NO;
As well as preventing selection, this also stops tableView:didSelectRowAtIndexPath: being called for the cells that have it set.
You can have individual classes in your css files and then assign the classname to your element
or you can loop through properties of styles as -
var css = { "font-size": "12px", "left": "200px", "top": "100px" };
for(var prop in css) {
document.getElementById("myId").style[prop] = css[prop];
}
I ran into this problem when I moved to a new machine, carrying with me my AWS_DEFAULT_PROFILE environment variable, but not my ~/.aws directory. I couldn't get any awscli commands to work until I unset that variable or properly configured the named profile. But even the aws configure
command was broken, making things a bit tricky. Assuming you have a Unix-like shell handy:
env | grep AWS_
unset AWS_DEFAULT_PROFILE
aws --profile foo configure
exec $SHELL
aws iam get-user
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
other way is:
sudo service apache2 reload
In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:
import matplotlib.pyplot as plt
fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")
ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")
ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")
ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")
fig.tight_layout()
# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)
fig.savefig("test.png")
gives:
Double check projects .net versions. Projects that referenced each other with different .net versions causes problems.
SELECT *
FROM pg_settings
WHERE name = 'port';
-while(int i=0; i < data.length; i++)
+for(int i=0; i < data.length; i++)
even shorter:
echo $select->__toString()."\n";
and more shorter:
echo $select .""; die;
I would say that it depends on what you want to do.
If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.
Here is a sample:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Input()
value: string[];
@Output()
valueChange: EventEmitter;
constructor(private elementRef:ElementRef) {
this.valueChange = new EventEmitter();
}
select(value) {
this.valueChange.emit(value);
}
}
This allows you to use it this way:
<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>
You can build your dropdown within the component, apply styles and manage selections internally.
Edit
You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Output()
select: EventEmitter;
constructor() {
this.select = new EventEmitter();
}
selectItem(value) {
this.select.emit(value);
}
}
Then you can use the component like this:
<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>
Notice that the action
method is the one of the parent component (not the dropdown one).
For creating a branch from another one can use this syntax as well:
git push origin refs/heads/<sourceBranch>:refs/heads/<targetBranch>
It is a little shorter than "git checkout -b " + "git push origin "
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
It means that one of the dependent dlls is compiled with a different run-time library.
Project -> Properties -> C/C++ -> Code Generation -> Runtime Library
Go over all the libraries and see that they are compiled in the same way.
More about this error in this link:
warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
I did it in this simple way, with Web API 2.0. You can remove UseDefaultCredentials. I used it for my own use cases.
List<YourObject> listObjects = new List<YourObject>();
string response = "";
using (var client = new WebClient() { UseDefaultCredentials = true })
{
response = client.DownloadString(apiUrl);
}
listObjects = JsonConvert.DeserializeObject<List<YourObject>>(response);
return listObjects;
I think you can do this:
var client = new HttpClient();
HttpContent content = new Widget();
client.PostAsync<Widget>("http://localhost:44268/api/test", content, new FormUrlEncodedMediaTypeFormatter())
.ContinueWith((postTask) => { postTask.Result.EnsureSuccessStatusCode(); });
This worked for me:
composer require "ext-gd:*" --ignore-platform-reqs
I found a simple jQuery library called Sticky Table Headers. Two lines of code and it did exactly what I wanted. The solutions above don't manage the column widths, so if you have table cells that take up a lot of space, the resulting size of the persistent header will not match your table's width.
http://plugins.jquery.com/StickyTableHeaders/
Usage info here: https://github.com/jmosbech/StickyTableHeaders
Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:
I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:
<title>jQuery+RequireJS Sample Page</title>
<script src="scripts/require.js"></script>
<script>
require({
baseUrl: 'scripts',
paths: {
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
},
priority: ['jquery']
}, ['main']);
</script>
Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:
Use GREATEST()
E.g.:
SELECT GREATEST(2,1);
Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)
It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:
The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.
srand()
seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time()
function from the <ctime>
library as such: srand(time(0))
. This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand()
to generate a pseudo-random number.
Here is a quote from a duplicate question:
The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand() it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand with a truly random number), then you will always get the same 'random' numbers out.
If you want to know more, you can read the following:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.
There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.
Hope it helps. Marc Jacobi
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
To resolve the issues make sure you are using build tools version "23.0.0 rc2" with the following tools build gradle dependency:
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
I found this page while trying to center align a pair of videos. So, if I enclose both videos in a center div
(which I've called central), the margin trick works, but the width is important (2 videos at 400 + padding etc)
<div class=central>
<video id="vid1" width="400" controls>
<source src="Carnival01.mp4" type="video/mp4">
</video>
<video id="vid2" width="400" controls>
<source src="Carnival02.mp4" type="video/mp4">
</video>
</div>
<style>
div.central {
margin: 0 auto;
width: 880px; <!--this value must be larger than both videos + padding etc-->
}
</style>
Worked for me!
If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...
myAccount.equals(yourAccount)
is true
because they have the same value, butmyAccount == yourAccount
is false
because they are not the same account.(Assuming appropriate definitions of the Account
class, of course. ;-)
If you still get
TCPDF ERROR: Unable to create output file: myfile.pdf
you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:
$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);
Maybe you're looking for something like this:
$(document).click(function(e)
{
if($(e.srcElement).attr('id')=='id')
{
alert('click on #id');
}
else
{
alert('click on something else');
}
});
You may retrieve a pointer to the clicked element using event.srcElement
.
So all you have to do is to check the id-attribute of the clicked element.
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
Another way is to open Visual Studio Code from a terminal with the virtualenv set and need to perform F1 Python: Select Interpreter
and select the required virtualenv.
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else
logic inside the if
:
if (!(id in tutorTimes)) { ... }
No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
Laravel 5 timestamps are instances of Carbon class, so you can directly call Carbon's string formatting method on your timestamps. Something like this in your view file.
{{$task->created_at->toFormattedDateString()}}
When you typed in sudo sendmailconfig
, you should have been prompted to configure sendmail.
For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):
/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc
You can test sendmail to see if it is properly configured and setup by typing the following into the command line:
$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]
The following will allow you to add smtp relay to sendmail:
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS
. Make sure you update your smtp server.
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl
Invoke creation sendmail.cf (alternatively run make -C /etc/mail
):
m4 sendmail.mc > sendmail.cf
Restart the sendmail daemon:
service sendmail restart
str.replace(/[[\]]/g,'')
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
you can use simply inside your controller:
return response()->download($filePath);
Happy coding :)
Just download and install LocalDB 64BIT\SqlLocalDB.msi can also solve this problem. You don't really need to uninstall and reinstall SQL Server 2014 Express with Advanced Services.
There's no direct way to do it yet, unfortunately, but there are a couple indirect ways:
[dt.year for dt in dates.astype(object)]
or
[datetime.datetime.strptime(repr(d), "%Y-%m-%d %H:%M:%S").year for d in dates]
both inspired by the examples here.
Both of these work for me on Numpy 1.6.1. You may need to be a bit more careful with the second one, since the repr() for the datetime64 might have a fraction part after a decimal point.
Try the following. It is simple, but I haven't figured out a graceful way to exit yet.
import cv2.cv as cv
import time
cv.NamedWindow("camera", 0)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
Those are the bitwise AND and bitwise OR operators.
int a = 6; // 110
int b = 4; // 100
// Bitwise AND
int c = a & b;
// 110
// & 100
// -----
// 100
// Bitwise OR
int d = a | b;
// 110
// | 100
// -----
// 110
System.out.println(c); // 4
System.out.println(d); // 6
Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.
Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&
) and Conditional-Or (||
) operators except for the fact that they don't short-circuit so while the following is safe:
if((a != null) && (a.something == 3)){
}
This is not:
if((a != null) & (a.something == 3)){
}
"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, &&
will examine the second condition only when a
is not null
(otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something
will not raise an exception, or is considered "safe."
The &
operator always examines every condition in the clause, so in the examples above, a.something
may be evaluated when a
is in fact a null
value, raising an exception.
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
The other answers have pointed out the solution for the majority of cases involving PropertySources
, but none have mentioned that certain property sources are unable to be casted into useful types.
One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource
. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.
If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.
In View Replace this:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
Sometimes, you really don't care about the collection itself. For instance, creating a simple model fit line to compare an "approximation" with the raw data:
fib_raw = [1, 1, 2, 3, 5, 8, 13, 21] # Fibonacci numbers
phi = (1 + sqrt(5)) / 2
phi2 = (1 - sqrt(5)) / 2
def fib_approx(n): return (phi**n - phi2**n) / sqrt(5)
x = range(len(data))
y = [fib_approx(n) for n in x]
# Now plot to compare fib_raw and y
# Compare error, etc
In this case, the values of the Fibonacci sequence itself were irrelevant. All we needed here was the size of the input sequence we were comparing with.
Is there some handy way of defining direction per column?
No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.
You might be able to do
_.each(array_of_objects, function(o) {
o.typeDesc = -o.type; // assuming a number
});
_.sortBy(array_of_objects, ['typeDesc', 'name'])
For everything else, you will need to resort to the native .sort()
with a custom comparison function:
array_of_objects.sort(function(a, b) {
return a.type - b.type // asc
|| +(b.name>a.name)||-(a.name>b.name) // desc
|| …;
});
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
The 1./2
syntax works because 1.
is a float. It's the same as 1.0
. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float()
on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division
at the top of the module.
Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:
<div class="Owner Joe" />
div:before {
content: attr(class);
}
Or even with the new HTML5 custom data attributes:
<div data-employeename="Owner Joe" />
div:before {
content: attr(data-employeename);
}
Try these:
Table definition:
DROP TABLE IF EXISTS category;
CREATE TABLE category (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
parent_id INT,
CONSTRAINT fk_category_parent FOREIGN KEY (parent_id)
REFERENCES category (id)
) engine=innodb;
Experimental rows:
INSERT INTO category VALUES
(19, 'category1', NULL),
(20, 'category2', 19),
(21, 'category3', 20),
(22, 'category4', 21),
(23, 'categoryA', 19),
(24, 'categoryB', 23),
(25, 'categoryC', 23),
(26, 'categoryD', 24);
Recursive Stored procedure:
DROP PROCEDURE IF EXISTS getpath;
DELIMITER $$
CREATE PROCEDURE getpath(IN cat_id INT, OUT path TEXT)
BEGIN
DECLARE catname VARCHAR(20);
DECLARE temppath TEXT;
DECLARE tempparent INT;
SET max_sp_recursion_depth = 255;
SELECT name, parent_id FROM category WHERE id=cat_id INTO catname, tempparent;
IF tempparent IS NULL
THEN
SET path = catname;
ELSE
CALL getpath(tempparent, temppath);
SET path = CONCAT(temppath, '/', catname);
END IF;
END$$
DELIMITER ;
Wrapper function for the stored procedure:
DROP FUNCTION IF EXISTS getpath;
DELIMITER $$
CREATE FUNCTION getpath(cat_id INT) RETURNS TEXT DETERMINISTIC
BEGIN
DECLARE res TEXT;
CALL getpath(cat_id, res);
RETURN res;
END$$
DELIMITER ;
Select example:
SELECT id, name, getpath(id) AS path FROM category;
Output:
+----+-----------+-----------------------------------------+
| id | name | path |
+----+-----------+-----------------------------------------+
| 19 | category1 | category1 |
| 20 | category2 | category1/category2 |
| 21 | category3 | category1/category2/category3 |
| 22 | category4 | category1/category2/category3/category4 |
| 23 | categoryA | category1/categoryA |
| 24 | categoryB | category1/categoryA/categoryB |
| 25 | categoryC | category1/categoryA/categoryC |
| 26 | categoryD | category1/categoryA/categoryB/categoryD |
+----+-----------+-----------------------------------------+
Filtering rows with certain path:
SELECT id, name, getpath(id) AS path FROM category HAVING path LIKE 'category1/category2%';
Output:
+----+-----------+-----------------------------------------+
| id | name | path |
+----+-----------+-----------------------------------------+
| 20 | category2 | category1/category2 |
| 21 | category3 | category1/category2/category3 |
| 22 | category4 | category1/category2/category3/category4 |
+----+-----------+-----------------------------------------+
There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:
$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});
Another would be to load the content of your external link into the dialog container using ajax.
$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});
Both works fine but depends on the external content.
from foo import *
adds all the names without leading underscores (or only the names defined in the modules __all__
attribute) in foo
into your current module.
In the above code with from socket import *
you just want to catch timeout
as you've pulled timeout
into your current namespace.
from socket import *
pulls in the definitions of everything inside of socket
but doesn't add socket
itself.
try:
# socketstuff
except timeout:
print 'caught a timeout'
Many people consider import *
problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.
For example, consider the following three python files:
# a.py
def foo():
print "this is a's foo function"
# b.py
def foo():
print "this is b's foo function"
# yourcode.py
from a import *
from b import *
foo()
If you run yourcode.py
you'll see just the output "this is b's foo function".
For this reason I'd suggest either importing the module and using it or importing specific names from the module:
For example, your code would look like this with explicit imports:
import socket
from socket import AF_INET, SOCK_DGRAM
def main():
client_socket = socket.socket(AF_INET, SOCK_DGRAM)
client_socket.settimeout(1)
server_host = 'localhost'
server_port = 1234
while(True):
client_socket.sendto('Message', (server_host, server_port))
try:
reply, server_address_info = client_socket.recvfrom(1024)
print reply
except socket.timeout:
#more code
Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.
Eric Petroelje almost has it right:
SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )
Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)
If you want to check if provided domain from email address is valid, use something like:
/*
* Check for valid MX record for given email domain
*/
if(!function_exists('check_email_domain')){
function check_email_domain($email) {
//Get host name from email and check if it is valid
$email_host = explode("@", $email);
//Add a dot to the end of the host name to make a fully qualified domain name and get last array element because an escaped @ is allowed in the local part (RFC 5322)
$host = end($email_host) . ".";
//Convert to ascii (http://us.php.net/manual/en/function.idn-to-ascii.php)
return checkdnsrr(idn_to_ascii($host), "MX"); //(bool)
}
}
This is handy way to filter a lot of invalid email addresses, along with standart email validation, because valid email format does not mean valid email.
Note that idn_to_ascii()
(or his sister function idn_to_utf8()
) function may not be available in your PHP installation, it requires extensions PECL intl >= 1.0.2 and PECL idn >= 0.1.
Also keep in mind that IPv4 or IPv6 as domain part in email (for example user@[IPv6:2001:db8::1]
) cannot be validated, only named hosts can.
See more here.
You can use the Tanuki wrapper to spawn a process with POSIX spawn instead of fork. http://wrapper.tanukisoftware.com/doc/english/child-exec.html
The WrapperManager.exec() function is an alternative to the Java-Runtime.exec() which has the disadvantage to use the fork() method, which can become on some platforms very memory expensive to create a new process.
json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.
Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.
Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.
First of all you don't use width=300px
that's an attribute setting for the tag not CSS, use width: 300px;
instead.
I would suggest applying the clearfix
technique on the #outerdiv
. Clearfix is a general solution to clear 2 floating divs so the parent div will expand to accommodate the 2 floating divs.
<div id='outerdiv' class='clearfix' style='width:600px; background-color: black;'>
<div style='width:300px; float: left;'>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div style='width:300px; float: left;'>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
</div>
Here is an example of your situation and what Clearfix does to resolve it.
this seems to work fine :
dataframe.axes[0].tolist()
To rotate by 45 degrees in IE, you need the following code in your stylesheet:
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */
You’ll note from the above that IE8 has different syntax to IE6/7. You need to supply both lines of code if you want to support all versions of IE.
The horrible numbers there are in Radians; you’ll need to work out the figures for yourself if you want to use an angle other than 45 degrees (there are tutorials on the internet if you look for them).
Also note that the IE6/7 syntax causes problems for other browsers due to the unescaped colon symbol in the filter string, meaning that it is invalid CSS. In my tests, this causes Firefox to ignore all CSS code after the filter. This is something you need to be aware of as it can cause hours of confusion if you get caught out by it. I solved this by having the IE-specific stuff in a separate stylesheet which other browsers didn’t load.
All other current browsers (including IE9 and IE10 — yay!) support the CSS3 transform
style (albeit often with vendor prefixes), so you can use the following code to achieve the same effect in all other browsers:
-moz-transform: rotate(45deg); /* FF3.5/3.6 */
-o-transform: rotate(45deg); /* Opera 10.5 */
-webkit-transform: rotate(45deg); /* Saf3.1+ */
transform: rotate(45deg); /* Newer browsers (incl IE9) */
Hope that helps.
Since this answer is still getting up-votes, I feel I should update it with information about a JavaScript library called CSS Sandpaper that allows you to use (near) standard CSS code for rotations even in older IE versions.
Once you’ve added CSS Sandpaper to your site, you should then be able to write the following CSS code for IE6–8:
-sand-transform: rotate(40deg);
Much easier than the traditional filter
style you'd normally need to use in IE.
Also note an additional quirk specifically with IE9 (and only IE9), which supports both the standard transform
and the old style IE -ms-filter
. If you have both of them specified, this can result in IE9 getting completely confused and rendering just a solid black box where the element would have been. The best solution to this is to avoid the filter
style by using the Sandpaper polyfill mentioned above.
Your stored procedures work as coded. The problem is with the last line, it is unable to invoke either of your stored procedures.
Three choices in SQL*Plus are: call
, exec
, and an anoymous PL/SQL block.
call
appears to be a SQL keyword, and is documented in the SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_4008.htm#BABDEHHG The syntax diagram indicates that parentesis are required, even when no arguments are passed to the call routine.
CALL test_sp_1();
An anonymous PL/SQL block is PL/SQL that is not inside a named procedure, function, trigger, etc. It can be used to call your procedure.
BEGIN
test_sp_1;
END;
/
Exec
is a SQL*Plus command that is a shortcut for the above anonymous block. EXEC <procedure_name>
will be passed to the DB server as BEGIN <procedure_name>; END;
Full example:
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE test_sp
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Test works');
5 END;
6 /
Procedure created.
SQL> CREATE OR REPLACE PROCEDURE test_sp_1
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Testing');
5 test_sp;
6 END;
7 /
Procedure created.
SQL> CALL test_sp_1();
Testing
Test works
Call completed.
SQL> exec test_sp_1
Testing
Test works
PL/SQL procedure successfully completed.
SQL> begin
2 test_sp_1;
3 end;
4 /
Testing
Test works
PL/SQL procedure successfully completed.
SQL>
Write a:hover::before
instead of a::before:hover
: example.
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.
Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:
SELECT db.[name] as dbname
FROM [master].[sys].[databases] db
LEFT OUTER JOIN [master].[sys].[sysusers] su on su.sid = db.owner_sid
WHERE su.sid is null
order by db.[name]
Use htmlspecialchars
on PHP
. On HTML try to avoid using:
element.innerHTML = “…”;
element.outerHTML = “…”;
document.write(…);
document.writeln(…);
where var
is controlled by the user.
Also obviously try avoiding eval(var)
,
if you have to use any of them then try JS escaping them, HTML escape them and you might have to do some more but for the basics this should be enough.
After Accept Answer
A method that meets these specs: (IMO, the other answers do not meet all)
It is practical/efficient when char
has a wide range. Example: CHAR_BIT
is 16
or 32
, so no use of bool Used[1 << CHAR_BIT];
Works for very long strings (use size_t
rather than int
).
Does not rely on ASCII. ( Use Upper[]
)
Defined behavior when a char
< 0. is...()
functions are defined for EOF
and unsigned char
static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
void LetterOccurrences(size_t *Count, const char *s) {
memset(Count, 0, sizeof *Count * 26);
while (*s) {
unsigned char ch = *s;
if (isalpha(ch)) {
const char *caseset = Upper;
char *p = strchr(caseset, ch);
if (p == NULL) {
caseset = Lower;
p = strchr(caseset, ch);
}
if (p != NULL) {
Count[p - caseset]++;
}
}
}
}
// sample usage
char *s = foo();
size_t Count[26];
LetterOccurrences(Count, s);
for (int i=0; i<26; i++)
printf("%c : %zu\n", Upper[i], Count[i]);
}
Using more_itertools.with_iter
, it is possible to open, read, close and assign an equivalent output
in one line (excluding the import statement):
import more_itertools as mit
output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r")))
Although possible, I would look for another approach other than assigning the contents of a file to a variable, i.e. lazy iteration - this can be done using a traditional with
block or in the example above by removing join()
and iterating output
.
The error occurred when I unknowingly tried plotting the image path instead of the image.
My code :
import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage
img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"
#cv.rectangle(img,(29,2496),(604,2992),(255,0,0),5)
plt.imshow(img)
Correction:
img = cv.imread("fitting.png")
--->THIS IS THE RIGHT USAGE"
I think this the better way with knowing the logic itself
var arrayOfInts = [2, 2, 4, 4]
var mainArray = [Int]()
for value in arrayOfInts {
if mainArray.contains(value) != true {
mainArray.append(value)
print("mainArray:\(mainArray)")
}}
there is also a sneak way with pandas:
pd.to_timedelta(x) - pd.to_timedelta(y)
#pragma once
is flakey, even on MS compilers, and is not supported by many other compilers. As many other people have mentioned, using include guards is the way to go. Don't use #pragma once
at all - it'll make your life much easier.
These are what's known as Shadow Copy Folders.
Simplistically....and I really mean it:
When ASP.NET runs your app for the first time, it copies any assemblies found in the /bin folder, copies any source code files (found for example in the App_Code folder) and parses your aspx, ascx files to c# source files. ASP.NET then builds/compiles all this code into a runnable application.
One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.
ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.
Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.
This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
In react router 4 the current route is in -
this.props.location.pathname
.
Just get this.props
and verify.
If you still do not see location.pathname
then you should use the decorator withRouter
.
This might look something like this:
import {withRouter} from 'react-router-dom';
const SomeComponent = withRouter(props => <MyComponent {...props}/>);
class MyComponent extends React.Component {
SomeMethod () {
const {pathname} = this.props.location;
}
}
"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.
This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.
i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.
with underscore i had to use String() in the iteratee function
function isUniq(item) {
return String(item.user);
}
var myUniqArray = _.uniq(myArray, isUniq);
Do not use >
; it messes up the character encoding. Use:
Get-Content files.* | Set-Content newfile.file
One thing that seems to work for me is this:
@ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")
Or in XML:
<context:component-scan base-package="com.example" resource-pattern="*.class"/>
This overrides the default resourcePattern
which is "**/*.class"
.
This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.
Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.
Right click on Project -> Add FrameWork Support -> Maven