In SQL*Plus putting SET DEFINE ?
at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.
for a quick search in VIM, you could use at Vim Control prompt: /This is.*\_.*sentence
Make sure all the folders are visible. click start>control panel>Appearance and Personalization>Show hidden files and folders then click "Show hidden files, folders and drives" The file should be in C:\Users\Username\AppData\Local\Android as mentioned above. otherwise you can check by opening Android SDK Manager - top left under SDK path.
A combination of the above responses. I would use the Microsoft preferred approach of using MailAddress but implement as an extension of string:
public static bool IsValidEmailAddress(this string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Then just validate any string as an email address with:
string customerEmailAddress = "[email protected]";
customerEmailAddress.IsValidEmailAddress()
Clean simple and portable. Hope it helps someone. Regex for emails are messy.
That said MattSwanson has a blog on this very topic and he strongly suggests NOT using regexs and instead just check for '@' abd maybe a dot. Read his explanation here: https://mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.
class ImputeLags(BaseEstimator, TransformerMixin):
def __init__(self, columns):
self.columns = columns
def fit(self, x, y=None):
""" do something """
def transfrom(self, x):
return x
AttributeError: 'NoneType' object has no attribute 'transform'?
Adding return self
to the fit function fixes the error.
I had some lint errors in Android Studio that occurred only when I generated a signed APK.
To avoid it, I added the following to build.gradle
android {
lintOptions {
checkReleaseBuilds false
}
}
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
You can either define the right default value into the model you want to edit with this form or you can specify an empty_data option so your code become:
$form = $this
->createFormBuilder($breed)
->add(
'species',
'entity',
array(
'class' => 'BFPEduBundle:Item',
'property' => 'name',
'empty_data' => 123,
'query_builder' => function(ItemRepository $er) {
return $er
->createQueryBuilder('i')
->where("i.type = 'species'")
->orderBy('i.name', 'ASC')
;
}
)
)
->add('breed', 'text', array('required'=>true))
->add('size', 'textarea', array('required' => false))
->getForm()
;
I was having a similar issue with formatting CardViews in a recylerView.
I got this simple solution working, not sure if it's the best solution, but it worked for me.
mv_cardView.getBackground().setTint(Color.BLUE)
It gets the background Drawable of the cardView and tints it.
Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.
list.objects <- function(env = .GlobalEnv)
{
if(!is.environment(env)){
env <- deparse(substitute(env))
stop(sprintf('"%s" must be an environment', env))
}
obj.type <- function(x) class(get(x, envir = env))
foo <- sapply(ls(envir = env), obj.type)
object.name <- names(foo)
names(foo) <- seq(length(foo))
dd <- data.frame(CLASS = foo, OBJECT = object.name,
stringsAsFactors = FALSE)
dd[order(dd$CLASS),]
}
> x <- 1:5
> d <- data.frame(x)
> list.objects()
# CLASS OBJECT
# 1 data.frame d
# 2 function list.objects
# 3 integer x
> list.objects(env = x)
# Error in list.objects(env = x) : "x" must be an environment
I know this thread is very old but for those not using SQL Server 2012 or above or cannot use the FORMAT function for any reason then the following works.
Also, a lot of the solutions did not work if the number was less than 1 (e.g. 0.01230000).
Please note that the following does not work with negative numbers.
DECLARE @num decimal(28,14) = 10.012345000
SELECT PARSENAME(@num,2) + REPLACE(RTRIM(LTRIM(REPLACE(@num-PARSENAME(@num,2),'0',' '))),' ','0')
set @num = 0.0123450000
SELECT PARSENAME(@num,2) + REPLACE(RTRIM(LTRIM(REPLACE(@num-PARSENAME(@num,2),'0',' '))),' ','0')
Returns 10.012345 and 0.012345 respectively.
Replacing all zeroes to NA:
df[df == 0] <- NA
Explanation
1. It is not NULL
what you should want to replace zeroes with. As it says in ?'NULL'
,
NULL represents the null object in R
which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that
data.frame(x = c(1, NULL, 2))
# x
# 1 1
# 2 2
That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA'
we see that
NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.
Importantly, NA
is of length 1 so that R reserves some space for it. E.g.,
data.frame(x = c(1, NA, 2))
# x
# 1 1
# 2 NA
# 3 2
Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL
values).
Now you could replace zeroes by NULL
in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var
, cov
, or cor
, that is actually equivalent to first replacing zeroes with NA
and setting the value of use
as "complete.obs"
. Typically, however, this is unsatisfactory as it leads to extra information loss.
2. Instead of running some sort of loop, in the solution I use df == 0
vectorization. df == 0
returns (try it) a matrix of the same size as df
, with the entries TRUE
and FALSE
. Further, we are also allowed to pass this matrix to the subsetting [...]
(see ?'['
). Lastly, while the result of df[df == 0]
is perfectly intuitive, it may seem strange that df[df == 0] <- NA
gives the desired effect. The assignment operator <-
is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'
.
1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.
You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
then use the server.crt
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./server.crt', 'utf8')
};
In addition to using an map-like object, there has been an actual Map
object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:
let people = new Map<string, Person>();
It supports the same functionality as Object
, and more, with a slightly different syntax:
// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });
// Checking for the presence of a key:
people.has("John"); // true
// Retrieving a value by a key:
people.get("John").lastName; // "Doe"
// Deleting an item by a key:
people.delete("John");
This alone has several advantages over using a map-like object, such as:
Object
(no, Object
does not support numbers, it converts them to strings)--noImplicitAny
, as a Map
always has a key type and a value type, whereas an object might not have an index-signatureObject
Additionally, a Map
object provides a more powerful and elegant API for common tasks, most of which are not available through simple Object
s without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):
// Iterate over Map entries:
people.forEach((person, key) => ...);
// Clear the Map:
people.clear();
// Get Map size:
people.size;
// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());
// Extract values into array (in insertion order):
let values = Array.from(people.values());
I read all the comments and thought that GitHub made it too difficult for normal user to create GitHub pages until I visited GitHub theme Page where its clearly mentioned that there is a section of "GitHub Pages" under settings Page of the concerned repo where you can choose the option "use the master branch for GitHub Pages." and voilà!!...checkout that particular repo on https://username.github.io/reponame
Date#parse
is deprecated . The alternative is :
java.text.DateFormat#parse
thereFore :
new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
is what you are looking for something like intellisense?
insevim seems to address the issue.
link to screenshots here
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
virtualenv
is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I'll be making comparisons to it for the rest of this answer.
It works by installing a bunch of files in a directory (eg: env/
), and then modifying the PATH
environment variable to prefix it with a custom bin
directory (eg: env/bin/
). An exact copy of the python
or python3
binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip
.
pyenv
is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the PATH
environment variable with ~/.pyenv/shims
, where there are special files matching the Python commands (python
, pip
). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION
environment variable, or the .python-version
file, or the ~/.pyenv/version
file. pyenv
also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install
.
pyenv-virtualenv
is a plugin for pyenv
by the same author as pyenv
, to allow you to use pyenv
and virtualenv
at the same time conveniently. However, if you're using Python 3.3 or later, pyenv-virtualenv
will try to run python -m venv
if it is available, instead of virtualenv
. You can use virtualenv
and pyenv
together without pyenv-virtualenv
, if you don't want the convenience features.
virtualenvwrapper
is a set of extensions to virtualenv
(see docs). It gives you commands like mkvirtualenv
, lssitepackages
, and especially workon
for switching between different virtualenv
directories. This tool is especially useful if you want multiple virtualenv
directories.
pyenv-virtualenvwrapper
is a plugin for pyenv
by the same author as pyenv
, to conveniently integrate virtualenvwrapper
into pyenv
.
pipenv
aims to combine Pipfile
, pip
and virtualenv
into one command on the command-line. The virtualenv
directory typically gets placed in ~/.local/share/virtualenvs/XXX
, with XXX
being a hash of the path of the project directory. This is different from virtualenv
, where the directory is typically in the current working directory. pipenv
is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv
, such as poetry
, which I won't list here since this question is only about the packages that are similarly named.
pyvenv
is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv
.
venv
is a package shipped with Python 3, which you can run using python3 -m venv
(although for some reason some distros separate it out into a separate distro package, such as python3-venv
on Ubuntu/Debian). It serves the same purpose as virtualenv
, but only has a subset of its features (see a comparison here). virtualenv
continues to be more popular than venv
, especially since the former supports both Python 2 and 3.
This is my personal recommendation for beginners: start by learning virtualenv
and pip
, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.
Go to the bar where you have file, edit, view etc Go on view -> Navigators -> Show Project Navigator -> Click on team -> Select yours.
Enjoy
Hi first of all i would like you to use 'Synaptic Package Manager'. You just need to goto the ubuntu software center and search for synaptic package manager.. The beauty of this is that all the packages you need are easily available here. Second it will automatically configures all your paths. Now install this then search for opencv packages over there if you found the package with the green box then its installed but else the package is not in the right place so you need to reinstall it but from package manager this time. If installed then you can do this only, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)
export OpenCV_DIR=<path_of_opencv>
Here's an example where I was extracting particular data from a list where I had multiple data types (that's what I'd call it in R-- sorry if it's the wrong nomenclature) and I wanted to extract only integers/numeric and NOT character data.
The data looked like:
>>> a = ['1', 'env', '2', 'gag', '1.234', 'nef']
>>> data = []
>>> type(a)
<class 'list'>
>>> type(a[1])
<class 'str'>
>>> type(a[0])
<class 'str'>
I wanted to remove all alphabetical characters, so I had the machine do it by subsetting the data, and "passing" over the alphabetical data:
a = ['1', 'env', '2', 'gag', '1.234', 'nef']
data = []
for i in range(0, len(a)):
if a[i].isalpha():
pass
else:
data.append(a[i])
print(data)
['1', '2', '1.234']
For my case, I had to right click the solution and click "Retarget Projects".
In my case I retargetted to Windows SDK version 10.0.1777.0 and Platform Toolset v142. I also had to change "Windows.h"
to<windows.h>
I am running Visual Studio 2019 version 16.25 on a windows 10 machine
If this is in a class property you could do it in the setter:
public class FooClass
{
private string foo;
public string Foo
{
get { return foo; }
set
{
if(!string.IsNullOrEmpty(value) && value.Length>5)
{
foo=value.Substring(0,5);
}
else
foo=value;
}
}
}
For the Javadoc tag @see
, you don't need to use @link
; Javadoc will create a link for you. Try
@see com.my.package.Class#method()
Slightly faster version of the implementation (If you know that most couples lists will have different lengths):
def checkEqual(L1, L2):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
Comparing:
>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)
>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up
When you input the body tag, press space just one time without closing the tag and input bgcolor="red"
, just for instance. Then choose a diff color for your font.
Post both multiple text inputs plus multiple files via Ajax in one Ajax request
HTML
<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">
Jquery Code
$(document).on('click','#btnSendData',function (event) {
event.preventDefault();
var form = $('#myform')[0];
var formData = new FormData(form);
// Set header if need any otherwise remove setup part
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
url: "{{route('sendFormWithImage')}}",// your request url
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log(data);
},
error: function () {
}
});
});
If you have N consumers then:
JMS Topics deliver messages to N of N JMS Queues deliver messages to 1 of N
You said you are "looking to have a 'thing' that will send a copy of the message to each subscriber in the same sequence as that in which the message was received by the ActiveMQ broker."
So you want to use a Topic in order that all N subscribers get a copy of the message.
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
This is the official Microsoft answer from the MS Connect forums. I am copying the relevant text below :-
When targeting .NET 4.5 Unobtrusive Validation is enabled by default. You need to have jQuery in your project and have something like this in Global.asax to register jQuery properly:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition {
Path = "~/scripts/jquery-1.4.1.min.js",
DebugPath = "~/scripts/jquery-1.4.1.js",
CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js",
CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js"
});
Replacing the version of jQuery with the version you are using.
You can also disable this new feature in web.config by removing the following line:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
This worked perfectly for me and does NOT require a file upload:
Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.
If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.
Note: Sending passwords in plain text is a BAD idea :)
Yes, we can check this.
print_lyrics()
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
As BJ Homer mentioned over above comments, A general rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.
Hope that helps.
Use specific value:
[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6
You need to use the special hiveconf for variable substitution. e.g.
hive> set CURRENT_DATE='2012-09-16';
hive> select * from foo where day >= ${hiveconf:CURRENT_DATE}
similarly, you could pass on command line:
% hive -hiveconf CURRENT_DATE='2012-09-16' -f test.hql
Note that there are env and system variables as well, so you can reference ${env:USER}
for example.
To see all the available variables, from the command line, run
% hive -e 'set;'
or from the hive prompt, run
hive> set;
Update:
I've started to use hivevar variables as well, putting them into hql snippets I can include from hive CLI using the source
command (or pass as -i option from command line).
The benefit here is that the variable can then be used with or without the hivevar prefix, and allow something akin to global vs local use.
So, assume have some setup.hql which sets a tablename variable:
set hivevar:tablename=mytable;
then, I can bring into hive:
hive> source /path/to/setup.hql;
and use in query:
hive> select * from ${tablename}
or
hive> select * from ${hivevar:tablename}
I could also set a "local" tablename, which would affect the use of ${tablename}, but not ${hivevar:tablename}
hive> set tablename=newtable;
hive> select * from ${tablename} -- uses 'newtable'
vs
hive> select * from ${hivevar:tablename} -- still uses the original 'mytable'
Probably doesn't mean too much from the CLI, but can have hql in a file that uses source, but set some of the variables "locally" to use in the rest of the script.
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.
You could do:
sub("*\\.[0-9]", "", a)
or
library(stringr)
str_sub(a, start=1, end=-3)
Do this:
list(map(chr,[66,53,0,94]))
In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.
If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map
object like so:
# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
print(ch)
Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.
Map<String, Integer> pointsByName = new HashMap<>();
Map<String, Integer> maxPointsByName = new HashMap<>();
Map<String, Double> gradesByName = pointsByName.entrySet().stream()
.map(entry -> new AbstractMap.SimpleImmutableEntry<>(
entry.getKey(), ((double) entry.getValue() /
maxPointsByName.get(entry.getKey())) * 100d))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake
file, which will help you with generating Makefile
.
With formulas, what you can do is:
D2
), add =COUNTA(A2:C2)
D4
in our example)D5
): =SUM(D2:D4)
Yes. In Xcode, you can go to Xcode
menu item -> Open Developer Tools
-> More Developer Tools
and download "Additional Tools for Xcode", which will have the Network Link Conditioner.
Using this tool, you can simulate different network scenarios (such as 100% loss, 3G, High latency DNS, and more) and you can create your own custom ones as well.
"start" is a name of a script, in npm you run scripts like this npm run scriptName
, npm start
is also a short for npm run start
As for "react-scripts" this is a script related specifically to create-react-app
The immediate problem is you have is with quoting: by using double quotes ("..."
), your variable references are instantly expanded, which is probably not what you want.
Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.
(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $
of references you do not want expanded with \
; e.g., \$var
).
However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin
input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<
, and the closing one on a line by itself - starting at the very first column; search for Here Documents
in man bash
or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.
If you quote the here-doc delimiter (EOF
in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \
:
echo "creating new script file."
cat <<'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}`
if [ $servicetest > /dev/null ]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi
EOF
As @BruceK notes, you can prefix your here-doc delimiter with -
(applied to this example: <<-"EOF"
) in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern.
Note, however, that this only works with actual tab characters, not leading spaces.
Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):
cat <<-'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service name: " ser
if [[ -n $(getsebool -a | grep "${ser}") ]]; then
echo "We are now going to work with ${ser}."
else
exit 1
fi
EOF
Finally, note that in bash
even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.
Thus, note how in the following #!/bin/bash
has to follow the opening '
immediately in order to become the first line of output:
echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi' > "$servfile"
Afterthoughts regarding the contents of your script:
$(...)
is preferred over `...`
for command substitution nowadays.${ser}
in the grep
command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).[[ -n $servicetest ]]
to test whether $servicetest
is empty (or perform the command substitution directly inside the conditional) - [[ ... ]]
- the preferred form in bash
- protects you from breaking the conditional if the $servicetest
happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ]
or [[ ... ]]
, as no stdout output is passed through; thus, the > /dev/null
is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).Do you want compare VBA with VB-Classic (VB6..) or VB.NET?
VBA (Visual Basic for Applications) is a vb-classic-based script language embedded in Microsoft Office applications. I think it's language features are similar to those of VB5 (it just lacks some few builtin functions), but:
You have access to the office document you wrote the VBA-script for and so you can e.g.
Example: Set the value of an excel-cell
ActiveSheet.Cells("A1").Value = "Foo"
VBC and -.NET are no script languages. You use them to write standalone-applications with separate IDE's which you can't do with VBA (VBA-scripts just "exist" in Office)
VBA has nothing to do with VB.NET (they just have a similar syntax).
By default, Jenkins stores all of its data in this directory on the file system.
There are a few ways to change the Jenkins home directory:
JENKINS_HOME
variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins
on Red Hat Linux).JENKINS_HOME
environment variable.JENKINS_HOME
before launching your web container, or before launching Jenkins directly from the WAR file.JENKINS_HOME
Java system property when launching your web container, or when launching Jenkins directly from the WAR file.web.xml
in jenkins.war (or its expanded image in your web container). This is not recommended.
This value cannot be changed while Jenkins is running.
It is shown here to help you ensure that your configuration is taking effect.It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep()
, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesthat's all you need
childView.frame = parentView.bounds
Truth values can be described using a Boolean algebra. The article also contains tables for and
and or
. This should help you to get started or to get even more confused.
Or you can use a for-each loop:
Collection<X> items = ...;
X last = null;
for (X x : items) last = x;
There are so many Answers. My solution for this was:
globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
console.log = function(message) {globalNamespace.globalArray.push(message)};
}
In short, if console.log doesn't exists (or in this case, isn't opened) then store the log in a global namespace Array. This way, you're not pestered with millions of alerts and you can still view your logs with the developer console opened or closed.
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = {_x000D_
first: "John",_x000D_
last: "Doe"_x000D_
};_x000D_
_x000D_
//_x000D_
// Visit non-inherited enumerable keys_x000D_
//_x000D_
Object.keys(obj).forEach(function(key) {_x000D_
_x000D_
console.log(key, obj[key]);_x000D_
_x000D_
});
_x000D_
Just try this.
<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>
This won't allow any characters to be entered inside the TextBox.
Official Android Documentation on the matter at hand with a step-by-step guide included on how to generate signed APK keys in Android Studio and even on how to setup the automatic APK key generation in a Gradle build.
https://developer.android.com/studio/publish/app-signing.html
Look under the chapter: Sign your release build
performance wise, my (crude) measurements found no difference on 1000 writes and reads
security wise, intuitively it would seem the localStore might be shut down before the sessionStore, but have no concrete evidence - maybe someone else does?
functional wise, concur with digitalFresh above
Guess you just missed the find method in the docs:
my_array.find {|e| e.satisfies_condition? }
CONVERT(varchar,GETDATE(),102)
Inherit Activity Class instead of ListActivity you can resolve this problem.
public class ExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
}
}
set intersection
and dict comprehension
can be used here
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}
Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'
It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.
Posting what was in the question body as CW answer.
Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a WindowEvent.WINDOW_CLOSING
at the application's event queue. Here's a synopsis of what the solution looks like
// closing down the window makes sense as a method, so here are
// the salient parts of what happens with the JFrame extending class ..
public class FooWindow extends JFrame {
public FooWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(5, 5, 400, 300); // yeah yeah, this is an example ;P
setVisible(true);
}
public void pullThePlug() {
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
}
}
// Here's how that would be employed from elsewhere -
// someplace the window gets created ..
FooWindow fooey = new FooWindow();
...
// and someplace else, you can close it thusly
fooey.pullThePlug();
#!/usr/bin/env python
import inspect
called=lambda: inspect.stack()[1][3]
def caller1():
print "inside: ",called()
def caller2():
print "inside: ",called()
if __name__=='__main__':
caller1()
caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py
inside: caller1
inside: caller2
shahid@shahid-VirtualBox:~/Documents$
I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards
depends on Less 1.7.0
https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less
.if(isnumber(2), {
.-then(){
log {
isnumber: true;
}
}
.-else(){
log {
isnumber: false;
}
}
});
.if(lightness(#fff) gt (20% * 2), {
.-then(){
log {
is-light: true;
}
}
});
using on example from above
.if(@debug, {
.-then(){
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
});
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
$location.search()
returns an object, consisting of the keys as variables and the values as its value.
So: if you write your query string like this:
?user=test_user_bLzgB
You could easily get the text like so:
$location.search().user
If you wish not to use a key, value like ?foo=bar, I suggest using a hash #test_user_bLzgB ,
and calling
$location.hash()
would return 'test_user_bLzgB' which is the data you wish to retrieve.
Additional info:
If you used the query string method and you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy instead of the html5 one... To get it working, add this config to your module
yourModule.config(['$locationProvider', function($locationProvider){
$locationProvider.html5Mode(true);
}]);
The easyest way is to change .attr() function to a javascript function .setAttribute()
$('#stop').click(function() {
$('next')[0].setAttribute('onclick','stopMoving()');
}
This happened on Windows 10 as well. I resolved it by creating an empty repositories.cfg file.
Generally speaking, fixed section should be set with width
, height
and top
, bottom
properties, otherwise it won't recognise its size and position.
If the used box is direct child for body and has neighbours, then it makes sense to check z-index
and top, left
properties, since they could overlap each other, which might affect your mouse hover while scrolling the content.
Here is the solution for a content box (a direct child of body
tag) which is commonly used along with mobile navigation.
.fixed-content {
position: fixed;
top: 0;
bottom:0;
width: 100vw; /* viewport width */
height: 100vh; /* viewport height */
overflow-y: scroll;
overflow-x: hidden;
}
Hope it helps anybody. Thank you!
forEach() :
return value : undefined
originalArray : not modified after the method call
newArray is not created after the end of method call.
map() :
return value : new Array populated with the results of calling a provided function on every element in the calling array
originalArray : not modified after the method call
newArray is created after the end of method call.
Since map builds a new array, using it when you aren't using the
returned array is an anti-pattern; use forEach or for-of instead.
For me work when i change my php.ini in my host:
; Default timeout for socket based streams (seconds)
default_socket_timeout = 300
I did it a slightly different way using a function within created().
created() {
window.addEventListener('click', (e) => {
if (!this.$el.contains(e.target)){
this.showMobileNav = false
}
})
},
This way, if someone clicks outside of the element, then in my case, the mobile nav is hidden.
Hope this helps!
References are cleaner and easier to use, and they do a better job of hiding information. References cannot be reassigned, however. If you need to point first to one object and then to another, you must use a pointer. References cannot be null, so if any chance exists that the object in question might be null, you must not use a reference. You must use a pointer. If you want to handle object manipulation on your own i.e if you want to allocate memory space for an object on the Heap rather on the Stack you must use Pointer
int *pInt = new int; // allocates *pInt on the Heap
Here is my code : )
app.Use((ctx, next) =>
{
ctx.Response.Headers.Add("Access-Control-Allow-Origin", ctx.Request.Headers["Origin"]);
ctx.Response.Headers.Add("Access-Control-Allow-Methods", "*");
ctx.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
ctx.Response.Headers.Add("Access-Control-Allow-Headers", "AccessToken,Content-Type");
ctx.Response.Headers.Add("Access-Control-Expose-Headers", "*");
if (ctx.Request.Method.ToLower() == "options")
{
ctx.Response.StatusCode = 204;
return Task.CompletedTask;
}
return next();
});
Modulus method is the usual method. We can also do this to check if odd or even:
def f(a):
if (a//2)*2 == a:
return 'even'
else:
return 'odd'
Integer division by 2 followed by multiplication by two.
I had similar error while trying to start httpd service for openstack train installation in RHEL 7.5 too.
-- Unit httpd.service has begun starting up.
Jan 31 10:11:16 controller httpd[1631]: (13)Permission denied: AH00072: make_sock: could not bind to address 10.0.0.11:5000
Jan 31 10:11:16 controller httpd[1631]: no listening sockets available, shutting down
Jan 31 10:11:16 controller httpd[1631]: AH00015: Unable to open logs
Jan 31 10:11:16 controller systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jan 31 10:11:16 controller kill[1632]: kill: cannot find process ""
Jan 31 10:11:16 controller systemd[1]: httpd.service: control process exited, code=exited status=1
Jan 31 10:11:16 controller systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
Solution: It got resolved by disabling SElinux.
Thought I would chip in here with when I have found ON
to be more useful than USING
. It is when OUTER
joins are introduced into queries.
ON
benefits from allowing the results set of the table that a query is OUTER
joining onto to be restricted while maintaining the OUTER
join. Attempting to restrict the results set through specifying a WHERE
clause will, effectively, change the OUTER
join into an INNER
join.
Granted this may be a relative corner case. Worth putting out there though.....
For example:
CREATE TABLE country (
countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(50) not null,
UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;
insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");
CREATE TABLE city (
cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
countryId int(10) unsigned not null,
city varchar(50) not null,
hasAirport boolean not null default true,
UNIQUE KEY cityUIdx1 (countryId,city),
CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;
insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);
-- Gah. Left outer join is now effectively an inner join
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
;
-- Hooray! I can see Monaco again thanks to
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
;
Use the WebView. Simple!!
http://developer.android.com/reference/android/webkit/WebView.html
If you want to reset the window layout. Then
go to "WINDOW" -> "RESET WINDOW LAYOUT"
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
In the synchronous case, the console.log command is not executed until the SQL query has finished executing.
In the asynchronous case, the console.log command will be directly executed. The result of the query will then be stored by the "callback" function sometime afterwards.
Microsoft's Using sp_executesql article recommends using sp_executesql
instead of execute
statement.
Because this stored procedure supports parameter substitution, sp_executesql is more versatile than EXECUTE; and because sp_executesql generates execution plans that are more likely to be reused by SQL Server, sp_executesql is more efficient than EXECUTE.
So, the take away: Do not use execute
statement. Use sp_executesql
.
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2shush
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
You can do it like this:
//HTML BUTTON
<button type="button" onclick="disableAll()">Disable</button>
//Jquery function
function disableAll() {
//DISABLE ALL FIELDS THAT ARE NOT DISABLED
$('form').find(':input:not(:disabled)').prop('disabled', true);
//ENABLE ALL FIELDS THAT DISABLED
//$('form').find(':input(:disabled)').prop('disabled', false);
}
UPDATE T1,T2
INNER JOIN T1 ON T1.Brands = T2.Brands
SET
T1.Inci = T2.Inci
WHERE
T1.Category= T2.Category
AND
T1.Date = T2.Date
Help → Install new Software → Switch to the Kepler Repository → General Purpose Tools → Marketplace Client
If you use Eclipse Luna SR 1, the released Marketplace contains a bug; you have to install it from the Marketplace update site. This is fixed again in Luna SR 2.
Marketplace update site:
this turns the recursion in to a loop:
def checkNextID(ID):
global numOfRuns, curRes, lastResult
while ID < lastResult:
try:
numOfRuns += 1
if numOfRuns % 10 == 0:
time.sleep(3) # sleep every 10 iterations
if isValid(ID + 8):
parseHTML(curRes)
ID = ID + 8
elif isValid(ID + 18):
parseHTML(curRes)
ID = ID + 18
elif isValid(ID + 7):
parseHTML(curRes)
ID = ID + 7
elif isValid(ID + 17):
parseHTML(curRes)
ID = ID + 17
elif isValid(ID+6):
parseHTML(curRes)
ID = ID + 6
elif isValid(ID + 16):
parseHTML(curRes)
ID = ID + 16
else:
ID = ID + 1
except Exception, e:
print "somethin went wrong: " + str(e)
For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:
For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:
A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.
0, if no rows are affected by the operation.
-1, if the operation is a mass delete on a segmented table space.
For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.
another solution disown the job
$ nohup node server.js &
[1] 1711
$ disown -h %1
If you have array of custom Objects, you can search by specific property like this:
if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
doctorsInArea.remove(at: index)
}
or if you want to search by name for example
if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
doctorsInArea.remove(at: index)
}
When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}
.
@click
is just shorthand for v-on:click
directive so the same rules apply.
In your case, simply use @click="addToCount(item.contactID)"
if you are newly implementing recaptcha on your site, I would suggest adding api.js and let google collect behavioral data of your users 1-2 days. It is much fail-safe this way, especially before starting to use score.
node.innerHTML = "";
Non-standard, but fast and well supported.
const originalArr = [1,2,3,4,5,6,7,8,9,10,11];
const splittedArray = [];
while (originalArr.length > 0) {
splittedArray.push(originalArr.splice(0,range));
}
output for range 3
splittedArray === [[1,2,3][4,5,6][7,8,9][10,11]]
output for range 4
splittedArray === [[1,2,3,4][5,6,7,8][9,10,11]]
Here's an example of the string "abc" repeated
3 times:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
int main() {
ostringstream repeated;
fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
cout << "repeated: " << repeated.str() << endl; // repeated: abcabcabc
return 0;
}
This worked for me.
git reset --hard ORIG_HEAD
Undo a merge or pull:
$ git pull (1)
Auto-merging nitfol
CONFLICT (content): Merge conflict in nitfol
Automatic merge failed; fix conflicts and then commit the result.
$ git reset --hard (2)
$ git pull . topic/branch (3)
Updating from 41223... to 13134...
Fast-forward
$ git reset --hard ORIG_HEAD (4)
Checkout this: HEAD and ORIG_HEAD in Git for more.
Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :
DROP TABLE IF EXISTS devops_guide CASCADE;
SELECT 'create the "devops_guide" table'
;
CREATE TABLE devops_guide (
guid UUID NOT NULL DEFAULT gen_random_uuid()
, level integer NULL
, seq integer NOT NULL DEFAULT 1
, name varchar (200) NOT NULL DEFAULT 'name ...'
, description text NULL
, CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
) WITH (
OIDS=FALSE
);
-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
RETURNS TRIGGER
AS $$
BEGIN
UPDATE devops_guide SET seq=col_serial FROM
(SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
WHERE devops_guide.guid=tmp_devops_guide.guid;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_devops_guide_set_all_seq
AFTER UPDATE OR DELETE ON devops_guide
FOR EACH ROW
WHEN (pg_trigger_depth() < 1)
EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();
with .Equals, you also gain the StringComparison options. very handy for ignoring case and other things.
btw, this will evaluate to false
string a = "myString";
string b = "myString";
return a==b
Since == compares the values of a and b (which are pointers) this will only evaluate to true if the pointers point to the same object in memory. .Equals dereferences the pointers and compares the values stored at the pointers. a.Equals(b) would be true here.
and if you change b to:
b = "MYSTRING";
then a.Equals(b) is false, but
a.Equals(b, StringComparison.OrdinalIgnoreCase)
would be true
a.CompareTo(b) calls the string's CompareTo function which compares the values at the pointers and returns <0 if the value stored at a is less than the value stored at b, returns 0 if a.Equals(b) is true, and >0 otherwise. However, this is case sensitive, I think there are possibly options for CompareTo to ignore case and such, but don't have time to look now. As others have already stated, this would be done for sorting. Comparing for equality in this manner would result in unecessary overhead.
I'm sure I'm leaving stuff out, but I think this should be enough info to start experimenting if you need more details.
There is a minor difference between const and static readonly fields in C#.Net
const must be initialized with value at compile time.
const is by default static and needs to be initialized with constant value, which can not be modified later on. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.
public const DateTime dt = DateTime.Today; //throws compilation error
public const string Name = string.Empty; //throws compilation error
public static readonly string Name = string.Empty; //No error, legal
readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor once. So there is a possibility to change value of readonly field once (does not matter, if it is static or not), which is not possible with const.
The value of EOF is a negative integer to distinguish it from "char" values that are in the range 0 to 255. It is typically -1, but it could be any other negative number ... according to the POSIX specs, so you should not assume it is -1.
The ^D character is what you type at a console stream on UNIX/Linux to tell it to logically end an input stream. But in other contexts (like when you are reading from a file) it is just another data character. Either way, the ^D character (meaning end of input) never makes it to application code.
As @Bastien says, EOF is also returned if getchar()
fails. Strictly speaking, you should call ferror
or feof
to see whether the EOF represents an error or an end of stream. But in most cases your application will do the same thing in either case.
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
There is already a predefined constant. Use Color.TRANSPARENT
.
You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes:
SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan'
You then have to copy and run the statements in query analyzer.
Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though.
DECLARE @old sysname, @new sysname, @sql varchar(1000)
SELECT
@old = 'jonathan'
, @new = 'dbo'
, @sql = '
IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
WHERE
QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
AND TABLE_SCHEMA = ''' + @old + '''
)
EXECUTE sp_changeobjectowner ''?'', ''' + @new + ''''
EXECUTE sp_MSforeachtable @sql
Got it from this site.
It also talks about doing the same for stored procs if you need to.
Just add another way , in normal mode , type ctrl+v
then G
, select the rest, then D
, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.
The answer to this post was very helpful and a big time saver. However, I found that when using FontAwesome 4.50
, I had to add an additional configuration for woff2
type of extension also as shown below else requests for woff2
type was giving a 404 error in Chrome's Developer Tools under Console> Errors.
According to the comment by S.Serp, the below configuration should be put within <system.webServer>
tag.
<staticContent>
<remove fileExtension=".woff" />
<!-- In case IIS already has this mime type -->
<mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
<remove fileExtension=".woff2" />
<!-- In case IIS already has this mime type -->
<mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
</staticContent>
There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.
If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.
If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.
The props vs state summary I like best is here: react-guide Big hat tip to those guys. Below is an edited version of that page:
tl;dr If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.
Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.
The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.
props state Can get initial value from parent Component? Yes Yes Can be changed by parent Component? Yes No Can set default values inside Component?* Yes Yes Can change inside Component? No Yes Can set initial value for child Components? Yes Yes Can change in child Components? Yes No
State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.
Stateless Component Only props, no state. There's not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.
Stateful Component Both props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
use this for fixing issue with shadow box
filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='2', OffY='2', Color='#F13434', Positive='true');
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)
The general consensus is that you do not (should not) need to dispose of HttpClient.
Many people who are intimately involved in the way it works have stated this.
See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.
I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:
Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request. The HttpClient object is intended to live for as long as your application needs to make HTTP requests. Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.
Or even open up DotPeek.
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
The best example which i know.
public abstract class DisposableType: IDisposable
{
bool disposed = false;
~DisposableType()
{
if (!disposed)
{
disposed = true;
Dispose(false);
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
Dispose(true);
GC.SuppressFinalize(this);
}
}
public void Close()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// managed objects
}
// unmanaged objects and resources
}
}
In our case, everything LOOKED ok, but it took most of the day to figure this out:
TLDR: Check your certificate paths to make sure the root certificate is correct. In the case of COMODO certificates, it should say "USERTrust" and be issued by "AddTrust External CA Root". NOT "COMODO" issued by "COMODO RSA Certification Authority".
From the CloudFront docs: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html
If the origin server returns an invalid certificate or a self-signed certificate, or if the origin server returns the certificate chain in the wrong order, CloudFront drops the TCP connection, returns HTTP error code 502, and sets the X-Cache header to Error from cloudfront.
We had the right ciphers enabled as per: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#RequestCustomEncryption
Our certificate was valid according to Google, Firefox and ssl-checker: https://www.sslshopper.com/ssl-checker.html
However the last certificate in the ssl checker chain was "COMODO RSA Domain Validation Secure Server CA", issued by "COMODO RSA Certification Authority"
It seems that CloudFront does not hold the certificate for "COMODO RSA Certification Authority" and as such thinks the certificate provided by the origin server is self signed.
This was working for a long time before apparently suddenly stopping. What happened was I had just updated our certificates for the year, but during the import, something was changed in the certificate path for all the previous certificates. They all started referencing "COMODO RSA Certification Authority" whereas before the chain was longer and the root was "AddTrust External CA Root".
Because of this, switching back to the older cert did not fix the cloudfront issue.
I had to delete the extra certificate named "COMODO RSA Certification Authority", the one that did not reference AddTrust. After doing this, all my website certificates' paths updated to point back to AddTrust/USERTrust again. Note can also open up the bad root certificate from the path, click "Details" -> "Edit Properties" and then disable it that way. This updated the path immediately. You may also need to delete multiple copies of the certificate, found under "Personal" and "Trusted Root Certificate Authorities"
Finally I had to re select the certificate in IIS to get it to serve the new certificate chain.
After all this, ssl-checker started displaying a third certificate in the chain, which pointed back to "AddTrust External CA Root"
Finally, CloudFront accepted the origin server's certificate and the provided chain as being trusted. Our CDN started working correctly again!
To prevent this happening in the future, we will need to export our newly generated certificates from a machine with the correct certificate chain, i.e. distrust or delete the certificate "COMODO RSA Certification Authroity" issued by "COMODO RSA Certification Authroity" (expiring in 2038). This only seems to affect windows machines, where this certificate is installed by default.
You usually see it in the ternary assignment operator;
Syntax
variable = `condition ? result 1 : result 2;`
example:
boolean isNegative = number > 0 ? false : true;
which is "equivalent" in nature to the if else
if(number > 0){
isNegative = false;
}
else{
isNegative = true;
}
Other than examples given by different posters,
you can also use : to signify a label for a block which you can use in conjunction with continue and break..
for example:
public void someFunction(){
//an infinite loop
goBackHere: { //label
for(int i = 0; i < 10 ;i++){
if(i == 9 ) continue goBackHere;
}
}
}
the simplest way
<input type="submit" style="width:0px; height:0px; opacity:0;"/>
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">
Please read the following information:
Below is the script which is integrated into ansible and generating dashboard in CSV format.
sh collection.sh
#!/bin/bash
HOSTNAME=`hostname -s`
for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt
sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt
paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt
My output stored in below text files.
cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt
This would work too:
document.getElementsByTagName('p')[0].id
(If element where the 1st paragraph in your document)
Going forward, for graphical elements that are purely decorative, the best solution is to use:
android:importantForAccessibility="no"
This makes sense if your min SDK version is at least 16, since devices running lower versions will ignore this attribute.
If you're stuck supporting older versions, you should use (like others pointed out already):
android:contentDescription="@null"
Source: https://developer.android.com/guide/topics/ui/accessibility/apps#label-elements
Below code gives in hh:mm format.
select RIGHT(LEFT(job_end- job_start,17),5)
Instead of a functor as Mehrdad proposed, you could use a Lambda function.
sort(numbers.begin(), numbers.end(), [](const int a, const int b) {return a > b; });
But one thing is that also if you have nested curly-braces, won't work for format but %
will work.
Example:
>>> '{{0}, {1}}'.format(1,2)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
'{{0}, {1}}'.format(1,2)
ValueError: Single '}' encountered in format string
>>> '{%s, %s}'%(1,2)
'{1, 2}'
>>>
Try to use flags: 'a'
to append data to a file
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});
The smarter_csv
gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.
require 'smarter_csv'
options = {}
SmarterCSV.process('input_file.csv', options) do |chunk|
chunk.each do |data_hash|
Moulding.create!( data_hash )
end
end
You can use the option chunk_size
to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.
See also: https://github.com/tilo/smarter_csv
while 1:
root.update()
... is (very!) roughly similar to:
root.mainloop()
The difference is, mainloop
is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop
is a much cleaner solution. After all, calling mainloop
is essentially this under the covers:
while the_window_has_not_been_destroyed():
wait_until_the_event_queue_is_not_empty()
event = event_queue.pop()
event.handle()
... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?
Put in the simplest terms possible: always call mainloop
as the last logical line of code in your program. That's how Tkinter was designed to be used.
I guess something like this would do the job.
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);
In June 2016 Google announced that they would stop supporting keyless usage, meaning any request that doesn’t include an API key or Client ID. This will go into effect on June 11 2018, and keyless access will no longer be supported
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
You can get a circular gradient using android:type="radial"
:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:type="radial" android:gradientRadius="250dp"
android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
The CONTINUE
statement is a new feature in 11g.
Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL
setTimeout() function it's use to delay a process in JavaScript.
w3schools has an easy tutorial about this function.
On MacOSX, by combining the answers from Calaf and Ollie Ford, the following worked for me.
On the command line (be sure adb is in your path, mine was at ~/Library/Android/sdk/platform-tools/adb) and with your android device plugged in and in USB debugging mode, run:
adb backup -f backup com.mypackage.myapp
Your android device will ask you for permission to backup your data. Select "BACKUP MY DATA"
Wait a few moments.
The file backup will appear in the directory where you ran adb.
Now run:
dd if=backup bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" > backup.tar
Now you'll you have a backup.tar file you can untar like this:
tar xvf backup.tar
And see all the files stored by your application.
Improving upon @Ianl's answer,
It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.
If you want to disable the prompts for both the username and password then you can set the URL as follows -
git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git
Note that the URL has both the username and password. Also the .git/config
file should show your current settings.
Update 20200128:
If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.
It would look like this -
git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git
AFAIK the best you can do to emulate Split()
is to use FILTERXML
which is available from Excel 2013 onwards (not Excel Online or Mac).
The syntax more or less always is:
=FILTERXML("<t><s>"&SUBSTITUTE(A1,"|","</s><s>")&"</s></t>","//s")
This would return an array to be used in other functions and would even hold up if no delimiter is found. If you want to read more about it, maybe you are interested in this post.
Example to set in the "V" environment variable the most recent file
FOR /F %I IN ('DIR *.* /O:D /B') DO SET V=%I
in a batch file you have to use double prefix in the loop variable:
FOR /F %%I IN ('DIR *.* /O:D /B') DO SET V=%%I
I don't know for sure if the solution is safe, but about the ClassGuard solution, it's interesting to read the article and the comment at: http://www.javaworld.com/community/?q=node/1604#comment-12296
How about this:
string test = "01-12-12";
try{
DateTime dateTime = DateTime.Parse(test);
test = dateTime.ToString("dd/yyyy");
}
catch (FormatException exc)
{
MessageBox.Show(exc.Message);
}
Where test will be equal to "12/2012"
Hope it helps!
Please read HERE.
You could also use jOOL library - https://github.com/jOOQ/jOOL
It has already prepared function interfaces with different number of parameters. For instance, you could use org.jooq.lambda.function.Function3
, etc from Function0
up to Function16
.
A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destructors. Roughly speaking, a type is a POD when the only things in it are built-in types and combinations of them. The result is something that "acts like" a C type.
int
, char
, wchar_t
, bool
, float
, double
are PODs, as are long/short
and signed/unsigned
versions of them.enums
are PODsconst
or volatile
POD is a POD.class
, struct
or union
of PODs is a POD provided that all non-static data members are public
, and it has no base class and no constructors, destructors, or virtual methods. Static members don't stop something being a POD under this rule. This rule has changed in C++11 and certain private members are allowed: Can a class with all private members be a POD class?3.9(10): "Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2) and cv-qualified versions of these types (3.9.3) are collectively caller scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types"
9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.
8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."
You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})
It would be helpful if you posted your code.
Swift 3.0/4.0
If you have created your own custom cell you can change the selection color on awakeFromNib()
for all of the cells:
override func awakeFromNib() {
super.awakeFromNib()
let colorView = UIView()
colorView.backgroundColor = UIColor.orange.withAlphaComponent(0.4)
self.selectedBackgroundView = colorView
}
Replace this:
c1.set(Calendar.HOUR, d1.getHours());
with this:
c1.set(Calendar.HOUR_OF_DAY, d1.getHours());
Calendar.HOUR is strictly for 12 hours.
It seems to me that you want to change the contents of menu inside a local method, and this method is called at any time, whenever an event is occurred, or in the activity UI thread.
Why don't you take the instance of Menu in the global variable in onPrepareOptionsMenu when this is overridden and use in this method of yours. Be sure that this method is called whenever an event is occurred (like button click), or in the activity UI thread, handler or async-task post-execute.
You should know in advance the index of this menu item you want to change. After clearing the menu, you need to inflate the menu XML and update your item's name or icon.
I use uploaded images on my website and I would definitely say option a).
One other thing I'd highly recommend is immediately changing the file name from what the user has named the photo, to something more manageable. For example something with the date and time to uniquely identify each picture.
It also helps to strip the user's file name of any strange characters to avoid future complications.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
For those who created rating bar programmatically and want set small rating bar instead of default big rating bar
private LinearLayout generateRatingView(float value){ LinearLayout linearLayoutRating=new LinearLayout(getContext()); linearLayoutRating.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); linearLayoutRating.setGravity(Gravity.CENTER); RatingBar ratingBar = new RatingBar(getContext(),null, android.R.attr.ratingBarStyleSmall); ratingBar.setEnabled(false); ratingBar.setStepSize(Float.parseFloat("0.5"));//for enabling half star ratingBar.setNumStars(5); ratingBar.setRating(value); linearLayoutRating.addView(ratingBar); return linearLayoutRating; }
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh
(and possibly play.csh
, etc):
PATH=$PATH:/home/me/play
export PATH
use -ProjectName option in Package Manager Console:
Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
The following will remove all the objects from your console
rm(list = ls())
DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'
Then change your query to use this logic:
AND
(
tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate)
AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)
It seems to work if you use
div#scrollable {
overflow-y: scroll;
height: 100%;
}
and add padding-bottom: 60px
to div.sidebar
.
For example: http://jsfiddle.net/AKL35/6/
However, I am unsure why it must be 60px
.
Also, you missed the f
from overflow-y: scroll;
The possible solution (Tested on ubuntu)
geany .bashrc
export CLASSPATH=$CLASSPATH:/web/apache-tomcat-8.5.39/lib/servlet-api.jar
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
Use this to delete everything:
docker system prune -a --volumes
Remove all unused containers, volumes, networks and images
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all volumes not used by at least one container
- all images without at least one container associated to them
- all build cache
https://docs.docker.com/engine/reference/commandline/system_prune/#extended-description
This problem can generally occur when you do not enable two step verification for the gmail
account (which can be done here) you are using to send an email
. So first, enable two step verification
, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password
. And use the app password
in your .env
file. When you are done with it, your .env
file will look something like.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls
and your mail.php
<?php
return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
];
After doing so, run php artisan config:cache
and php artisan config:clear
, then check, email should work.
function getKeys(obj){
var keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
}
return keys;
}
@wcm - actually to nit pick the Table Variable isn't Ram only - it can be partially stored on disk.
A temp table can have indexes, whereas a table variable can only have a primary index. If speed is an issue Table variables can be faster, but obviously if there are a lot of records, or the need to search the temp table of a clustered index, then a Temp Table would be better.
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
The current free version is PIL 1.1.7. This release supports Python 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be released later.
Your python version is 3.4.1, PIL do not support!
We can use having here which work on aggregate functions as shown below
create table #TableB (id_account int, data int, [date] date)
insert into #TableB values (1 ,-50, '10/20/2018'),
(1, 20, '10/09/2018'),
(2 ,-900, '10/01/2018'),
(1 ,20, '09/25/2018'),
(1 ,-100, '08/01/2018')
SELECT id_account , data, COUNT(*)
FROM #TableB
GROUP BY id_account , data
HAVING COUNT(id_account) > 1
drop table #TableB
Here as two fields id_account and data are used with Count(*). So, it will give all the records which has more than one times same values in both columns.
We some reason mistakely we had missed to add any constraints in SQL server table and the records has been inserted duplicate in all columns with front-end application. Then we can use below query to delete duplicate query from table.
SELECT DISTINCT * INTO #TemNewTable FROM #OriginalTable
TRUNCATE TABLE #OriginalTable
INSERT INTO #OriginalTable SELECT * FROM #TemNewTable
DROP TABLE #TemNewTable
Here we have taken all the distinct records of the orignal table and deleted the records of original table. Again we inserted all the distinct values from new table to the original table and then deleted new table.
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
In Codeignitor version 3.0.x the system/core/Codeigniter.php do not contain the time constraint as well as inserting
ini_set('MAX_EXECUTION_TIME', -1);
will not work since codeignitor will override that with its own function set_time_limit() . So either you have to delete that function from codeignitor or simply you can insert
set_time_limit('1000');
in the beginning of the php file if you wanna change that to 1000 seconds. Set the time to 0 (zero) if you want to run it as long as it want.
I used Jason's answer but wanted to clarify how to get in to properties.
Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:
IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;
The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).
$ git rev-parse --abbrev-ref HEAD
master
This should work with Git 1.6.3 or newer.
Here is an approach where Inkscape is called by Python.
Note that it suppresses certain crufty output that Inkscape writes to the console (specifically, stderr and stdout) during normal error-free operation. The output is captured in two string variables, out
and err
.
import subprocess # May want to use subprocess32 instead
cmd_list = [ '/full/path/to/inkscape', '-z',
'--export-png', '/path/to/output.png',
'--export-width', 100,
'--export-height', 100,
'/path/to/input.svg' ]
# Invoke the command. Divert output that normally goes to stdout or stderr.
p = subprocess.Popen( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
# Below, < out > and < err > are strings or < None >, derived from stdout and stderr.
out, err = p.communicate() # Waits for process to terminate
# Maybe do something with stdout output that is in < out >
# Maybe do something with stderr output that is in < err >
if p.returncode:
raise Exception( 'Inkscape error: ' + (err or '?') )
For example, when running a particular job on my Mac OS system, out
ended up being:
Background RRGGBBAA: ffffff00
Area 0:0:339:339 exported to 100 x 100 pixels (72.4584 dpi)
Bitmap saved as: /path/to/output.png
(The input svg file had a size of 339 by 339 pixels.)
If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.
I created my email sending this way:
function send_mail($email, $recipient_name, $message='')
{
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = "utf-8";
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = "mail.example.com"; // Specify main and backup server
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "myusername"; // SMTP username
$mail->Password = "p@ssw0rd"; // SMTP password
$mail->From = "[email protected]";
$mail->FromName = "System-Ad";
$mail->AddAddress($email, $recipient_name);
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML (true) or plain text (false)
$mail->Subject = "This is a Sampleenter code here Email";
$mail->Body = $message;
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
$mail->AddEmbeddedImage('images/logo.png', 'logo', 'logo.png');
$mail->addAttachment('files/file.xlsx');
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.
If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you.
It can be as simple as this : $("#element").transition({x:'90px'})
.
Take it from this link : http://ricostacruz.com/jquery.transit/
The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.
Express currently treats app.get("/foo*")
as app.get(/\/foo(.*)/)
, removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "*
in a path is replaced with .+
".
Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.
The WHATWG HTML spec has the exact algorithm for parsing a legacy color value: https://html.spec.whatwg.org/multipage/infrastructure.html#rules-for-parsing-a-legacy-colour-value.
The code Netscape Classic used for parsing color strings is open source: https://dxr.mozilla.org/classic/source/lib/layout/layimage.c#155.
For example, notice that each character is parsed as a hex digit and then is shifted into a 32-bit integer without checking for overflow. Only eight hex digits fit into a 32-bit integer, which is why only the last 8 characters are considered. After parsing the hex digits into 32-bit integers, they are then truncated into 8-bit integers by dividing them by 16 until they fit into 8-bit, which is why leading zeros are ignored.
Update: This code does not exactly match what is defined in the spec, but the only difference there is a few lines of code. I think it is these lines that was added (in Netscape 4):
if (bytes_per_val > 4)
{
bytes_per_val = 4;
}
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
- What is the difference between connection and read timeout for sockets?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read
call, a read timeout error will be raised.
- What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?
It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt()
call may also do the trick ... not sure.)
- What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?
It means that a call to read
on the socket stream may block for ever. Once again there is no infinite loop, but the read
can be unblocked by a Thread.interrupt()
call, closing the socket, and (of course) the other end sending data or closing the connection.
1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.
I've been trying to find answer to this questions for two days. Many answers direct you to different issues. But serpentr's answer above is really to the point. It is the shortest, simplest solution. Just a reminder the last word "var" represents the variable name, so should be used as:
result = driver.execute_script('var text = document.title ; return text')
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
Use commitAllowingStateLoss()
instead of commit()
.
when you use commit()
it will can throw an exception if state loss occurs but commitAllowingStateLoss()
saves transaction without state loss so that will doesn't throw an exception if state loss occurs.
try setting AutoPostBack="True"
on the DropDownList.
I have take comments below into consideration and agreed. Eval is to be avoided.
Accessing root properties in object is easily achieved with obj[variable]
, but getting nested complicates thing. Not to write already written code I suggest to use lodash.get
.
Example
// Accessing root property
var rootProp = 'rootPropert';
_.get(object, rootProp, defaultValue);
// Accessing nested property
var listOfNestedProperties = [var1, var2];
_.get(object, listOfNestedProperties);
Lodash get can be used on different ways, here is link to the documentation lodash.get
As Foo
is a class can you not create virtual overloaded Initialise()
methods? Then they would be available to sub-classes and still extensible?
public class Foo
{
...
public Foo() {...}
public virtual void Initialise(int i) {...}
public virtual void Initialise(int i, int i) {...}
public virtual void Initialise(int i, int i, int i) {...}
...
public virtual void Initialise(int i, int i, ..., int i) {...}
...
public virtual void SomethingElse() {...}
...
}
This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.
You can get a list of any configured remote URLs with the command git remote -v
.
This will give you something like the following:
base /home/***/htdocs/base (fetch)
base /home/***/htdocs/base (push)
origin [email protected]:*** (fetch)
origin [email protected]:*** (push)
Run the script as source= to run in debug mode as well.
source= ./myscript.sh
If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.
Assuming that ID
is an identity column:
INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32
Try to avoid loops with SQL. Try to think in terms of sets instead.
An alternative in Java 8:
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);