Another idea:
Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)
).
So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...
Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...
Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.
check this fiddle , and if you want to move the overlapped div you set its position to absolute
then change it's top
and left
values
You can always run this:
java -cp HelloWorld.jar HelloWorld
-cp HelloWorld.jar
adds the jar to the classpath, then HelloWorld
runs the class you wrote.
To create a runnable jar with a main class with no package, add Class-Path: .
to the manifest:
Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld
I would advise using a package
to give your class its own namespace. E.g.
package com.stackoverflow.user.blrp;
public class HelloWorld {
...
}
Here's how to determine a local user:
public bool IsLocalUser()
{
return windowsIdentity.AuthenticationType == "NTLM";
}
You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.
Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:
Why the NTLM Plug-in is Needed
NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.
Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.
By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.
How the Plug-in Works
The Verifier plug detects the following errors:
The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).
The target name in the call to InitializeSecurityContext is NULL.
The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.
The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).
The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.
NTLM Stops
5000 – Application Has Explicitly Selected NTLM Package
Severity – Error
The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.
How to Fix this Error
The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.
APIs(parameter) Used by Application Incorrect Value Correct Value ===================================== =============== ======================== AcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”
Let's break >> /dev/null 2>&1
statement into parts:
Part 1: >>
output redirection
This is used to redirect the program output and append the output at the end of the file. More...
Part 2: /dev/null
special file
This is a Pseudo-devices special file.
Command ls -l /dev/null
will give you details of this file:
crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null
Did you observe crw
? Which means it is a pseudo-device file which is of character-special-file type that provides serial access.
/dev/null
accepts and discards all input; produces no output (always returns an end-of-file indication on a read). Reference: Wikipedia
Part 3: 2>&1
file descriptor
Whenever you execute a program, the operating system always opens three files, standard input, standard output, and standard error as we know whenever a file is opened, the operating system (from kernel) returns a non-negative integer called a file descriptor. The file descriptor for these files are 0, 1, and 2, respectively.
So 2>&1
simply says redirect standard error to standard output.
&
means whatever follows is a file descriptor, not a filename.
In short, by using this command you are telling your program not to shout while executing.
What is the importance of using 2>&1
?
If you don't want to produce any output, even in case of some error produced in the terminal. To explain more clearly, let's consider the following example:
$ ls -l > /dev/null
For the above command, no output was printed in the terminal, but what if this command produces an error:
$ ls -l file_doesnot_exists > /dev/null
ls: cannot access file_doesnot_exists: No such file or directory
Despite I'm redirecting output to /dev/null
, it is printed in the terminal. It is because we are not redirecting error output to /dev/null
, so in order to redirect error output as well, it is required to add 2>&1
:
$ ls -l file_doesnot_exists > /dev/null 2>&1
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:
[['Gender']]
If it's easy enough for you to access your csv, you can use the excel formula trim()
to clip any spaces of the cells.
or remove it like this
df.columns = df.columns.to_series().apply(lambda x: x.strip())
I know the question is already closed but I've found it searching for same TypeScriptException, maybe some one else hit this question searching for this problem.
The problem lays in missing TypeScript typing:
var coordinates = outerElement[0].getBBox();
Throws The property 'getBBox' does not exist on value of type 'HTMLElement'.
var outerHtmlElement: any = outerElement[0];
var coordinates = outerHtmlElement.getBBox();
Since TypeScript 1.6, the prefered casting operator is as
, so those lines can be squashed into:
let coordinates = (outerElement[0] as any).getBBox();
Of course if you'd like to do it right, which is an overkill sometimes, you can:
HTMLElement
HTMLElement
System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;
will give you FileName of your app like; "MyApplication.exe"
As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0
is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*
>>> a = np.zeros(10)
>>> not np.any(a)
True
However, the answer claimed that any
was faster than other options due partly to short-circuiting. As of 2018, Numpy's all
and any
do not short-circuit.
If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba
:
import numba as nb
# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
for x in array.flat:
if x:
return True
return False
# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
for x in array.flat:
if not x:
return False
return True
These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero
is the slowest.
Some input to check performance:
import numpy as np
n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]
Check:
## count_nonzero
%timeit np.count_nonzero(all_0)
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
* Helpful all
and any
equivalences:
np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int(stringNumber)
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way
This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter.numberFromString(self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.
This fails with the timestamp error:
Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1
This works:
Insert Into Table2
Select Table1.A, Table1.B, null From Table1
I had come across the same requirement to flatter multidimensional array into single dimensional array than search value using text in key. here is my code
$data = '{
"json_data": [{
"downtime": true,
"pfix": {
"max": 100,
"threshold": 880
},
"ints": {
"int": [{
"rle": "pri",
"device": "laptop",
"int": "Ether3",
"ip": "127.0.0.3"
}],
"eth": {
"lan": 57
}
}
},
{
"downtime": false,
"lsi": "987654",
"pfix": {
"min": 10000,
"threshold": 890
},
"mana": {
"mode": "NONE"
},
"ints": {
"int": [{
"rle": "sre",
"device": "desk",
"int": "Ten",
"ip": "1.1.1.1",
"UF": true
}],
"ethernet": {
"lan": 2
}
}
}
]
}
';
$data = json_decode($data,true);
$stack = &$data;
$separator = '.';
$toc = array();
while ($stack) {
list($key, $value) = each($stack);
unset($stack[$key]);
if (is_array($value)) {
$build = array($key => ''); # numbering without a title.
foreach ($value as $subKey => $node)
$build[$key . $separator . $subKey] = $node;
$stack = $build + $stack;
continue;
}
if(!is_numeric($key)){
$toc[$key] = $value;
}
}
echo '<pre/>';
print_r($toc);
My output:
Array
(
[json_data] =>
[json_data.0] =>
[json_data.0.downtime] => 1
[json_data.0.pfix] =>
[json_data.0.pfix.max] => 100
[json_data.0.pfix.threshold] => 880
[json_data.0.ints] =>
[json_data.0.ints.int] =>
[json_data.0.ints.int.0] =>
[json_data.0.ints.int.0.rle] => pri
[json_data.0.ints.int.0.device] => laptop
[json_data.0.ints.int.0.int] => Ether3
[json_data.0.ints.int.0.ip] => 127.0.0.3
[json_data.0.ints.eth] =>
[json_data.0.ints.eth.lan] => 57
[json_data.1] =>
[json_data.1.downtime] =>
[json_data.1.lsi] => 987654
[json_data.1.pfix] =>
[json_data.1.pfix.min] => 10000
[json_data.1.pfix.threshold] => 890
[json_data.1.mana] =>
[json_data.1.mana.mode] => NONE
[json_data.1.ints] =>
[json_data.1.ints.int] =>
[json_data.1.ints.int.0] =>
[json_data.1.ints.int.0.rle] => sre
[json_data.1.ints.int.0.device] => desk
[json_data.1.ints.int.0.int] => Ten
[json_data.1.ints.int.0.ip] => 1.1.1.1
[json_data.1.ints.int.0.UF] => 1
[json_data.1.ints.ethernet] =>
[json_data.1.ints.ethernet.lan] => 2
)
"hello world".split.each{|i| i.capitalize!}.join(' ')
Update: So apparently, WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. Are there such engines for IE/Opera/Firefox and what are the differences, pros and cons of using one over the other? Can I use WebKit features in Firefox for example?
Every browser is backed by a rendering engine to draw the HTML/CSS web page.
See Comparison of web browser engines for a list of comparisons in different areas.
The ultimate question... is WebKit supported by IE?
Not natively.
I was also facing this issue for quite long time. Below are the steps that I perform, and it works for me always:
function IsNumeric(val) {
return Number(parseFloat(val)) === val;
}
I always do input prompts, like this:
<input style="color: #C0C0C0;" value="[email protected]"
onfocus="this.value=''; this.style.color='#000000'">
Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:
<script language = "text/Javascript">
cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
function clearField(t){ //declaring the array outside of the
if(! cleared[t.id]){ // function makes it static and global
cleared[t.id] = 1; // you could use true and false, but that's more typing
t.value=''; // with more chance of typos
t.style.color='#000000';
}
}
</script>
Your <input> field then looks like this:
<input id = 0; style="color: #C0C0C0;" value="[email protected]"
onfocus=clearField(this)>
According to pip documentation example 3:
pip install --upgrade django
But based on my experience, using this method will also upgrade any package related to it. Example:
Assume you want to upgrade somepackage
that require Django >= 1.2.4
using this kind of method it will also upgrade somepackage
and django
to the newest update. Just to be safe, do:
# Assume you want to keep Django 1.2.4
pip install --upgrade somepackage django==1.2.4
Doing this will upgrade somepackage
and keeping Django to the 1.2.4 version.
You can also use this code to show/hide elements:
document.getElementById(id).style.visibility = "hidden";
document.getElementById(id).style.visibility = "visible";
Note The difference between style.visibility
and style.display
is
when using visibility:hidden unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.
See this link to see the differences.
#father {
position: relative;
}
#son1 {
position: absolute;
top: 0;
}
#son2 {
position: absolute;
bottom: 0;
}
This works because position: absolute
means something like "use top
, right
, bottom
, left
to position yourself in relation to the nearest ancestor who has position: absolute
or position: relative
."
So we make #father
have position: relative
, and the children have position: absolute
, then use top
and bottom
to position the children.
Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
Use:
bt
- backtrace: show stack functions and argsinfo frame
- show stack start/end/args/locals pointers x/100x $sp
- show stack memory(gdb) bt
#0 zzz () at zzz.c:96
#1 0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2 0xf7d3a4f6 in yyyinit () at yyy.c:590
#3 0x0804ac0c in gnninit () at gnn.c:374
#4 main (argc=1, argv=0xffffd5e4) at gnn.c:389
(gdb) info frame
Stack level 0, frame at 0xffeac770:
eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
source language c.
Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
Locals at 0xffeac768, Previous frame's sp is 0xffeac770
Saved registers:
ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c
(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba 0xf7d3c0d8 0xf7d3c21b 0x00000001
0xffeac64c: 0xf78d133f 0xffeac6f4 0xf7a14450 0xffeac678
0xffeac65c: 0x00000000 0xf7d3790e
The new Grid CSS specification provides a far more elegant solution. Using position: absolute
may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.
Most minimal Grid Overlay example:
HTML
<div class="container">
<div class="content">This is the content</div>
<div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>
CSS
.container {
display: grid;
}
.content, .overlay {
grid-area: 1 / 1;
}
That's it. If you don't build for Internet Explorer, your code will most probably work.
Something along the lines of (using JSTL):
<p>Selected Values:
<ul>
<c:forEach items="${paramValues['select2']}" var="selectedValue">
<li><c:out value="${selectedValue}" /></li>
</c:forEach>
</ul>
</p>
I find this process much safer and easier to understand by creating another branch from the SHA1 of A and cherry-picking the desired changes so I can make sure I'm satisfied with how this new branch looks. After that, it is easy to remove the old branch and rename the new one.
git checkout <SHA1 of A>
git log #verify looks good
git checkout -b rework
git cherry-pick <SHA1 of D>
....
git log #verify looks good
git branch -D <oldbranch>
git branch -m rework <oldbranch>
Here is something i just put together.
if ( urlencode(urldecode($data)) === $data){
echo 'string urlencoded';
} else {
echo 'string is NOT urlencoded';
}
None of the above solutions worked for me on localhost. I even allowed access from less secure apps, allowed access through display unlock captcha and set the verify peer and verify peer name to false for SSL.
Eventually, I used the open source SMTP testing solution of MailHog. The steps are as follows:
MAIL_DRIVER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
MAIL_USERNAME=testuser
MAIL_PASSWORD=testpwd
MAIL_ENCRYPTION=null
According to their documentation:
An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.
Here is the link with example: http://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent
As the document describes, in order to start an activity (you also need to understand what activity is) use the intent like below
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.
[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db
Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped
function stringStripNCharsFromStart {
echo ${1:$2:${#1}}
}
echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl
sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git
should work fine
As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
This takes smhg from here and curt's from Last index of a given substring in MySQL and combines them. This is for mysql, all I needed was to get a decent split of name to first_name last_name with the last name a single word, the first name everything before that single word, where the name could be null, 1 word, 2 words, or more than 2 words. Ie: Null; Mary; Mary Smith; Mary A. Smith; Mary Sue Ellen Smith;
So if name is one word or null, last_name is null. If name is > 1 word, last_name is last word, and first_name all words before last word.
Note that I've already trimmed off stuff like Joe Smith Jr. ; Joe Smith Esq. and so on, manually, which was painful, of course, but it was small enough to do that, so you want to make sure to really look at the data in the name field before deciding which method to use.
Note that this also trims the outcome, so you don't end up with spaces in front of or after the names.
I'm just posting this for others who might google their way here looking for what I needed. This works, of course, test it with the select first.
It's a one time thing, so I don't care about efficiency.
SELECT TRIM(
IF(
LOCATE(' ', `name`) > 0,
LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
`name`
)
) AS first_name,
TRIM(
IF(
LOCATE(' ', `name`) > 0,
SUBSTRING_INDEX(`name`, ' ', -1) ,
NULL
)
) AS last_name
FROM `users`;
UPDATE `users` SET
`first_name` = TRIM(
IF(
LOCATE(' ', `name`) > 0,
LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
`name`
)
),
`last_name` = TRIM(
IF(
LOCATE(' ', `name`) > 0,
SUBSTRING_INDEX(`name`, ' ', -1) ,
NULL
)
);
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about
1959167 [MiB]
On jython 2.5 it crashes earlier:
239000 [MiB]
probably I can configure Jython to use more memory (it uses limits from JVM)
Test app:
import sys
sl = []
i = 0
# some magic 1024 - overhead of string object
fill_size = 1024
if sys.version.startswith('2.7'):
fill_size = 1003
if sys.version.startswith('3'):
fill_size = 497
print(fill_size)
MiB = 0
while True:
s = str(i).zfill(fill_size)
sl.append(s)
if i == 0:
try:
sys.stderr.write('size of one string %d\n' % (sys.getsizeof(s)))
except AttributeError:
pass
i += 1
if i % 1024 == 0:
MiB += 1
if MiB % 25 == 0:
sys.stderr.write('%d [MiB]\n' % (MiB))
In your app you read whole file at once. For such big files you should read the line by line.
"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.
GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html
Add this to your .pro file
QMAKE_CXXFLAGS += -std=c++11
or
CONFIG += c++11
Use shift method
array.shift(n) => Remove first n elements from array
array.shift(1) => Remove first element
Be aware that the result may be slightly different than you expect.
NOW()
returns a DATETIME
.
And INTERVAL
works as named, e.g. INTERVAL 1 DAY = 24 hours
.
So if your script is cron'd to run at 03:00
, it will miss the first three hours of records from the 'oldest' day
.
To get the whole day use CURDATE() - INTERVAL 1 DAY
. This will get back to the beginning of the previous day regardless of when the script is run.
With an editable div you can use the method document.execCommand
(more details) to easily provide the support for the tags you specified and for some other functionality..
#text {_x000D_
width : 500px;_x000D_
min-height : 100px;_x000D_
border : 2px solid;_x000D_
}
_x000D_
<div id="text" contenteditable="true"></div>_x000D_
<button onclick="document.execCommand('bold');">toggle bold</button>_x000D_
<button onclick="document.execCommand('italic');">toggle italic</button>_x000D_
<button onclick="document.execCommand('underline');">toggle underline</button>
_x000D_
If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a
To get your specific machine hardware name run
uname -m
You can also call
getconf LONG_BIT
which returns either 32 or 64
For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:
#! /usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
html = urlopen("http://www.google.com/")
print(html.read())
For anyone coming to this via Google, note that starting from SDK 1.6 Android now has an official native SDK.
You can download the Android NDK (Native Development Kit) from here: https://developer.android.com/ndk/downloads/index.html
Also there is an blog post about the NDK:
http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html
Try using the following:
Window parentWindow = Window.GetWindow(userControlReference);
The GetWindow
method will walk the VisualTree for you and locate the window that is hosting your control.
You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow
method from returning null
. E.g. wire up an event:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);
Mutations expect two arguments: state
and payload
, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.
The easiest way to pass a number of parameters is to destruct them:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
Then later on in your actions you can simply
store.commit('authenticate', {
token,
expiration,
});
There is one alternate solution (NOT the best solution) for this problem, but works. Using flag you can handle it, like below
/**
* Flag to avoid "java.lang.IllegalStateException: Can not perform this action after
* onSaveInstanceState". Avoid Fragment transaction until onRestoreInstanceState or onResume
* gets called.
*/
private boolean isOnSaveInstanceStateCalled = false;
@Override
public void onRestoreInstanceState(final Bundle bundle) {
.....
isOnSaveInstanceStateCalled = false;
.....
}
@Override
public void onSaveInstanceState(final Bundle outState) {
.....
isOnSaveInstanceStateCalled = true;
.....
}
@Override
public void onResume() {
super.onResume();
isOnSaveInstanceStateCalled = false;
.....
}
And you can check this boolean
value while doing fragment transaction.
private void fragmentReplace(Fragment fragment, String fragmentTag){
if (!isOnSaveInstanceStateCalled) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.layout_container, fragment, fragmentTag)
.commit();
}
}
Use position: fixed
, and anchor it to the top
and right
sides of the page:
#fixed-div {
position: fixed;
top: 1em;
right: 1em;
}
IE6 does not support position: fixed
, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div>
to contain some of the styles for it to work, as seen in the stylesheet.
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
In case anyone was wondering - it was probably my css...
@font-face
font-family: "bingo"
src: url('bingo.eot')
src: local('bingo')
src: url('bingo.svg#bingo') format('svg')
src: url('bingo.otf') format('opentype')
will render as
@font-face {
font-family: "bingo";
src: url('bingo.eot');
src: local('bingo');
src: url('bingo.svg#bingo') format('svg');
src: url('bingo.otf') format('opentype'); }
which seems to be close enough... just need to check the SVG rendering
Well, for just getting the filename of your batch the easiest way would be to just use %~n0
.
@echo %~n0
will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call
). The complete list of such “special” substitutions for path names can be found with help for
, at the very end of the help:
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only
To precisely answer your question, however: Substrings are done using the :~start,length
notation:
%var:~10,5%
will extract 5 characters from position 10 in the environment variable %var%
.
NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.
To get substrings of argument variables such as %0
, %1
, etc. you have to assign them to a normal environment variable using set
first:
:: Does not work:
@echo %1:~10,5
:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%
The syntax is even more powerful:
%var:~-7%
extracts the last 7 characters from %var%
%var:~0,-4%
would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [.
]).See help set
for details on that syntax.
In an XML file, there is a sequence of declarations, and you may override a previous definition with a newer one. When you use annotations, there is no notion of before or after. All the beans are at the same level. You defined two beans with the same name, and Spring doesn't know which one it should choose.
Give them a different name (staticConverterDAO, inMemoryConverterDAO for example), create an alias in the Spring XML file (theConverterDAO for example), and use this alias when injecting the converter:
@Autowired @Qualifier("theConverterDAO")
As of MySQL 5.6.5, you can use the DATETIME
type with a dynamic default value:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Or even combine both rules:
modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
Prior to 5.6.5, you need to use the TIMESTAMP
data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP
field can exist per table.
CREATE TABLE mytable (
mydate TIMESTAMP
)
See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
If you want to prevent MySQL from updating the timestamp value on UPDATE
(so that it only triggers on INSERT
) you can change the definition to:
CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
You can compare for exactly the same type using:
class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}
typeof returns the Type object from a given class.
But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.
class B : A {
}
var b = new B();
var typeOfb = b.GetType();
if (typeOfb == typeof(A)) { // false
}
if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}
I use this alias
git config --global alias.track '!f() { ([ $# -eq 2 ] && ( echo "Setting tracking for branch " $1 " -> " $2;git branch --set-upstream $1 $2; ) || ( git for-each-ref --format="local: %(refname:short) <--sync--> remote: %(upstream:short)" refs/heads && echo --Remotes && git remote -v)); }; f'
then
git track
You can use this method, It is easy to understand and implement :
public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
calendar.add(Calendar.MINUTE, nombreMinute);
calendar.add(Calendar.SECOND, nombreSeconde);
return calendar.getTime();
}
You can convert an existing vector into a matrix by wrapping it in an extra set of square brackets...
from numpy import *
v=array([5,4]) ## create a numpy vector
array([v]).T ## transpose a vector into a matrix
numpy also has a matrix
class (see array vs. matrix)...
matrix(v).T ## transpose a vector into a matrix
It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text()
and it'll work fine.
Remember that you cannot create a method and a property with the same name in a class.
By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:
Namespace: System.Linq
using System.Linq
namespace Teste
{
public class TestLinq
{
public return Foo()
{
var listX = new List<int>();
return listX.Count(x => x.Id == 1);
}
}
}
Namespace: System.Collections.Generic
using System.Collections.Generic
namespace Teste
{
public class TestList
{
public int Foo()
{
var listX = new List<int>();
return listX.Count;
}
}
}
With Java 7 you can use
if (Objects.equals(foo, null)) {
...
}
which will return true
if both parameters are null
.
on mac terminal (at least in ZSH): open stackoverflow.com
(opens site in new tab in your chrome default browser)
From remote repo:
svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax
with dataType: 'jsonp'
meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}
.
This method is more kind of a proxy actually attached in window
object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.
I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin
is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".
ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.
SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.
I found a simple & elegant method:
Code for the first activity:
final Object objSent = new Object();
final Bundle bundle = new Bundle();
bundle.putBinder("object_value", new ObjectWrapperForBinder(objSent));
startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
Log.d(TAG, "original object=" + objSent);
Code for the second activity:
final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value")).getData();
Log.d(TAG, "received object=" + objReceived);
you will find objSent
& objReceived
have the same hashCode
, so they are identical.
But why can we pass a java object in this way?
Actually, android binder will create global JNI reference for java object and release this global JNI reference when there are no reference for this java object. binder will save this global JNI reference in the Binder object.
*CAUTION: this method ONLY work unless the two activities run in the same process, otherwise throw ClassCastException at (ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value") *
class ObjectWrapperForBinder defination
public class ObjectWrapperForBinder extends Binder {
private final Object mData;
public ObjectWrapperForBinder(Object data) {
mData = data;
}
public Object getData() {
return mData;
}
}
But Method 2 has a little but serious issue, if the receiver fail to restore the java object (for example, some exception happen before restore the java object, or the receiver Activity does not exist at all), then the java object will become an orphan or memory leak, Method 1 don't have this issue, because android binder will handle this exception
To invoke the java object remotely, we will create a data contract/interface to describe the java object, we will use the aidl file
IDataContract.aidl
package com.example.objectwrapper;
interface IDataContract {
int func1(String arg1);
int func2(String arg1);
}
Code for the first activity
final IDataContract objSent = new IDataContract.Stub() {
@Override
public int func2(String arg1) throws RemoteException {
// TODO Auto-generated method stub
Log.d(TAG, "func2:: arg1=" + arg1);
return 102;
}
@Override
public int func1(String arg1) throws RemoteException {
// TODO Auto-generated method stub
Log.d(TAG, "func1:: arg1=" + arg1);
return 101;
}
};
final Bundle bundle = new Bundle();
bundle.putBinder("object_value", objSent.asBinder());
startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
Log.d(TAG, "original object=" + objSent);
Code for the second activity:
change the android:process attribute in AndroidManifest.xml to a non-empty process name to make sure the second activity run in another process
final IDataContract objReceived = IDataContract.Stub.asInterface(getIntent().getExtras().getBinder("object_value"));
try {
Log.d(TAG, "received object=" + objReceived + ", func1()=" + objReceived.func1("test1") + ", func2()=" + objReceived.func2("test2"));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In this way, we can pass an interface between two activities even though they run in different process, and call the interface method remotely
method 3 seem not simple enough because we must implement an aidl interface. If you just want to do simple task and the method return value is unnecessary, we can use android.os.Messenger
Code for the first activity( sender):
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
public static final int MSG_OP1 = 1;
public static final int MSG_OP2 = 2;
public static final String EXTRA_MESSENGER = "messenger";
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.e(TAG, "handleMessage:: msg=" + msg);
switch (msg.what) {
case MSG_OP1:
break;
case MSG_OP2:
break;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(this, SecondActivity.class).putExtra(EXTRA_MESSENGER, new Messenger(mHandler)));
}
}
Code for the second activity ( receiver ):
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final Messenger messenger = getIntent().getParcelableExtra(MainActivity.EXTRA_MESSENGER);
try {
messenger.send(Message.obtain(null, MainActivity.MSG_OP1, 101, 1001, "10001"));
messenger.send(Message.obtain(null, MainActivity.MSG_OP2, 102, 1002, "10002"));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
All the Messenger.send will execute in a Handler asynchronously and sequentially.
Actually, android.os.Messenger is also an aidl interface, if you have the android source code, you can find a file named IMessenger.aidl
package android.os;
import android.os.Message;
/** @hide */
oneway interface IMessenger {
void send(in Message msg);
}
Try this :
<script type="text/javascript">
function clearThis(target){
if(target.value == "[email protected]")
{
target.value= "";
}
}
</script>
onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.
<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function
Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function
Two parameter interface
BiConsumer
BiPredicate
BiFunction
For more than two, you have to create functional interface as follow(Consumer type):
@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
public void accept(T t, U u, V v, W w, X x);
}
For those who like to work close to the metal, here is a command that will clear out the unwanted soot, without needing any special tools or scripts:
adb logcat "eglCodecCommon:S"
This may have been answered before: Python URLLib / URLLib2 POST.
Your server is likely performing a 302 redirect from http://myserver/post_service
to http://myserver/post_service/
. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url
to http://myserver/post_service/
.
Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.
here "n" could be the number of temp variables present
rm(list = c(paste("temp",c(1:n),sep="")))
try this:
.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
You can do this:
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).
I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.
In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.
I would do it this way:
try {
txtProt = (EditText) findViewById(R.id.Protein); // Same
p = txtProt.getText().toString(); // Same
protein = Double.parseDouble(p); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
// p did not contain a valid double
}
EDIT: "the program force closes immediately without leaving any info in the logcat"
I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.
What are non-recursive mutexes good for?
They are absolutely good when you have to make sure the mutex is unlocked before doing something. This is because pthread_mutex_unlock
can guarantee that the mutex is unlocked only if it is non-recursive.
pthread_mutex_t g_mutex;
void foo()
{
pthread_mutex_lock(&g_mutex);
// Do something.
pthread_mutex_unlock(&g_mutex);
bar();
}
If g_mutex
is non-recursive, the code above is guaranteed to call bar()
with the mutex unlocked.
Thus eliminating the possibility of a deadlock in case bar()
happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.
If g_mutex
was recursive, there would be simply no way to make sure it is unlocked before making a call.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
All three template options - <%@include>
, <jsp:include>
and <%@tag>
are valid, and all three cover different use cases.
With <@include>
, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include
). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include>
(and JSTL's <c:import>
, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import>
also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute>
and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
Make sure that any client scripts you have that interact with .NET AJAX have the following line at the end:
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
This tells the script manager that the whole script file has loaded and that it can begin to call client methods
You can also write:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
Performance testing
At first glance it seems that repeat is the fastest way to create a list with n identical elements:
>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819
But wait - it's not a fair test...
>>> itertools.repeat(0, 10)
repeat(0, 10) # Not a list!!!
The function itertools.repeat
doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:
>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233
So if you want a list, use [e] * n
. If you want to generate the elements lazily, use repeat
.
One way is to simply destroy the listener once you are done with it.
var removeListener = $scope.$on('navBarRight-ready', function () {
$rootScope.$broadcast('workerProfile-display', $scope.worker)
removeListener(); //destroy the listener
})
Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :
public DefaultHttpClient secureClient() {
DefaultHttpClient httpclient = new DefaultHttpClient();
SSLSocketFactory sf;
KeyStore trustStore;
FileInputStream trustStream = null;
File truststoreFile;
// java.security.cert.PKIXParameters for the trustStore
PKIXParameters pkixParamsTrust;
KeyStore keyStore;
FileInputStream keyStream = null;
File keystoreFile;
// java.security.cert.PKIXParameters for the keyStore
PKIXParameters pkixParamsKey;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
truststoreFile = new File(TRUSTSTORE_FILE);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keystoreFile = new File(KEYSTORE_FILE);
try {
trustStream = new FileInputStream(truststoreFile);
keyStream = new FileInputStream(keystoreFile);
} catch (FileNotFoundException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
trustStore.load(trustStream, PASSWORD.toCharArray());
keyStore.load(keyStream, PASSWORD.toCharArray());
} catch (IOException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
pkixParamsTrust = new PKIXParameters(trustStore);
// accepts Server certificate generated with keytool and (auto) signed by SUN
pkixParamsTrust.setPolicyQualifiersRejected(false);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
pkixParamsKey = new PKIXParameters(keyStore);
// accepts Client certificate generated with keytool and (auto) signed by SUN
pkixParamsKey.setPolicyQualifiersRejected(false);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sf = new SSLSocketFactory(trustStore);
ClientConnectionManager manager = httpclient.getConnectionManager();
manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
} catch (KeyManagementException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
// use the httpclient for any httpRequest
return httpclient;
}
you can create user with name web2vi
and grant all privilage
Just another alternative if anyone cares.
You can also use the to_set
method of an array which converts the Array into a Set and by definition, set elements are unique.
[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]
Download a recent gradle release from gradle.org/releases Unzip the file and copy the gradle folder e.g. gradle 4.0 into C -- program files -- android -- android studio -- gradle. On your android studio goto file -- settings -- Build, Execution, Deployment --Build Tools -- Gradle and choose Use local gradle distribution, in the gradle home locate your gradle folder and click apply. Then click okay. This solved the problem for me. Your android studio might require a more recent gradle release, make sure you download a gradle that is compatible with your studio or latest releases.
Use ProgressDialog
ProgressDialog.show(Context context, CharSequence title, CharSequence message);
However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I
Self-referencing as example
public class Employee {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int ManagerId { get; set; }
public virtual Employee Manager { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public Employee() {
Employees = new HashSet<Employee>();
}
}
HasMany(e => e.Employees)
.WithRequired(e => e.Manager)
.HasForeignKey(e => e.ManagerId)
.WillCascadeOnDelete(false);
you can also use andSelf()
method to get wrapper DOM contain then find()
can be work around as your idea
$(function() {_x000D_
$('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/
This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671
This solution requires both an UPDATE
and INSERT
.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507
You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:
{
command1
command2
command3
command4
} > file1
{
command5
command6
command7
command8
} > file2
There is no colspan in css as far as I know, but there will be column-span
for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div
and span
with table-like display like this.
This would be the HTML:
<div class="table">
<div class="row">
<span class="cell red first"></span>
<span class="cell blue fill"></span>
<span class="cell green last"></span>
</div>
</div>
<div class="table">
<div class="row">
<span class="cell black"></span>
</div>
</div>
And this would be the css:
/* this is to reproduce table-like structure
for the sake of table-less layout. */
.table { display:table; table-layout:fixed; width:100px; }
.row { display:table-row; height:10px; }
.cell { display:table-cell; }
/* this is where the colspan tricks works. */
span { width:100%; }
/* below is for visual recognition test purposes only. */
.red { background:red; }
.blue { background:blue; }
.green { background:green; }
.black { background:black; }
/* this is the benefit of using table display, it is able
to set the width of it's child object to fill the rest of
the parent width as in table */
.first { width: 20px; }
.last { width: 30px; }
.fill { width: 100%; }
The only reason to use this trick is to gain the benefit of table-layout
behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.
But if you don't need to benefit from the table-layout
behaviour, then durilai's answer would suit you enough.
There isn't any function in the standard library (to my knowledge) that will do it, but there are absolutely modules out there which have such functions. However, its easy enough that you can just write your own function:
def normalize(lst):
s = sum(lst)
return map(lambda x: float(x)/s, lst)
Sample output:
>>> normed = normalize(raw)
>>> normed
[0.25, 0.5, 0.25]
You can limit in following way. First is starting index and second is number of characters.
**{{ results['text'][4:2] }}**
If you want to alter the original objects, then a simple Array#forEach
will do:
rockets.forEach(function(rocket) {
rocket.launches += 10;
});
If you want to keep the original objects unaltered, then use Array#map
and copy the objects using Object#assign
:
var newRockets = rockets.forEach(function(rocket) {
var newRocket = Object.assign({}, rocket);
newRocket.launches += 10;
return newRocket;
});
It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.
If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true
in your tsconfig.json
file.
You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
import difflib
cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
('afrykanerskojezycznym', 'afrykanerskojezyczny'),
('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
('abcdefg','xac')]
for a,b in cases:
print('{} => {}'.format(a,b))
for i,s in enumerate(difflib.ndiff(a, b)):
if s[0]==' ': continue
elif s[0]=='-':
print(u'Delete "{}" from position {}'.format(s[-1],i))
elif s[0]=='+':
print(u'Add "{}" to position {}'.format(s[-1],i))
print()
prints:
afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20
afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2
afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20
nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16
abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
Use Datepart function: DATEPART(datepart, date)
E.g#
SELECT DatePart(@YourVar, hh)*60) + DatePart(@YourVar, mi)*60)
This will give you total time of day in minutes allowing you to compare more easily.
You can use DateDiff if your dates are going to be the same, otherwise you'll need to strip out the date as above
I found that setting the time out settings in HttpConnectionParams
and HttpConnectionManager
did not solve our case. We're limited to using org.apache.commons.httpclient
version 3.0.1.
I ended up using an java.util.concurrent.ExecutorService
to monitor the HttpClient.executeMethod()
call.
Here's a small, self-contained example
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
/**
* @author Jeff Kirby
* @since <pre>Jun 17, 2011</pre>
*/
public class Example {
private static final String SITE = "http://some.website.com/upload";
private static final int TIME_OUT_SECS = 5;
// upload a file and return the response as a string
public String post(File file) throws IOException, InterruptedException {
final Part[] multiPart = { new FilePart("file", file.getName(), file) };
final EntityEnclosingMethod post = new PostMethod(SITE);
post.setRequestEntity(new MultipartRequestEntity(multiPart, post.getParams()));
final ExecutorService executor = Executors.newSingleThreadExecutor();
final List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new KillableHttpClient(post)), TIME_OUT_SECS, TimeUnit.SECONDS);
executor.shutdown();
if(futures.get(0).isCancelled()) {
throw new IOException(SITE + " has timed out. It has taken more than " + TIME_OUT_SECS + " seconds to respond");
}
return post.getResponseBodyAsString();
}
private static class KillableHttpClient implements Callable<Integer> {
private final EntityEnclosingMethod post;
private KillableHttpClient(EntityEnclosingMethod post) {
this.post = post;
}
public Integer call() throws Exception {
return new HttpClient().executeMethod(post);
}
}
}
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
Executive summary / TL;DR:
Try doing a find & replace of "=" with "=". Yes, replace the equals sign with itself. For my scenario, it forced everything to update.
Background:
I frequently make formulas across multiple columns then concatenate them together. After doing such, I'll copy & paste them as values to extract my created formula. After this process, they're typically stuck displaying a formula, and not displaying a value, unless I enter the cell and press Enter. Pressing F2 & Enter repeatedly is not fun.
As of 2014, you can trigger the click on a <a/>
tag. However, for security reasons, you have to do it in a click
event handler, or the browser will tag it as a popup (some other events may allow you to safely trigger the opening).
Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.
csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv
Replacing 2 with the column number will effectively extract the column data you are looking for.
A trick that works is to position box #2 with position: absolute
instead of position: relative
. We usually put a position: relative
on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute
to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:
And here is the full code with this change:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
/* Positioning */
#box1 { overflow: hidden }
#box2 { position: absolute }
#box3 { position: absolute; top: 10px }
/* Styling */
#box1 { background: #efe; padding: 5px; width: 125px }
#box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
#box3 { background: #eef; padding: 2px; width: 75px; height: 150px }
</style>
</head>
<body>
<br/><br/><br/>
<div id="box1">
<div id="box2">
<div id="box3"/>
</div>
</div>
</body>
</html>
This how I managed to get the screen width in React JS Project:
If width is equal to 1680 then return 570 else return 200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
You can use:
for await (let resolvedPromise of arrayOfPromises) {
console.log(resolvedPromise)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
If you wish to use Promise.all()
instead you can go for Promise.allSettled()
So you can have better control over rejected promises.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
Size of the boolean in java is virtual machine dependent. but Any Java object is aligned to an 8 bytes granularity. A Boolean has 8 bytes of header, plus 1 byte of payload, for a total of 9 bytes of information. The JVM then rounds it up to the next multiple of 8. so the one instance of java.lang.Boolean takes up 16 bytes of memory.
Simply you can use this code for solve it:
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
appDb.daoAccess().someJobes();//replace with your code
}
});
Or in lambda you can use this code:
Executors.newSingleThreadExecutor().execute(() -> appDb.daoAccess().someJobes());
You can replace appDb.daoAccess().someJobes()
with your own code;
Use the response.info()
method to get the headers.
From the urllib2 docs:
urllib2.urlopen(url[, data][, timeout])
...
This function returns a file-like object with two additional methods:
- geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
- info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)
So, for your example, try stepping through the result of response.info().headers
for what you're looking for.
Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.
<TextView android:alpha="0.3" ...
, for example.
Change the file phpmyadmin.conf on c:/wamp64/alias/phpmyadmin.conf
php_admin_value upload_max_filesize 512M
php_admin_value post_max_size 512M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360
It's very important you increase the time to 5000 or higher, Thus, the process will not stop when you are uploading a large file.
That works for me.
Here is a complete method that only has one button, an 'ok', to close the UIAlert:
- (void) myAlert: (NSString*)errorMessage
{
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:errorMessage
message:@""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"ok", nil];
myAlert.cancelButtonIndex = -1;
[myAlert setTag:1000];
[myAlert show];
}
You need to use a group by clause.
SELECT site_id, MAX(ts) as TIME, count(*) group by site_id
Now we've got CSS grid. Welcome to 2019.
/* Required */_x000D_
body {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
height: 100vh;_x000D_
display: grid;_x000D_
grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="header">Header Content</div>_x000D_
<div id="content">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<div id="footer">Footer Content</div>_x000D_
</div>_x000D_
</body>
_x000D_
If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.
This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.
import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
# Temporary rc parameters in effect
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(range(10))
ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))
You can type plt.rcParams
to view all available rc parameters, and use list comprehension to search for keywords:
# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]
In this case it is better to use basename
instead of awk
:
$ basename /home/parent/child1/child2/filename
filename
I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler
(pretty sure some of the web devs already know about this tool)
Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder
PS. I would rather have it implemented in Chrome as a flag preserve after reload
, cannot do this now, forums and discussion groups blocked on corporate network :)
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
Scope means the code context that performs the INSERT
statement SCOPE_IDENTITY()
, as opposed to the global scope of @@IDENTITY
.
CREATE TABLE Foo(
ID INT IDENTITY(1,1),
Dummy VARCHAR(100)
)
CREATE TABLE FooLog(
ID INT IDENTITY(2,2),
LogText VARCHAR(100)
)
go
CREATE TRIGGER InsertFoo ON Foo AFTER INSERT AS
BEGIN
INSERT INTO FooLog (LogText) VALUES ('inserted Foo')
INSERT INTO FooLog (LogText) SELECT Dummy FROM inserted
END
INSERT INTO Foo (Dummy) VALUES ('x')
SELECT SCOPE_IDENTITY(), @@IDENTITY
Gives different results.
When using java 8, you may take advantage of stream API and simplify code to
return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();
That will give you java.util.Optional
If you prefer null instead, all you need is
...
.getResultList()
.stream().findFirst().orElse(null);
Here a complete example :
Suppose we have a Person class like :
public class Person
{
protected String fname;
protected String lname;
public Person()
{
}
public Person(String fname, String lname)
{
this.fname = fname;
this.lname = lname;
}
public boolean equals(Object objet)
{
if(objet instanceof Person)
{
Person p = (Person) objet;
return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
}
else return super.equals(objet);
}
@Override
public String toString()
{
return "Person(fname : " + getFname + ", lname : " + getLname + ")";
}
/** Getters and Setters **/
}
Now we create a comparator :
import java.util.Comparator;
public class ComparePerson implements Comparator<Person>
{
@Override
public int compare(Person p1, Person p2)
{
if(p1.getFname().equalsIgnoreCase(p2.getFname()))
{
return p1.getLname().compareTo(p2.getLname());
}
return p1.getFname().compareTo(p2.getFname());
}
}
Finally suppose we have a group of persons :
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Group
{
protected List<Person> listPersons;
public Group()
{
this.listPersons = new ArrayList<Person>();
}
public Group(List<Person> listPersons)
{
this.listPersons = listPersons;
}
public void order(boolean asc)
{
Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
Collections.sort(this.listPersons, comp);
}
public void display()
{
for(Person p : this.listPersons)
{
System.out.println(p);
}
}
/** Getters and Setters **/
}
Now we try this :
import java.util.ArrayList;
import java.util.List;
public class App
{
public static void main(String[] args)
{
Group g = new Group();
List listPersons = new ArrayList<Person>();
g.setListPersons(listPersons);
Person p;
p = new Person("A", "B");
listPersons.add(p);
p = new Person("C", "D");
listPersons.add(p);
/** you can add Person as many as you want **/
g.display();
g.order(true);
g.display();
g.order(false);
g.display();
}
}
Well, this question was asked years ago. I think technology has changed quite a bit and browser compatibility is much better. You could use vertical-align but I would consider that some what less scaleable and less reusable. I would recommend a flexbox approach.
Here is the same example the original poster used but with flexbox. It styles a single element. If a button size changes for whatever reason, it will continue to be vertically and horizontally centered.
.button {
border: 1px solid #ccc;
height: 40px;
margin: 60px;
padding: 4px;
display: flex;
justify-content: space-around;
align-items: center;
}
Example: JsFiddle
I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.
in eclipse
properties->c/c++Build->setting->GCC C++ linker->libraries in top part add "pthread"
I had the same error with JBoss 7.1.. And I did the same as Zefiro. Just ignored the error and i was able to place breakpoints normally. In my case i was building thought ant builder and this is my javac task:
<javac
srcdir="${src.dir}"
destdir="${build.classes.dir}"
includeantruntime="false"
debug="${debug}"
verbose="false"
debuglevel="lines,vars,source"
source="1.6"
target="1.6">
<!-- Sppressing warning for setting an older source without bootclasspath
(see: https://blogs.oracle.com/darcy/entry/bootclasspath_older_source) -->
<compilerarg value="-Xlint:-options"/>
<classpath>
<fileset dir="${lib.dir}" includes="*.jar" />
<fileset dir="${jboss.lib.dir}" includes="**/*.jar" />
</classpath>
</javac>
int fib(int x)
{
if (x < 2)
return x;
else
return (fib(x - 1) + fib(x - 2));
}
Each class implementing IList has a method Contains(Object value). And so does System.Array.
declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
@locationID =
CASE @locationType
WHEN 'location' THEN account_location
WHEN 'area' THEN xxx_location_area
WHEN 'division' THEN xxx_location_division
END
I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm
Which works nicely. :)
Starting from GNU make 3.82 (July 2010), you can use the .ONESHELL
special target to run all recipe lines in a single instantiation of the shell (bold emphasis mine):
- New special target:
.ONESHELL
instructs make to invoke a single instance of the shell and provide it with the entire recipe, regardless of how many lines it contains.
.ONESHELL: # Only applies to all target
all:
cd ~/some_dir
pwd # Prints ~/some_dir if cd succeeded
another_rule:
cd ~/some_dir
pwd # Oops, prints ~
Not really the answer to your question, but if you want to have something like an array that can grow and shrink you should not use an array in java. You are probably best of by using ArrayList or another List implementation.
You can then call size() on it to get it's size.
This was the only code snippet that worked for me
Swift 4:
tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: true)
P.S. 70 is the height of my header and table view cell
For all Solution index.php remove form url and woff file allowed. for write below code in .htaccess file and and make this alternation to your application/config/config.php file: $config['index_page'] = '';
For only Linux hosting server. .htaccess file details
AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
To get an array with the right keys, you can try this:
// Open file
$file = fopen($file_path, 'r');
// Headers
$headers = fgetcsv($file);
// Rows
$data = [];
while (($row = fgetcsv($file)) !== false)
{
$item = [];
foreach ($row as $key => $value)
$item[$headers[$key]] = $value ?: null;
$data[] = $item;
}
// Close file
fclose($file);
I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'your/route'
];
func change(string: inout String) {
var character: Character = .normal
enum Character {
case space
case newLine
case normal
}
for i in stride(from: string.count - 1, through: 0, by: -1) {
// first get index
let index: String.Index?
if i != 0 {
index = string.index(after: string.index(string.startIndex, offsetBy: i - 1))
} else {
index = string.startIndex
}
if string[index!] == "\n" {
if character != .normal {
if character == .newLine {
string.remove(at: index!)
} else if character == .space {
let number = string.index(after: string.index(string.startIndex, offsetBy: i))
if string[number] == " " {
string.remove(at: number)
}
character = .newLine
}
} else {
character = .newLine
}
} else if string[index!] == " " {
if character != .normal {
string.remove(at: index!)
} else {
character = .space
}
} else {
character = .normal
}
}
// startIndex
guard string.count > 0 else { return }
if string[string.startIndex] == "\n" || string[string.startIndex] == " " {
string.remove(at: string.startIndex)
}
// endIndex - here is a little more complicated!
guard string.count > 0 else { return }
let index = string.index(before: string.endIndex)
if string[index] == "\n" || string[index] == " " {
string.remove(at: index)
}
}
Working solution:
Bootstrap 3.0 by default has a 15px padding on top and bottom, so we just need to override it!
For example:
.navbar-nav > li > a {padding-top:10px !important; padding-bottom:10px !important;}
.navbar {min-height:40px !important}
Just to top this up to the new Java 8 API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.
The project npm-install-peers
will detect peers and install them.
As of v1.0.1
it doesn't support writing back to the package.json
automatically, which would essentially solve our need here.
Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4
Try the following shell command (replace DB_NAME
with your database name):
mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head
For Drupal/drush solution, check the following example script which will display the biggest tables in use:
#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20
For anyone coming across this years later:
TL;DR check your pip version (2 vs 3)
I had this same issue and it was not fixed by running pip install simplejson
despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.
> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)
Installing with the correct version of pip is as easy as using pip2
:
> pip2 install simplejson
and then python 2 can import simplejson
fine.
Edited @ajhuddy's answer a little. Only for bar charts. My version adds:
Downside: When hovering over a bar that has value inside it the value might look a little jagged. I have not found a solution do disable hover effects. It might also need tweaking depending on your own settings.
Configuration:
bar: {
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
animation: {
onComplete: function() {
this.chart.controller.draw();
drawValue(this, 1);
},
onProgress: function(state) {
var animation = state.animationObject;
drawValue(this, animation.currentStep / animation.numSteps);
}
}
}
Helpers:
// Font color for values inside the bar
var insideFontColor = '255,255,255';
// Font color for values above the bar
var outsideFontColor = '0,0,0';
// How close to the top edge bar can be before the value is put inside it
var topThreshold = 20;
var modifyCtx = function(ctx) {
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
return ctx;
};
var fadeIn = function(ctx, obj, x, y, black, step) {
var ctx = modifyCtx(ctx);
var alpha = 0;
ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
ctx.fillText(obj, x, y);
};
var drawValue = function(context, step) {
var ctx = context.chart.ctx;
context.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20;
fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
}
});
};
To avoid a lot of complexity I keep track of the current viewController by creating a viewController in the delegate and set it to self inside each viewDidLoad method, this way anytime you load a new view the ViewController held in the delegate will correspond to that view's viewController. This may be ugly, but it works wonderfully, and theres no need to have a navigation controller or any of that nonsense.
I got a very similar error message that was caused by inadvertently having made a duplicate of a class in another project of my solution. Deleting the duplicate fixed the issue
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Yes, you can use Visual Studio for Android (native) using "vs-android".
Here are the steps to set it up:
Download the Android SDK here.
Download the Android NDK here.
Download Cygwin here.
Download the JDK here.
Download Visual Studio 2010, 2012 or 2013 here.
Download vs-android here.
Download Apache Ant here.
Set environment variables:
(Control Panel > System > Advanced > Environment Variables)
ANDROID_HOME = <install_path>\android-sdk
ANDROID_NDK_ROOT = <install_path>\android-ndk
ANT_HOME = <install_path>\apache-ant
JAVA_HOME = <install_path>\jdk
_JAVA_OPTIONS = -Xms256m -Xmx512m
It works like a charm... and best so far to use.
One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.
Websocket and WebRTC can be used together, Websocket as a signal channel of WebRTC, and webrtc is a video/audio/text channel, also WebRTC can be in UDP also in TURN relay, TURN relay support TCP HTTP also HTTPS. Many projects use Websocket and WebRTC together.
I had this issue with python 3.5, anaconda 3, windows 7 32 bit. I solved it by moving my pythonX.lib and pythonX.dll files into my working directory and calling
Py_SetPythonHome(L"C:\\Path\\To\\My\\Python\\Installation");
before initialize so that it could find the headers that it needed, where my path was to "...\Anaconda3\". The extra step of calling Py_SetPythonHome was required for me or else I'd end up getting other strange errors where python import files.
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
I did this recently but included double quotes around my values.
For example, change these two lines:
sb.Append("\"" + col.ColumnName + "\",");
...
sb.Append("\"" + row[i].ToString() + "\",");
if you want to see it graphically you can use
gitk -- foo/A
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.
$query->withCount([
'activity AS paid_sum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
it returns
"paid_sum_count" => "320.00"
in Deals attribute.
This it now the sum which i wanted to get not the count.
Or you can always map
over an iterator, without the need to build an intermediate list:
>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
Press CTRL+F11
to rotate the screen.
thanks, try this instead
Select
STR(account_code) as account_code_Numeric,
descr
from account
where STR(account_code) = 1
I'm happy to help you
I installed Android Studio alongside to Xamarin Visual Studio (was already installed). After the installation (excluded SDK, because they were already installed) I started Android Studio and it downloaded, installed and added missing SDKs (after giving the path to the SDK location). As a result I got the error message on build
java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0
As a solution I installed jdk-8u101-windows-i586.exe
without JRE (because it was already installed). Before I tried the x64 version, but it disappeared ... Then you have to change the Java Development Kit location.
This is done in Visual Studio by clicking Tools > Options > Xamarin > Android Settings. Here you can navigate to the correct location. In my case it was C:\Program Files (x86)\Java\jdk1.8.0_101
.
Finally, clean your project and make a new build :-)
Add this dependency to your pom.xml
file:
http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
</dependency>
This will select and deselect all checkboxes:
function checkAll()
{
var checkboxes = document.getElementsByTagName('input'), val = null;
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].type == 'checkbox')
{
if (val === null) val = checkboxes[i].checked;
checkboxes[i].checked = val;
}
}
}
You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:
function checkAll()
{
var table = document.getElementById ('dataTable');
var checkboxes = table.querySelectorAll ('input[type=checkbox]');
var val = checkboxes[0].checked;
for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
}
Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:
function checkAll (tableID)
{
var table = document.getElementById (tableID);
var val = table.rows[0].cells[0].children[0].checked;
for (var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[0].children[0].checked = val;
}
}
Why not to use FusedLocationApi
instead of OnMyLocationChangeListener
? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates()
method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient
.
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
@Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
@Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
You could use a separate file, like npm_globals.txt
, instead of package.json
. This file would contain each module on a new line like this,
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Then in the command line run,
< npm_globals.txt xargs npm install -g
Check that they installed properly with,
npm list -g --depth=0
As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json
encapsulate these tools and dependencies together is much preferred.
But nowadays I find that I'm always installing create-react-app
and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.
And nowadays, I'm using npx
, an npm package runner, instead of installing packages globally.
You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.
DELETE FROM tableA
WHERE ROWID IN
( SELECT q.ROWID
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
On the basis that some of the recommendations here (esp in the comments) suggested the use of Python, I was disappointed not to find an example.
So, here's a one liner to get a single value from some JSON data. It assumes that you are piping the data in (from somewhere) and so should be useful in a scripting context.
echo '{"hostname":"test","domainname":"example.com"}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["hostname"]'
On Oracle XE this works:
SELECT 'DROP TABLE "' || TABLE_NAME || '";'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'
Or if you want to remove the constraints and free up space as well, use this:
SELECT 'DROP TABLE "' || TABLE_NAME || '" cascade constraints PURGE;'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'
Which will generate a bunch of DROP TABLE cascade constraints PURGE
statements...
For VIEWS
use this:
SELECT 'DROP VIEW "' || VIEW_NAME || '";'
FROM USER_VIEWS
WHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'
This error
Failure [INSTALL_FAILED_OLDER_SDK]
Means that you're trying to install an app that has a higher minSdkVersion
specified in its manifest than the device's API level. Change that number to 8
and it should work. I'm not sure about the other error, but it may be related to this one.
not sure if it works outside of firefox:
callback (event){
if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
// do something
}
}
if not, replace event.DOM_VK_BACK_SPACE
with 8
and event.DOM_VK_DELETE
with 46
or define them as constant (for better readability)
Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true)
first if you're accessing it from a different class.
import java.lang.reflect.*;
class Other
{
private String str;
public void setStr(String value)
{
str = value;
}
}
class Test
{
public static void main(String[] args)
// Just for the ease of a throwaway test. Don't
// do this normally!
throws Exception
{
Other t = new Other();
t.setStr("hi");
Field field = Other.class.getDeclaredField("str");
field.setAccessible(true);
Object value = field.get(t);
System.out.println(value);
}
}
And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.
"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.
If Model.update
statement does not work for you, you can try like this:
try{
await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
console.log(err)
}
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.
I'm using Debian, and I was unable to use tilde for the path. Originally I was using
curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword
I had to change this to:
curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword
-c
creates the cookie, -b
uses the cookie
so then I'd use for instance:
curl -b "/tmp/cookie" http://localhost:5000/getData
An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .
Map<String,Integer> newMap = givenMap.
entrySet().
stream().collect(Collector.of
( ()-> new HashMap<String,Integer>(),
(mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
(map1,map2)->{ map1.putAll(map2); return map1;}
));
I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah.
These times, I've realized that the last path element was "src". Just removing this path element (thus indeed pointing one level above the actual path where the "org" or "com" folder is located) magically makes it work.
Somehow, Eclipse seems to imply this "src" path element if present, and if you then have it included in the source path, Eclipse chokes. Or something like that.
You can monkey-patch the Array class:
class Array
def contains_all?(ary)
ary.uniq.all? { |x| count(x) >= ary.count(x) }
end
end
test
irb(main):131:0> %w[a b c c].contains_all? %w[a b c]
=> true
irb(main):132:0> %w[a b c c].contains_all? %w[a b c c]
=> true
irb(main):133:0> %w[a b c c].contains_all? %w[a b c c c]
=> false
irb(main):134:0> %w[a b c c].contains_all? %w[a]
=> true
irb(main):135:0> %w[a b c c].contains_all? %w[x]
=> false
irb(main):136:0> %w[a b c c].contains_all? %w[]
=> true
irb(main):137:0> %w[a b c d].contains_all? %w[d c h]
=> false
irb(main):138:0> %w[a b c d].contains_all? %w[d b c]
=> true
Of course the method can be written as a standard-alone method, eg
def contains_all?(a,b)
b.uniq.all? { |x| a.count(x) >= b.count(x) }
end
and you can invoke it like
contains_all?(%w[a b c c], %w[c c c])
Indeed, after profiling, the following version is much faster, and the code is shorter.
def contains_all?(a,b)
b.all? { |x| a.count(x) >= b.count(x) }
end
The following worked for me when changing Author and Committer of a commit.
git push -f origin master
Git was smart enough to figure out that these were commits of identical deltas which only differed in the meta information section.
Both the local and remote heads pointed to the commits in question.
You could try removing any alphanumeric characters and space. And then use -n
will give you the line number. Try following:
grep -vn "^[a-zA-Z0-9 ]*$" application.log
You can do it with gridview's datarow bound event. try the following sample of code:
protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}
For more details about the row databound event study Thsi....
One line solution:
& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")
I use Wrapper's setValue[https://vue-test-utils.vuejs.org/api/wrapper/#setvalue-value] method to set value.
inputA = wrapper.findAll('input').at(0)
inputA.setValue('123456')
Using jQuery:
$('#link_other a').each(function(){
$(this).attr('target', '_BLANK');
});
Simple SCSS solution with pseudo-elements
Live demo: https://codepen.io/vlasterx/pen/xaMgag
// Change border size here_x000D_
$border-width: 5px;_x000D_
_x000D_
.element-with-border {_x000D_
display: flex;_x000D_
height: 100px;_x000D_
width: 100%;_x000D_
position: relative;_x000D_
background-color: #f2f2f2;_x000D_
box-sizing: border-box;_x000D_
_x000D_
// Use pseudo-element to create inset border_x000D_
&:before {_x000D_
position: absolute;_x000D_
content: ' ';_x000D_
display: flex;_x000D_
border: $border-width solid black;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
border: $border-width solid black;_x000D_
// Important: We must deduct border size from width and height_x000D_
width: calc(100% - $border-width); _x000D_
height: calc(100% - $border-width);_x000D_
}_x000D_
}
_x000D_
<div class="element-with-border">_x000D_
Lorem ipsum dolor sit amet_x000D_
</div>
_x000D_
In my case the problem was 32-bit Putty and pageant.exe - it can't communicate with 64-bit TortoisePlink.exe. Replacing 32-bit Putty with a 64-bit version solved the problem.
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
first you have to import: import javax.swing.JOptionPane; then you can call it using this:
JOptionPane.showMessageDialog(null,
"ALERT MESSAGE",
"TITLE",
JOptionPane.WARNING_MESSAGE);
the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE
. it works pretty well in a lot of ways mostly for errors.
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
Try this:
location / {
root /path/to/root;
expires 30d;
access_log off;
}
location ~* ^.*\.php$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php
should be forwared to Apache if only a corresponding .php
file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.
You could use CodeSmith to generate something like this:
http://www.csharping.com/PermaLink,guid,cef1b637-7d37-4691-8e49-138cbf1d51e9.aspx
I prefer using the glob
module, as it does pattern matching and expansion.
import glob
print(glob.glob("/home/adam/*.txt"))
It will return a list with the queried files:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
Quick, interactive way to see column names
If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.
import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description
Outputs something like this:
(('Date', None, None, None, None, None, None),
('Object-Name', None, None, None, None, None, None),
('Object-Count', None, None, None, None, None, None))
Or, quick way to access and print them out.
colnames = cursor.description
for row in colnames:
print row[0]
Outputs something like this:
Date
Object-Name
Object-Count
This is what I did, and it works for me.
step 1: add this in the build.grade(module: app)
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
step 2: sync the project and done.
Both versions using sets didn't work for me (tested with MySQL 5.5). The function ELT() returns the whole set. Considering the WHILE statement is only avaible in PROCEDURE context i added it to my solution:
DROP PROCEDURE IF EXISTS __main__;
DELIMITER $
CREATE PROCEDURE __main__()
BEGIN
SET @myArrayOfValue = '2,5,2,23,6,';
WHILE (LOCATE(',', @myArrayOfValue) > 0)
DO
SET @value = LEFT(@myArrayOfValue, LOCATE(',',@myArrayOfValue) - 1);
SET @myArrayOfValue = SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);
END WHILE;
END;
$
DELIMITER ;
CALL __main__;
To be honest, i don't think this is a good practice. Even if its realy necessary, this is barely readable and quite slow.
You can use the following code to get the value of the first column of the selected row of your table.
int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();