No, but another great alternative is having the method use a generic template class for optional parameters as follows:
public class OptionalOut<Type>
{
public Type Result { get; set; }
}
Then you can use it as follows:
public string foo(string value, OptionalOut<int> outResult = null)
{
// .. do something
if (outResult != null) {
outResult.Result = 100;
}
return value;
}
public void bar ()
{
string str = "bar";
string result;
OptionalOut<int> optional = new OptionalOut<int> ();
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
// example: call it with named optional parameter
foo (str, outResult: optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}
It might be interesting to some of you that in case of multiple default parameters:
void printValues(int x=10, int y=20, int z=30)
{
std::cout << "Values: " << x << " " << y << " " << z << '\n';
}
Given the following function calls:
printValues(1, 2, 3);
printValues(1, 2);
printValues(1);
printValues();
The following output is produced:
Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30
Reference: http://www.learncpp.com/cpp-tutorial/77-default-parameters/
Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.
\newcount\seccount
\def\sec{%
\seccount0%
\let\go\secnext\go
}
\def\secnext#1{%
\def\last{#1}%
\futurelet\next\secparse
}
\def\secparse{%
\ifx\next\bgroup
\let\go\secparseii
\else
\let\go\seclast
\fi
\go
}
\def\secparseii#1{%
\ifnum\seccount>0, \fi
\advance\seccount1\relax
\last
\def\last{#1}%
\futurelet\next\secparse
}
\def\seclast{\ifnum\seccount>0{} and \fi\last}%
\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"
\sec{a}
% outputs "a"
\sec{a}{b}
% outputs "a and b"
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
A slightly extended example to initialize all missing arguments with None
:
from collections import namedtuple
class Node(namedtuple('Node', ['value', 'left', 'right'])):
__slots__ = ()
def __new__(cls, *args, **kwargs):
# initialize missing kwargs with None
all_kwargs = {key: kwargs.get(key) for key in cls._fields}
return super(Node, cls).__new__(cls, *args, **all_kwargs)
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
This works too. It seems shortest working notation:
!$('#selector:checked')
<roleManager
enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add
connectionStringName="MembershipConnection"
applicationName="Mvc3"
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add
applicationName="Mvc3"
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
I tried solution based on Laplacian filter from this post. It didn't help me. So, I tried the solution from this post and it was good for my case (but is slow):
import cv2
image = cv2.imread("test.jpeg")
height, width = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
def px(x, y):
return int(gray[y, x])
sum = 0
for x in range(width-1):
for y in range(height):
sum += abs(px(x, y) - px(x+1, y))
Less blurred image has maximum sum
value!
You can also tune speed and accuracy by changing step, e.g.
this part
for x in range(width - 1):
you can replace with this one
for x in range(0, width - 1, 10):
If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.
As noted in an issue in the Roslyn project on GitHub, a solution (that worked for me) is to simply unload and reload the project in Visual Studio.
The "bin\roslyn" folder wasn't created on build or rebuild until I reloaded the project.
Btw you can also use the ui-sref attribute in your templates to pass objects
ui-sref="myState({ myParam: myObject })"
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
If you want to manually install NLTK Corpus.
1) Go to http://www.nltk.org/nltk_data/ and download your desired NLTK Corpus file.
2) Now in a Python shell check the value of nltk.data.path
3) Choose one of the path that exists on your machine, and unzip the data files into the corpora sub directory inside.
4) Now you can import the data from nltk.corpos import stopwords
Reference: https://medium.com/@satorulogic/how-to-manually-download-a-nltk-corpus-f01569861da9
Swift 3 Solution:
private func createImagesFolder() {
// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
if let documentDirectoryPath = documentDirectoryPath {
// create the custom folder path
let imagesDirectoryPath = documentDirectoryPath.appending("/images")
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: imagesDirectoryPath) {
do {
try fileManager.createDirectory(atPath: imagesDirectoryPath,
withIntermediateDirectories: false,
attributes: nil)
} catch {
print("Error creating images folder in documents dir: \(error)")
}
}
}
}
You have several techniques to do it.
This post - read the part about the revert will explain in details what we want to do and how to do it.
Here is the most simple solution to your problem:
# Checkout the desired branch
git checkout <branch>
# Undo the desired commit
git revert <commit>
# Update the remote with the undo of the code
git push origin <branch>
The revert command will create a new commit with the undo of the original commit.
I've developed my own MySQL escape method in Java (if useful for anyone).
See class code below.
Warning: wrong if NO_BACKSLASH_ESCAPES SQL mode is enabled.
private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;
static
{
//MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
String[][] search_regex_replacement = new String[][]
{
//search string search regex sql replacement regex
{ "\u0000" , "\\x00" , "\\\\0" },
{ "'" , "'" , "\\\\'" },
{ "\"" , "\"" , "\\\\\"" },
{ "\b" , "\\x08" , "\\\\b" },
{ "\n" , "\\n" , "\\\\n" },
{ "\r" , "\\r" , "\\\\r" },
{ "\t" , "\\t" , "\\\\t" },
{ "\u001A" , "\\x1A" , "\\\\Z" },
{ "\\" , "\\\\" , "\\\\\\\\" }
};
sqlTokens = new HashMap<String,String>();
String patternStr = "";
for (String[] srr : search_regex_replacement)
{
sqlTokens.put(srr[0], srr[2]);
patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];
}
sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}
public static String escape(String s)
{
Matcher matcher = sqlTokenPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while(matcher.find())
{
matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
Based on comment of @alessandro-pezzato.
Run multiples commands by using &
between the commands.
Example:
$ sleep 3 & sleep 5 & sleep 2 &
It's will execute the commands in background.
I looked for a solution to this problem, and came across the present page. I implemented the above solution:
$("#testdiv",opener.document) //doesn't work
But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.
I found this working solution on another stackoverflow page: how to access parent window object using jquery?
From which I got this working solution:
window.opener.$("#testdiv") //This works.
I use do-while loops all the time when reading in files. I work with a lot of text files that include comments in the header:
# some comments
# some more comments
column1 column2
1.234 5.678
9.012 3.456
... ...
i'll use a do-while loop to read up to the "column1 column2" line so that I can look for the column of interest. Here's the pseudocode:
do {
line = read_line();
} while ( line[0] == '#');
/* parse line */
Then I'll do a while loop to read through the rest of the file.
Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/
This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run
import os
os.getcwd()
you'll see this is true.
However, let's say you're using an ipython notebook, run os.getcwd()
and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir
setting).
The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:
import sys
sys.path.append('my/path/to/module/folder')
import module-of-interest
If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.
The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.
Remove both http and https setting by using commands.
git config --global --unset http.proxy
git config --global --unset https.proxy
It doesn't work because Date - Date
relies on exactly the kind of type coercion TypeScript is designed to prevent.
There is a workaround this using the +
prefix:
var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");
Or, if you prefer not to use Date.now()
:
var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));
Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()
An extension of juba's method is to use reformulate
, a function which is explicitly designed for such a task.
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
For the example in the OP, the easiest solution here would be
# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
or
mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
Note that adding the dependent variable to the data.frame in d <- cbind(y, d)
is preferred not only because it allows for the use of reformulate
, but also because it allows for future use of the lm
object in functions like predict
.
I have written a very simple tool that does exactly that - it's called PE Deconstructor.
Simply fire it up and load your DLL file:
In the example above, the loaded DLL is 32-bit.
You can download it here (I only have the 64-bit version compiled ATM):
http://files.quickmediasolutions.com/exe/pedeconstructor_0.1_amd64.exe
An older 32-bit version is available here:
http://dl.dropbox.com/u/31080052/pedeconstructor.zip
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ...
, or <html><body>NOT FOUND</body></html>
).
In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).
I would suggest this to handle both cases:
// parse response as json, or else as txt
static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
(async () => {
var responseString = await response.text();
try{
if (responseString && typeof responseString === "string"){
var responseParsed = JSON.parse(responseString);
if (Api.debug) {
console.log("RESPONSE(Json)", responseParsed);
}
return jsonConsumer(responseParsed);
}
} catch(error) {
// text is not a valid json so we will consume as text
}
if (Api.debug) {
console.log("RESPONSE(Txt)", responseString);
}
return txtConsumer(responseString);
})();
}
then it become more easy to tune the rest handler:
class Api {
static debug = true;
static contribute(entryToAdd) {
return new Promise((resolve, reject) => {
fetch('/api/contributions',
{ method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(entryToAdd) })
.catch(reject);
.then(response => Api.consumeResponseBodyAs(response,
(json) => {
if (!response.ok) {
// valid json: reject will use error.details or error.message or http status
reject((json && json.details) || (json && json.message) || response.status);
} else {
resolve(json);
}
},
(txt) => reject(txt)// not json: reject with text payload
)
);
});
}
let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
this.form.complexForm.patchValue(cloneObj);
If you don't want manually set each field.
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>
, though the semantics of sets and lists are a bit different.
@Jason S: your "fmod" variant will not work on a standards-compliant implementation. The C standard is explicit and clear (7.12.10.1, "the fmod functions"):
if y is nonzero, the result has the same sign as x
thus,
fmod(atan2(y,x)/M_PI*180,360)
is actually just a verbose rewriting of:
atan2(y,x)/M_PI*180
Your third suggestion, however, is spot on.
If you're connecting to a named instance and UDP is not available when connecting to it, then you may need to specify the protocol as well.
Example: tcp:192.168.1.21\SQL2K5,1443
I suggest you run OpenCV sanity check
Its a serie of small executables located in the bin directory of opencv.
It will check if your camera is ok
From managed code you have access to instances of the Thread
type for each managed thread. Thread
encapsulates the concept of an OS thread and as of the current CLR there's a one-to-one correspondance with managed threads and OS threads. However, this is an implementation detail, that may change in the future.
The ID displayed by Visual Studio is actually the OS thread ID. This is not the same as the managed thread ID as suggested by several replies.
The Thread
type does include a private IntPtr member field called DONT_USE_InternalThread
, which points to the underlying OS structure. However, as this is really an implementation detail it is not advisable to pursue this IMO. And the name sort of indicates that you shouldn't rely on this.
I tend to look at it from the inverse perspective which may be what you intended:
What characters do I want to allow?
This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.
For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:
"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Upgrading ipykernel
, notebook
and then downgrading tornado
to 4.2.0 solved the issue for me.
My current package versions related to jupyter:
jupyter==1.0.0
jupyter-client==5.2.2
jupyter-console==6.1.0
jupyter-core==4.4.0
jupyterlab==2.2.5
jupyterlab-server==1.2.0
ipykernel==5.3.4
notebook==5.2.2
tornado==4.2
pyparsing==2.4.2
ipython==5.5.0
ipython-genutils==0.2.0
prompt-toolkit==1.0.15
For sake of simplicity, maybe you should consider using the Requests library.
An example with json response content would be something like:
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
If you look for further information, in the Quickstart section, they have lots of working examples.
EDIT:
For your specific curl translation:
import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)
I'm against using when others
so I would use (returning an "boolean integer" due to SQL not suppporting booleans)
create or replace function is_number(param in varchar2) return integer
is
ret number;
begin
ret := to_number(param);
return 1; --true
exception
when invalid_number then return 0;
end;
In the SQL call you would use something like
select case when ( is_number(myTable.id)=1 and (myTable.id >'0') )
then 'Is a number greater than 0'
else 'it is not a number or is not greater than 0'
end as valuetype
from table myTable
In some websites, XMLHttpRequest
may send you something like <script src="#"></srcipt>
. In that case, try using a HTML document like the script under:
<html>
<body>
<iframe src="website.com"></iframe>
<script src="your_JS"></script>
</body>
</html>
Now you can use JS to get some text out of the HTML, such as getElementbyId
.
But this may not work for some websites with cross-domain blocking.
What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.
That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).
In MySQL, a user is identified by both a username ("test2") and a host ("localhost").
The error message identifies the user ("test2") and the host ("localhost") values...
'test2'@'localhost'
We can check to see if the user exists, using this query from a client we can connect from:
SELECT user, host FROM mysql.user
We're looking for a row that has "test2" for user, and "localhost" for host.
user host
------- -----------
test2 127.0.0.1 cleanup
test2 ::1
test2 localhost
If that row doesn't exist, then the host may be set to wildcard value of %
, to match any other host that isn't a match.
If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root
SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')
We can also verify that the user has privileges on objects in the database.
GRANT SELECT ON jobs.* TO 'test2'@'localhost'
EDIT
If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES
statement, executed by a privileged user.
Had the same issue, but my code must work on both PHP 5 & PHP 7..
Here is my piece of code, which solved this.. Input a date in dmY format with one of delimiters "/ . -"
<?php
function DateToEN($date){
if ($date!=""){
list($d, $m, $y) = function_exists("split") ? split("[/.-]", $date) : preg_split("/[\/\.\-]+/", $date);
return $y."-".$m."-".$d;
}else{
return false;
}
}
?>
If you are planning to use these components along with your proprietary code then please refer below information.
Mongodb:
Mongoose:
POSIX 7
First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html
That contains a link to a time.h
, which as a header should be where structs are defined:
The header shall declare the timespec structure, which shall > include at least the following members:
time_t tv_sec Seconds. long tv_nsec Nanoseconds.
man 2 nanosleep
Pseudo-official glibc docs which you should always check for syscalls:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
I was having problems with a new install of VS with an x64 project - for Visual Studio 2013, Visual Studio 2015 and Visual Studio 2017:
Tools
-> Options
-> Projects and Solutions
-> Web Projects
-> Check "Use the 64 bit version of IIS Express for web sites and projects"
I use objects JSON style for dumb structs (no member functions).
Since version 4.14 of Linux kernel, vfs_read
and vfs_write
functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:
# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);
Also, filp_open
no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs
).
The cleanest way, as far as I know:
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
By psql --help
, when you didn't set options for database name (without -d
option) it would be your username, if you didn't do -U
, the database username would be your username too, etc.
But by initdb
(to create the first database) command it doesn't have your username as any database name. It has a database named postgres
. The first database is always created by the initdb command when the data storage area is initialized. This database is called postgres.
So if you don't have another database named your username, you need to do psql -d postgres
for psql command to work. And it seems it gives -d
option by default, psql postgres
also works.
If you have created another database names the same to your username, (it should be done with createdb
) then you may command psql
only. And it seems the first database user name sets as your machine username by brew.
psql -d <first database name> -U <first database user name>
or,
psql -d postgres -U <your machine username>
psql -d postgres
would work by default.
Having a default structure of folders generated by Vue CLI such as src/assets
you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png">
as well (works automatically without any changes on deployment too).
I use the following format and works well.
robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
to copy everything you can replace filename.txt
with *.*
and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
_
has 3 main conventional uses in Python:
To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the gettext documentation for example), as in code like
raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name:
To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
label, has_label, _ = text.partition(':')
As part of a function definition (using either def
or lambda
), where
the signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like:
def callback(_):
return True
[For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]
This use case can conflict with the translation lookup use case, so it is necessary to avoid using _
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __
, as their throwaway variable for exactly this reason).
Linters often recognize this use case. For example year, month, day = date()
will raise a lint warning if day
is not used later in the code. The fix, if day
is truly not needed, is to write year, month, _ = date()
. Same with lambda functions, lambda arg: 1.0
creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0
. An unused variable is often hiding a bug/typo (e.g. set day
but use dya
in the next line).
with performance in mind, you'd better use typeof with a typical hardware, if you create a script with a loop of 10 million iterations the instruction: typeof str == 'string' will take 9ms while 'string' instanceof String will take 19ms
Just adding some extra sorting if needed
=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
I got this from YouTube Setting up Python Visual Studio Code... Venv
OK, the video really didn't help me all that much, but... the first comment under (by the person who posted the video) makes a lot of sense and is pure gold.
Basically, open up Visual Studio Code' built-in Terminal. Then source <your path>/activate.sh
, the usual way you choose a venv from the command line. I have a predefined Bash function to find & launch the right script file and that worked just fine.
Quoting that YouTube comment directly (all credit to aneuris ap):
(you really only need steps 5-7)
1. Open your command line/terminal and type `pip virtualenv`.
2. Create a folder in which the virtualenv will be placed in.
3. 'cd' to the script folder in the virtualenv and run activate.bat (CMD).
4. Deactivate to turn of the virtualenv (CMD).
5. Open the project in Visual Studio Code and use its built-in terminal to 'cd' to the script folder in you virtualenv.
6. Type source activates (in Visual Studio Code I use the Git terminal).
7. Deactivate to turn off the virtualenv.
As you may notice, he's talking about activate.bat
. So, if it works for me on a Mac, and it works on Windows too, chances are it's pretty robust and portable.
As we were already using jQuery for a graphical eye-candy feature we ended up using this. A code like
$(document).ready(function() {
// any code goes here
init();
});
did everything we wanted and cares about browser incompatibilities at its own.
Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)
Controller
@event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group
View
<% @event_attendees.each do |event_attendee| %>
<%= event_attendee['group'].first.user.first_name %>
<% end %>
.fa-circle{_x000D_
color: tomato;_x000D_
}_x000D_
_x000D_
div{_x000D_
font-size: 100px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<div><i class="fa fa-circle" aria-hidden="true"></i></div>
_x000D_
Just wanted to mention another solution which answers the question of "Easier way to create circle div than using an image?" which is to use FontAwesome.
You import the fontawesome css file or from the CDN here
and then you just:
<div><i class="fa fa-circle" aria-hidden="true"></i></div>
and you can give it any color you want any font size.
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
A cleaner way to handle file open/close and avoid memory leaks:
Prep:
import numpy as np
import h5py
data_to_write = np.random.random(size=(100,20)) # or some such
Write:
with h5py.File('name-of-file.h5', 'w') as hf:
hf.create_dataset("name-of-dataset", data=data_to_write)
Read:
with h5py.File('name-of-file.h5', 'r') as hf:
data = hf['name-of-dataset'][:]
You might want to do this.
input[type=checkbox] {
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
I needed a fat static lib for JsonKit so created a static lib project in Xcode and then ran this bash script in the project directory. So long as you've configured the xcode project with "Build active configuration only" turned off, you should get all architectures in one lib.
#!/bin/bash
xcodebuild -sdk iphoneos
xcodebuild -sdk iphonesimulator
lipo -create -output libJsonKit.a build/Release-iphoneos/libJsonKit.a build/Release-iphonesimulator/libJsonKit.a
Deleting "Derived Data" worked for me.
In Xcode go to File > Workspace Settings > Click the arrow next to the Derived Data file path > move the "Derived Data" folder to the trash.
Add the $http, $scope services in the controller fucntion, sometimes if they are missing these errors occur.
Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.
$(document).on('change', 'input[type="file"]', function (event) { _x000D_
var filename = $(this).val();_x000D_
if (filename == undefined || filename == ""){_x000D_
$(this).next('.custom-file-label').html('No file chosen');_x000D_
}_x000D_
else _x000D_
{ $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
});
_x000D_
input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
outline:none!important;_x000D_
border-color: transparent;_x000D_
box-shadow: none!important;_x000D_
}_x000D_
.custom-file,_x000D_
.custom-file-label,_x000D_
.custom-file-input {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container py-5">_x000D_
<div class="input-group mb-3">_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text">Upload</span>_x000D_
</div>_x000D_
<div class="custom-file">_x000D_
<input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I am going to assume you were having the same issue I was. Even though you specify larger sizes for the TextBox and mark it as important, the box would not get larger. That is likely because in your site.css file the MaxWidth is being set to 280px.
Add a style attribute to your input to remove the MaxWidth like this:
<input type="text" style="max-width:none !important" class="input-medium">
The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.
Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman
) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run
serman install <path_to_config_file>
will install the service. stdout
and stderr
are all logged. For more info, take a look at the project website.
A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env>
and <persistent_env>
below.
<service>
<id>hello</id>
<name>hello</name>
<description>This service runs the hello application</description>
<executable>node.exe</executable>
<!--
{{dir}} will be expanded to the containing directory of your
config file, which is normally where your executable locates
-->
<arguments>"{{dir}}\hello.js"</arguments>
<logmode>rotate</logmode>
<!-- OPTIONAL FEATURE:
NODE_ENV=production will be an environment variable
available to your application, but not visible outside
of your application
-->
<env name="NODE_ENV" value="production"/>
<!-- OPTIONAL FEATURE:
FOO_SERVICE_PORT=8989 will be persisted as an environment
variable machine-wide.
-->
<persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>
This will work, and if you need where statement you can add it as parameter.
class GenericDAOWithJPA<T, ID extends Serializable> {
.......
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
While working with different versions of Python on Windows,
I am using this method to switch between versions.
I think it is better than messing with shebangs and virtualenvs
1) install python versions you desire
2) go to Environment Variables > PATH
(i assume that paths of python versions are already added to Env.Vars.>PATH)
3) suppress the paths of all python versions you dont want to use
(dont delete the paths, just add a suffix like "_sup")
4) call python from terminal
(so Windows will skip the wrong paths you changed, and will find the python.exe at the path you did not suppressed, and will use this version after on)
5) switch between versions by playing with suffixes
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
You can pass the DBNull.Value
into the parameter's .Value property:
SqlParameters[0] = new SqlParameter("LedgerID", SqlDbType.BigInt );
SqlParameters[0].Value = DBNull.Value;
Just adjust for your two DateTime parameters, obviously - just showing how to use the DBNull.Value
property value here.
Marc
alternatively you can perform a fast export without using Office dll, as Excel can parse csv files without problems.
Doing something like this (for less than 65.536 rows with titles):
Try
If (p_oGrid.RowCount = 0) Then
MsgBox("No data", MsgBoxStyle.Information, "App")
Exit Sub
End If
Cursor.Current = Cursors.WaitCursor
Dim sText As New System.Text.StringBuilder
Dim sTmp As String
Dim aVisibleData As New List(Of String)
For iAuxRow As Integer = 0 To p_oGrid.Columns.Count - 1
If p_oGrid.Columns(iAuxRow).Visible Then
aVisibleData.Add(p_oGrid.Columns(iAuxRow).Name)
sText.Append(p_oGrid.Columns(iAuxRow).HeaderText.ToUpper)
sText.Append(";")
End If
Next
sText.AppendLine()
For iAuxRow As Integer = 0 To p_oGrid.RowCount - 1
Dim oRow As DataGridViewRow = p_oGrid.Rows(iAuxRow)
For Each sCol As String In aVisibleData
Dim sVal As String
sVal = oRow.Cells(sCol).Value.ToString()
sText.Append(sVal.Replace(";", ",").Replace(vbCrLf, " ; "))
sText.Append(";")
Next
sText.AppendLine()
Next
sTmp = IO.Path.GetTempFileName & ".csv"
IO.File.WriteAllText(sTmp, sText.ToString, System.Text.Encoding.UTF8)
sText = Nothing
Process.Start(sTmp)
Catch ex As Exception
process_error(ex)
Finally
Cursor.Current = Cursors.Default
End Try
typedef union{
float a;
char b[4];
} my_union_t;
You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.
Trying to do the same thing. If you want it to be aligned on the right side then set the value of right
to 0
. In case you need some padding from the right, set the value to the size of the padding you need.
Example:
.test {
position: fixed;
right: 20px; /* Padding from the right side */
}
You could also use the CountDownLatch
object like explained here.
The problem is not in your dependencies.... you should open detail error on this path
Please refer to D:\Masters\thesis related papers and tools\junitcategorizer\junitcategorizer.instrument\target\surefire-reports for the individual test results.
the detail error's in there, maybe your service class or serviceImpl class or something missing like @anotation or else... i got error same with you,...u should try
If you don't mind using numpy, you can use numpy.random.choice.
For example:
import numpy
items = [["item1", 0.2], ["item2", 0.3], ["item3", 0.45], ["item4", 0.05]
elems = [i[0] for i in items]
probs = [i[1] for i in items]
trials = 1000
results = [0] * len(items)
for i in range(trials):
res = numpy.random.choice(items, p=probs) #This is where the item is selected!
results[items.index(res)] += 1
results = [r / float(trials) for r in results]
print "item\texpected\tactual"
for i in range(len(probs)):
print "%s\t%0.4f\t%0.4f" % (items[i], probs[i], results[i])
If you know how many selections you need to make in advance, you can do it without a loop like this:
numpy.random.choice(items, trials, p=probs)
The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.
I recommend you follow NuGet's instructions but just to recap what I did:
packages
folder is not committed to TFS. If it is, get it out of there..sln
file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this)..nuget
folder. You can use Windows Explorer to name it .nuget.
for it to successfully save as .nuget
(it automatically removes the last period) but directly trying to name it .nuget
may not work (you may get an error or it may change the name, depending on your version of Windows).
Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nugetNuGet.config
file and add the following contents and save it:NuGet.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
.sln
's folder and create a new text file and name it .tfignore
(if using Windows Explorer, use the same trick as above and name it .tfignore.
).tfignore:
# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's
# not in the same folder as .tfignore.
packages
# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
.tfignore
file and .nuget
folder to all of my various solutions and committed them and I no longer have the packages
folder trying to sneak into my source control repo!While not mine, I have found this .tfignore
template by sirkirby to be handy. The example in my answer covers the Nuget packages
folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.
In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h)
. (explanation: 9AM - 24h/day = -15h)
You can also use updated >= startOfDay(-900m)
. where 900m = 15h*60m
Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching
This Perl one-liner shows how closely Perl is related to awk:
perl -lane 'print $F[3]' text.txt
However, the @F
autosplit array starts at index $F[0]
while awk fields start with $1
The simplest way is EF, Reverse Engineer. http://msdn.microsoft.com/en-US/data/jj593170
# First use prune --dry-run to filter+delete the local branches
git remote prune origin --dry-run \
| grep origin/ \
| sed 's,.*origin/,,g' \
| xargs git branch -D
# Second delete the remote refs without --dry-run
git remote prune origin
Prune the same branches from local- and remote-refs(in my example from origin
).
For those using the context menu api
, the docs are not immediately clear on how to obtain tab information.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log(info);
return console.log(tab);
});
Using Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
Explanation
We convert the int[] data
array to boxed Integer Stream. Then we collect by groupingBy
on the element and use a secondary counting collector for counting after the groupBy
.
Finally we sort the map of element ->
count based on count again by using a stream and lambda comparator.
you can use this command for particular branch clone :
git clone <url of repo> -b <branch name to be cloned>
Eg: git clone https://www.github.com/Repo/FirstRepo -b master
With \
you escape special characters
Escapes special characters to literal and literal characters to special.
E.g:
/\(s\)/
matches '(s)' while/(\s)/
matches any whitespace and captures the match.
Source: http://www.javascriptkit.com/javatutors/redev2.shtml
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
A quote from the documentation:
Using multiple commands and conditional processing symbols
You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.
For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.
You can use the special characters listed in the following table to pass multiple commands.
& [...]
command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.
&& [...]
command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.
|| [...]
command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).
( ) [...]
(command1 & command2)
Use to group or nest multiple commands.
; or ,
command1 parameter1;parameter2
Use to separate command parameters.
Remember to use the server's local name, not the domain name, when resolving the name
IIS AppPool\DefaultAppPool
(just a reminder because this tripped me up for a bit):
Try setting the system default encoding as utf-8
at the start of the script, so that all strings are encoded using that.
Example -
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
The above should set the default encoding as utf-8
.
Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.
SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
AND CompletedDate in
(Select Max(CompletedDate) from HR_EmployeeTrainings B
where B.TrainingID = ET.TrainingID)
If you also want to match by AntiRecID you should include that in the subselect as well.
Figure 1, lifted from RFC6750:
+--------+ +---------------+
| |--(A)- Authorization Request ->| Resource |
| | | Owner |
| |<-(B)-- Authorization Grant ---| |
| | +---------------+
| |
| | +---------------+
| |--(C)-- Authorization Grant -->| Authorization |
| Client | | Server |
| |<-(D)----- Access Token -------| |
| | +---------------+
| |
| | +---------------+
| |--(E)----- Access Token ------>| Resource |
| | | Server |
| |<-(F)--- Protected Resource ---| |
+--------+ +---------------+
The only way it worked for me for arduino nano 33 iot is via pressing the reset button on the board continuously many time then press uoplad!
You can pass it like this
let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});
this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
Here's how you might implement a counter:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
exit 0
elif [[ "$counter" -gt 20 ]]; then
echo "Counter: $counter times reached; Exiting loop!"
exit 1
else
counter=$((counter+1))
echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Some Explanations:
counter=$((counter+1))
- this is how you can increment a counter. The $
for counter
is optional inside the double parentheses in this case.elif [[ "$counter" -gt 20 ]]; then
- this checks whether $counter
is not greater than 20
. If so, it outputs the appropriate message and breaks out of your while loop.Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
This is the code you need to set the summary to the chosen value. It also sets the values on startup and respects the default values, not only on change. Just change "R.layout.prefs" to your xml-file and extend the setSummary-method to your needs. It actually is only handling ListPreferences, but it is easy to customize to respect other Preferences.
package de.koem.timetunnel;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
public class Prefs
extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addPreferencesFromResource(R.layout.prefs);
this.initSummaries(this.getPreferenceScreen());
this.getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
/**
* Set the summaries of all preferences
*/
private void initSummaries(PreferenceGroup pg) {
for (int i = 0; i < pg.getPreferenceCount(); ++i) {
Preference p = pg.getPreference(i);
if (p instanceof PreferenceGroup)
this.initSummaries((PreferenceGroup) p); // recursion
else
this.setSummary(p);
}
}
/**
* Set the summaries of the given preference
*/
private void setSummary(Preference pref) {
// react on type or key
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry());
}
}
/**
* used to change the summary of a preference
*/
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
Preference pref = findPreference(key);
this.setSummary(pref);
}
// private static final String LOGTAG = "Prefs";
}
koem
A StreamReader is for text, not plain bytes. Don't use a StreamReader, and instead read directly from the underlying stream.
Just for convenience, very simple.
def hexlify_byteString(byteString, delim="%"):
''' very simple way to hexlify a bytestring using delimiters '''
retval = ""
for intval in byteString:
retval += ( '0123456789ABCDEF'[int(intval / 16)])
retval += ( '0123456789ABCDEF'[int(intval % 16)])
retval += delim
return( retval[:-1])
hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'
Consider collection of balls in a bucket all in black color. Your Job is to color those balls as follows and use it for appropriate game,
For Tennis - Yellow, Red. For Cricket - White
Now bucket has balls in three colors Yellow, Red and White. And that now you did the coloring Only you know which color is for which game.
Coloring the balls - Hashing. Choosing the ball for game - Equals.
If you did the coloring and some one chooses the ball for either cricket or tennis they wont mind the color!!!
Let's assume we're working with the following representation of data (two columns, k
and v
, where k
contains three entries, two unique:
+---+---+
| k| v|
+---+---+
|foo| 1|
|bar| 2|
|foo| 3|
+---+---+
With a Pandas dataframe:
import pandas as pd
p_df = pd.DataFrame([("foo", 1), ("bar", 2), ("foo", 3)], columns=("k", "v"))
p_df['k'].unique()
This returns an ndarray
, i.e. array(['foo', 'bar'], dtype=object)
You asked for a "pyspark dataframe alternative for pandas df['col'].unique()". Now, given the following Spark dataframe:
s_df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("foo", 3)], ('k', 'v'))
If you want the same result from Spark, i.e. an ndarray
, use toPandas()
:
s_df.toPandas()['k'].unique()
Alternatively, if you don't need an ndarray
specifically and just want a list of the unique values of column k
:
s_df.select('k').distinct().rdd.map(lambda r: r[0]).collect()
Finally, you can also use a list comprehension as follows:
[i.k for i in s_df.select('k').distinct().collect()]
Short answer: yes.
Long answer:
In MySQL, the InnoDB storage engine always creates a primary key if you didn't specify it explicitly, thus making an extra column you don't have access to.
Note that a primary key can be composite.
If you have a many-to-many link table, you create the primary key on all fields involved in the link. Thus you ensure that you don't have two or more records describing one link.
Besides the logical consistency issues, most RDBMS engines will benefit from including these fields in a unique index.
And since any primary key involves creating a unique index, you should declare it and get both logical consistency and performance.
See this article in my blog for why you should always create a unique index on unique data:
P.S. There are some very, very special cases where you don't need a primary key.
Mostly they include log tables which don't have any indexes for performance reasons.
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
Swift: xcode 6.1
let font:UIFont? = UIFont(name: "Arial", size: 12.0)
let attrString = NSAttributedString(
string: titleData,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName))
I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg
Try this instead:
<img src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />
UPDATE:
I don't know what your $PROJECTHOME
is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.
Then in your HTML you can simply reference the image within the images folder relative to the site, like so:
<img src="images/66.jpg" width="400" height="400" />
Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):
<img src="/images/66.jpg" width="400" height="400" />
For Size : fa-lg, fa-2x, fa-3x, fa-4x, fa-5x.
For Color : <i class="fa fa-link fa-lg" aria-hidden="true"style="color:indianred"></i>
For Shadow : .fa-linkedin-square{text-shadow: 3px 6px #272634;}
One of Androids powerful feature is the AsyncTask class.
To work with it, you have to first extend it and override doInBackground
(...).
doInBackground
automatically executes on a worker thread, and you can add some
listeners on the UI Thread to get notified about status update, those functions are
called: onPreExecute()
, onPostExecute()
and onProgressUpdate()
You can find a example here.
Refer to below post for other alternatives:
Following the instructions here Codesign gdb on macOS seemed to resolve this issue, for me, on macOS High Sierra (10.13.3).
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;
Close the cursor, if it is empty then deallocate it:
IF CURSOR_STATUS('global','myCursor') >= -1
BEGIN
IF CURSOR_STATUS('global','myCursor') > -1
BEGIN
CLOSE myCursor
END
DEALLOCATE myCursor
END
I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.
A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.
If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.
TIMESTAMP LIMITATION
The TIMESTAMP
type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME
type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW()
.
Actually this will give you repeated indices np.random.random_integers(0, len(df), N)
where N
is a large number.
Launch the installer, but don't press the Install > button. Then
cd "%AppData%\..\LocalLow\Sun\Java"
and find your MSI file in one of sub-directories (e.g., jre1.7.0_25
).
Note that Data1.cab
from that sub-directory will be required as well.
From the Python PEP 8 -- Style Guide for Python Code:
Descriptive: Naming Styles
The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
_single_leading_underscore
: weak "internal use" indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside class FooBar,__boo
becomes_FooBar__boo
; see below).
__double_leading_and_trailing_underscore__
: "magic" objects or attributes that live in user-controlled namespaces. E.g.__init__
,__import__
or__file__
. Never invent such names; only use them as documented.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
The current PHP Nightrain (4.0.0) is written in Python and it uses the wxPython libraries. So far wxPython has been working well to get PHP Nightrain where it is today but in order to push PHP Nightrain to its next level, we are introducing a sibling of PHP Nightrain, the PHPWebkit!
It's an update to PHP Nightrain.
You could do this:
echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";
How inheritance can be dangerous ?
Lets take an example
public class X{
public void do(){
}
}
Public Class Y extends X{
public void work(){
do();
}
}
1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature
public int work(){
}
Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.
How does composition solves this issue?
Lets see by revising the same example
public class X{
public void do(){
}
}
Public Class Y{
X x = new X();
public void work(){
x.do();
}
}
Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class. Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.
2) Second very good advantage of composition in that It provides method calling flexibility, for example :
class X implements R
{}
class Y implements R
{}
public class Test{
R r;
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance
3) Another great advantage : Unit testing
public class X {
public void do(){
}
}
Public Class Y {
X x = new X();
public void work(){
x.do();
}
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.
4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.
Lets take an example to understand this :
Public class Transaction {
Banking b;
public static void main(String a[])
{
b = new Deposit();
if(b.deposit()){
b = new Credit();
c.credit();
}
}
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time
composition is also know as HAS-A relation and inheritance is also known as IS-A relation
So make it a habit of always preferring composition over inheritance for various above reasons.
You can use SET ECHO ON
in the beginning of your script to achieve that, however, you have to specify your script using @
instead of <
(also had to add EXIT
at the end):
test.sql
SET ECHO ON
SELECT COUNT(1) FROM dual;
SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);
EXIT
terminal
sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log
test.log
SQL> SQL> SELECT COUNT(1) FROM dual; COUNT(1) ---------- 1 SQL> SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual); COUNT(1) ---------- 2 SQL> SQL> EXIT
Very useful thing have applied today in my project. One div had to be aligned right, with no floating applied.
Applying code made my goal achieved:
.div {
margin-right: 0px;
margin-left: auto;
}
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
The paint()
method supports painting via a Graphics object.
The repaint()
method is used to cause paint()
to be invoked by the AWT painting thread.
The list is compiler specific. But here are the values supported in Eclipse:
- allDeprecation deprecation even inside deprecated code
- allJavadoc invalid or missing javadoc
- assertIdentifier occurrence of assert used as identifier
- boxing autoboxing conversion
- charConcat when a char array is used in a string concatenation without being converted explicitly to a string
- conditionAssign possible accidental boolean assignment
- constructorName method with constructor name
- dep-ann missing @Deprecated annotation
- deprecation usage of deprecated type or member outside deprecated code
- discouraged use of types matching a discouraged access rule
- emptyBlock undocumented empty block
- enumSwitch, incomplete-switch incomplete enum switch
- fallthrough possible fall-through case
- fieldHiding field hiding another variable
- finalBound type parameter with final bound
- finally finally block not completing normally
- forbidden use of types matching a forbidden access rule
- hiding macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
- indirectStatic indirect reference to static member
- intfAnnotation annotation type used as super interface
- intfNonInherited interface non-inherited method compatibility
- javadoc invalid javadoc
- localHiding local variable hiding another variable
- maskedCatchBlocks hidden catch block
- nls non-nls string literals (lacking of tags //$NON-NLS-)
- noEffectAssign assignment with no effect
- null potential missing or redundant null check
- nullDereference missing null check
- over-ann missing @Override annotation
- paramAssign assignment to a parameter
- pkgDefaultMethod attempt to override package-default method
- raw usage a of raw type (instead of a parametrized type)
- semicolon unnecessary semicolon or empty statement
- serial missing serialVersionUID
- specialParamHiding constructor or setter parameter hiding another field
- static-access macro for indirectStatic and staticReceiver
- staticReceiver if a non static receiver is used to get a static field or call a static method
- super overriding a method without making a super invocation
- suppress enable @SuppressWarnings
- syntheticAccess, synthetic-access when performing synthetic access for innerclass
- tasks enable support for tasks tags in source code
- typeHiding type parameter hiding another type
- unchecked unchecked type operation
- unnecessaryElse unnecessary else clause
- unqualified-field-access, unqualifiedField unqualified reference to field
- unused macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
- unusedArgument unused method argument
- unusedImport unused import reference
- unusedLabel unused label
- unusedLocal unused local variable
- unusedPrivate unused private member declaration
- unusedThrown unused declared thrown exception
- uselessTypeCheck unnecessary cast/instanceof operation
- varargsCast varargs argument need explicit cast
- warningToken unhandled warning token in @SuppressWarnings
Sun JDK (1.6) has a shorter list of supported warnings:
- deprecation Check for use of depreciated items.
- unchecked Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
- serial Warn about missing serialVersionUID definitions on serializable classes.
- finally Warn about finally clauses that cannot complete normally.
- fallthrough Check switch blocks for fall-through cases and provide a warning message for any that are found.
- path Check for a nonexistent path in environment paths (such as classpath).
The latest available javac (1.6.0_13) for mac have the following supported warnings
- all
- cast
- deprecation
- divzero
- empty
- unchecked
- fallthrough
- path
- serial
- finally
- overrides
This is an old post, but thanks to this post I have found this:
\! echo 'some text';
Tested with MySQL 8 and working correctly. Cool right? :)
Instead of images i choose background option:
HTML:
<div class="class1">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class2">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class3">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
CSS:
.class1 {
background: url("Some.png") no-repeat top center;
text-align: center;
}
.class2 {
background: url("Some2.png") no-repeat top center;
text-align: center;
}
.class3 {
background: url("Some3.png") no-repeat top center;
text-align: center;
}
In powershell :
$this_script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
$parent_folder = Split-Path $this_script_path -Leaf
If you have Java 7 so include the below following snippet within your app-level build.gradle
:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
In your app's build.gradle
add the following:
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
Enforces Gradle to only compile the version number you state for all dependencies, no matter which version number the dependencies have stated.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
adb tcpip 5555
Weird, but this only works for me if I have the USB cable connected, then I can unplug the usb and go for it with everything else adb.
and the same when returning to usb,
adb usb
will only work if usb is connected.
It doesn't matter if I issue the
setprop service.adb.tcp.port 5555
or
setprop service.adb.tcp.port -1
then stop & start adbd, I still need the usb cable in or it doesn't work.
So, if my ADB over usb wasn't working, I bet I wouldn't be able to enable ADB over WiFi either.
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
The CloseReason
enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...
You can do different actions, according to the reason, like:
void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
// Prompt user to save his data
if(e.CloseReason == CloseReason.WindowsShutDown)
// Autosave and clear up ressources
}
But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a CloseReason.UserClosing
reason.
You are doing two mistakes here.
1. calling getMaxValue(),getMinValue()
methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue()
methods.
So try this code
for (int i = 0 ; i < array.length; i++ )
{
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
// get biggest number
int maxValue = getMaxValue(array);
System.out.println(maxValue );
// get smallest number
int minValue = getMinValue(array);
System.out.println(minValue);
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
Agreed with Richard Garside's short answer, but instead of using prop()
in $(this).prop("checked")
you can use native JS checked
property of checkbox like,
$("#checkAll").change(function () {_x000D_
$("input:checkbox").prop('checked', this.checked);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
_x000D_
<fieldset>_x000D_
<legend>Loads of checkboxes</legend>_x000D_
<p><label><input type="checkbox" /> Option 1</label></p>_x000D_
<p><label><input type="checkbox" /> Option 2</label></p>_x000D_
<p><label><input type="checkbox" /> Option 3</label></p>_x000D_
<p><label><input type="checkbox" /> Option 4</label></p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith
of class String
without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.
cd -
It's the command-line equivalent of the back button (takes you to the previous directory you were in).
I don't think that they really are random, but my guess is those are some hashes.
Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:
Guid.NewGuid().ToString("n");
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
May also be called, "rename" by tortoise, but svn move, is the command in the barebones svn client.
I achieved the goal where I have multiple images to insert in the DB as
INSERT INTO [dbo].[User]
([Name]
,[Image1]
,[Age]
,[Image2]
,[GroupId]
,[GroupName])
VALUES
('Umar'
, (SELECT BulkColumn
FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
,26
,(SELECT BulkColumn
FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
,'Group123'
,'GroupABC')
declare @n int = 7,
@m int = 3;
select
case
when @n = 1 then
'SOMETEXT'
else
case
when @m = 1 then
'SOMEOTHERTEXT'
when @m = 2 then
'SOMEOTHERTEXTGOESHERE'
end
end as col1
-- n=1 => returns SOMETEXT regardless of @m
-- n=2 and m=1 => returns SOMEOTHERTEXT
-- n=2 and m=2 => returns SOMEOTHERTEXTGOESHERE
-- n=2 and m>2 => returns null (no else defined for inner case)
e.printStackTrace equivalent in python
In Java, this does the following (docs):
public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream...
This is used like this:
try
{
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}
In Java, the Standard Error stream is unbuffered so that output arrives immediately.
import traceback
import sys
try: # code that may raise an error
pass
except IOError as e: # exception handling
# in Python 2, stderr is also unbuffered
print >> sys.stderr, traceback.format_exc()
# in Python 2, you can also from __future__ import print_function
print(traceback.format_exc(), file=sys.stderr)
# or as the top answer here demonstrates, use:
traceback.print_exc()
# which also uses stderr.
In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:
print(traceback.format_exception(None, # <- type(e) by docs, but ignored
e, e.__traceback__),
file=sys.stderr, flush=True)
Conclusion:
In Python 3, therefore, traceback.print_exc()
, although it uses sys.stderr
by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print
with flush=True
.
I've faced with the same situation. And it was solved by adding codes before you clear your collection.
mRecyclerView.getRecycledViewPool().clear();
It works:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from
GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES,
to draw lines,
GL_POINTS
(if you need to draw only vertices), or
GL_TRIANGLE_STRIP
, GL_TRIANGLE_FAN
, and GL_TRIANGLES
to draw filled triangles
as first argument to your
glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)
or
glDrawArrays(GLenum mode, GLint first, GLsizei count)
calls.
The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.
Passing and returning an integer
The C++ code for a function which takes an integer and adds one to the returned value,
extern "C" int add_one(int i)
{
return i+1;
}
Saved as file test.cpp
, note the required extern "C" (this can be removed for C code).
This is compiled using g++, with arguments similar to Chinmay Kanchi answer,
g++ -shared -o testlib.so -fPIC test.cpp
The Python code uses load_library
from the numpy.ctypeslib
assuming the path to the shared library in the same directory as the Python script,
import numpy.ctypeslib as ctl
import ctypes
libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)
py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)
This prints 6 as expected.
Passing and printing an array
You can also pass arrays as follows, for a C code to print the element of an array,
extern "C" void print_array(double* array, int N)
{
for (int i=0; i<N; i++)
cout << i << " " << array[i] << endl;
}
which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,
import numpy as np
py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64,
flags='aligned, c_contiguous'),
ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)
where we specify the array, the first argument to print_array
, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,
1.4
2.6
3.0
try this
$('.modal').on('hide.bs.modal', function () {
if ($(this).is(':visible')) {
console.log("show modal")
$('.modal-backdrop').show();
}else{
console.log("hidden modal");
$('.modal-backdrop').remove();
}
})
<xmp>
tag:<xmp>
<div>
<input placeholder='write something' value='test'>
</div>
</xmp>
_x000D_
It is very sad this tag has been deprecated, but it does still works on browsers, it it is a bad-ass tag. no need to escape anything inside it. What a joy!
<textarea>
tag:<textarea readonly rows="4" style="background:none; border:none; resize:none; outline:none; width:100%;">
<div>
<input placeholder='write something' value='test'>
</div>
</textarea>
_x000D_
I would just like to add another useful advantage of using %timeit to answer by mu ? that:
PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.
Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().
display(dataframe)
display() supports proper alignment also.
However if you want to make the dataset more beautiful you can check pd.option_context()
. It has lot of options to clearly show the dataframe.
Note - I am using Jupyter Notebooks.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works. If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.
Mac 11.1 appears to be interfering with Tomcat.
As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.
Spent several days trying to figure this out, but cannot resolve.
Suggestions very welcome! :)
In my case, my app had multiple layers of modules, so the module I was trying to import had to be added into the module parent that actually used it pages.module.ts
, instead of app.module.ts
.
As suggested here you can also inject the HttpServletRequest
as a method param, e.g.:
public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
...
}
I can suggest two options.
Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.
void method() {
long endTimeMillis = System.currentTimeMillis() + 10000;
while (true) {
// method logic
if (System.currentTimeMillis() > endTimeMillis) {
// do some clean-up
return;
}
}
}
Run the method in a thread, and have the caller count to 10 seconds.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
method();
}
});
thread.start();
long endTimeMillis = System.currentTimeMillis() + 10000;
while (thread.isAlive()) {
if (System.currentTimeMillis() > endTimeMillis) {
// set an error flag
break;
}
try {
Thread.sleep(500);
}
catch (InterruptedException t) {}
}
The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.
You're almost there. Simply use:
//form[@id='myform']//input[@type='submit']
The //
shortcut can also be used inside an expression.
I was making mistakes like this.
@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&subset=cyrillic,cyrillic-ext,latin-ext";
@import "https://use.fontawesome.com/releases/v5.3.1/css/all.css";
It works properly this way
@import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&subset=cyrillic,cyrillic-ext,latin-ext);
@import url(https://use.fontawesome.com/releases/v5.3.1/css/all.css);
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
git log --format="%H" -n 1
Use the above command to get the commitid, hope this helps.
There's always a goto
statement, but I would recommend nesting an if
with an inverse of the breaking condition.
This would be Haskell-style:
def wrand(vtlg):
def helpf(lalt,lneu):
if not lalt==[]:
return helpf(lalt[1::],[lalt[0]+lneu[0]]+lneu)
else:
lneu.reverse()
return lneu[1:]
return helpf(vtlg,[0])
For multiplication of variable to time.Second using following code
oneHr:=3600
addOneHrDuration :=time.Duration(oneHr)
addOneHrCurrTime := time.Now().Add(addOneHrDuration*time.Second)
Eclipse has also its own annotations.
org.eclipse.jdt.annotation.NonNull
See at http://wiki.eclipse.org/JDT_Core/Null_Analysis for details.
Put the elements which you want to shift to the centre within this div tag.
<div class="col d-flex justify-content-center">
</div>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
This workedfor me
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
#pragma
push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?
try
{
// ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
// ...
}
To differentiate the routes, try adding a constraint that id must be numeric:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
For me, this is the most useful way to understand the three property types:
Public: Use this when you are OK with this variable being directly accessed and changed from anywhere in your code.
Example usage from outside of the class:
$myObject = new MyObject()
$myObject->publicVar = 'newvalue';
$pubVar = $myObject->publicVar;
Protected: Use this when you want to force other programmers (and yourself) to use getters/setters outside of the class when accessing and setting variables (but you should be consistent and use the getters and setters inside the class as well). This or private
tend to be the default way you should set up all class properties.
Why? Because if you decide at some point in the future (maybe even in like 5 minutes) that you want to manipulate the value that is returned for that property or do something with it before getting/setting, you can do that without refactoring everywhere you have used it in your project.
Example usage from outside of the class:
$myObject = new MyObject()
$myObject->setProtectedVar('newvalue');
$protectedVar = $myObject->getProtectedVar();
Private: private
properties are very similar to protected
properties. But the distinguishing feature/difference is that making it private
also makes it inaccessible to child classes without using the parent class's getter or setter.
So basically, if you are using getters and setters for a property (or if it is used only internally by the parent class and it isn't meant to be accessible anywhere else) you might as well make it private
, just to prevent anyone from trying to use it directly and introducing bugs.
Example usage inside a child class (that extends MyObject):
$this->setPrivateVar('newvalue');
$privateVar = $this->getPrivateVar();
do you want to force only children to be selected? http://css.maxdesign.com.au/selectutorial/selectors_child.htm
.area1
{
border:1px solid black;
}
.area1>.item
{
color:red;
}
.area2
{
border:1px solid blue;
}
.area2>.item
{
color:blue;
}
I think the tutorial passed by @emdhie will help a lot. How install maven
But, i followed and still getting mvn: command not found
I found this solution to know what was wrong in my configuration:
I opened the command line and called this command:
../apache-maven-3.5.3/bin/mvn --version
After that i got the correct JAVA_HOME and saw that my JAVA_HOME was wrong.
Hope this helps.
Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.
Try this in your Head section of the site:
$(function() {
$('.menu_box_list li').click(function() {
$('.menu_box_list li.active').removeClass('active');
$(this).addClass('active');
});
});
Try using something like Server.Transfer("~/ErrorPage.aspx");
from within the Application_Error()
method of global.asax.cs
Then from within Page_Load()
of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();
Server.Transfer()
seems to keep the exception hanging around.
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
In class WeatherRecord
:
First import the class if they are in different package else this statement is not requires
Import <path>.ClassName
Then, just referene or call your object like:
Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();
But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.
Date.date(date,month,year); // this is enough to call those static function
Have clear concept on Object and Static functions. Click me
Using
public String replaceAll(String regex, String replacement)
will work.
Usage would be str.replace("X", "");
.
Executing
"Xlakjsdf Xxx".replaceAll("X", "");
returns:
lakjsdf xx
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
Here's my two cents as the accepted answer didn't work for me.
var documentAtBottom = (document.documentElement.scrollTop + window.innerHeight) >= document.documentElement.scrollHeight;
I encounter similar situation. I would like to have background of the last .item
to be yellow in the elements that look like...
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
...
<div class="item">item x</div>
<div class="other">I'm here for some reasons</div>
</div>
I use nth-last-child(2)
to achieve it.
.item:nth-last-child(2) {
background-color: yellow;
}
It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick
You need to click Log Navigator icon (far right in left sidebar). Then choose your Debug/Run session in left sidebar, and you will have console in editor area.
This is because an XML documentation file has been specified in your Project Properties and Your Method/Class is public and lack documentation.
You can either :
Right Click on your Project -> Properties -> 'Build' tab -> uncheck XML Documentation File.
Summary of XML documentation goes like this:
/// <summary>
/// Description of the class/method/variable
/// </summary>
..declaration goes here..
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:
#include <iostream>
using namespace std;
int variable = 20;
int main()
{
float variable = 30;
cout << "This is local to the main function: " << variable << endl;
cout << "This is global to the main function: " << ::variable << endl;
return 0;
}
The resulting output would be:
This is local to the main function: 30
This is global to the main function: 20
Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.
I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.
Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer
controlval = "A1B2C3D4"
For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i
resultval = 1234
As you are using Windows, I think your path separator is '\' (and '/' on Linux).
Try using the constant DIRECTORY_SEPARATOR
. Your code will be more portable.
Try:
curl_setopt($process, CURLOPT_CAINFO, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cacert.pem');
EDIT: and write the full path. I had some issues with relative paths (perhaps curl is executed from another base directory?)
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
Here's an example of how you'd use filter
within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
<Files *>
Header set Cache-Control: "no-cache, private, pre-check=0, post-check=0, max-age=0"
Header set Expires: 0
Header set Pragma: no-cache
</Files>
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
The solution with removing the license information from the registry also works with Visual Studio 2013, but as described in the answer above, it is important to execute a "repair" on Visual Studio.
This worked for with maven 3.5.4 and now Intellij Idea see this code as source:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
</configuration>
</plugin>
Since nobody has yet mentioned it, the primary linguistic significance of size_t
is that the sizeof
operator returns a value of that type. Likewise, the primary significance of ptrdiff_t
is that subtracting one pointer from another will yield a value of that type. Library functions that accept it do so because it will allow such functions to work with objects whose size exceeds UINT_MAX on systems where such objects could exist, without forcing callers to waste code passing a value larger than "unsigned int" on systems where the larger type would suffice for all possible objects.