If it is an absolute must to generate delay in a test CountDownLatch
is a simple solution. In your test class declare:
private final CountDownLatch waiter = new CountDownLatch(1);
and in the test where needed:
waiter.await(1000 * 1000, TimeUnit.NANOSECONDS); // 1ms
Maybe unnecessary to say but keeping in mind that you should keep wait times small and not cumulate waits to too many places.
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
A simple alternative to this is to use threads along with join. Refer : Joining Threads
A wait()
only makes sense when there is also a notify()
, so it's always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:
Semantically, you never just wait()
. You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is
if(!condition){
wait();
}
But the condition is being set by a separate thread, so in order to have this work correctly you need synchronization.
A couple more things wrong with it, where just because your thread quit waiting doesn't mean the condition you are looking for is true:
You can get spurious wakeups (meaning that a thread can wake up from waiting without ever having received a notification), or
The condition can get set, but a third thread makes the condition false again by the time the waiting thread wakes up (and reacquires the monitor).
To deal with these cases what you really need is always some variation of this:
synchronized(lock){
while(!condition){
lock.wait();
}
}
Better yet, don't mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent
packages.
Those who are using Java 7.0 or below version can refer the code which I used here and it works.
public class WaitTest {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void waitHere(long waitTime) {
System.out.println("wait started...");
lock.lock();
try {
condition.await(waitTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
System.out.println("wait ends here...");
}
public static void main(String[] args) {
//Your Code
new WaitTest().waitHere(10);
//Your Code
}
}
Simple use if you want How to execute threads alternatively :-
public class MyThread {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "A");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T1").start();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "B");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T2").start();
}
}
response :-
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
You can easily set a pandas.DataFrame column to a constant. This constant can be an int such as in your example. If the column you specify isn't in the df, then pandas will create a new column with the name you specify. So after your dataframe is constructed, (from your question):
df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])
You can just run:
df['s1'], df['s2'] = 5, 6
You could write a loop or comprehension to make it do this for all the elements in a list of tuples, or keys and values in a dictionary depending on how you have your real data stored.
Given the declarations
char *s0 = "hello world";
char s1[] = "hello world";
assume the following hypothetical memory map:
0x01 0x02 0x03 0x04 0x00008000: 'h' 'e' 'l' 'l' 0x00008004: 'o' ' ' 'w' 'o' 0x00008008: 'r' 'l' 'd' 0x00 ... s0: 0x00010000: 0x00 0x00 0x80 0x00 s1: 0x00010004: 'h' 'e' 'l' 'l' 0x00010008: 'o' ' ' 'w' 'o' 0x0001000C: 'r' 'l' 'd' 0x00
The string literal "hello world"
is a 12-element array of char
(const char
in C++) with static storage duration, meaning that the memory for it is allocated when the program starts up and remains allocated until the program terminates. Attempting to modify the contents of a string literal invokes undefined behavior.
The line
char *s0 = "hello world";
defines s0
as a pointer to char
with auto storage duration (meaning the variable s0
only exists for the scope in which it is declared) and copies the address of the string literal (0x00008000
in this example) to it. Note that since s0
points to a string literal, it should not be used as an argument to any function that would try to modify it (e.g., strtok()
, strcat()
, strcpy()
, etc.).
The line
char s1[] = "hello world";
defines s1
as a 12-element array of char
(length is taken from the string literal) with auto storage duration and copies the contents of the literal to the array. As you can see from the memory map, we have two copies of the string "hello world"
; the difference is that you can modify the string contained in s1
.
s0
and s1
are interchangeable in most contexts; here are the exceptions:
sizeof s0 == sizeof (char*)
sizeof s1 == 12
type of &s0 == char **
type of &s1 == char (*)[12] // pointer to a 12-element array of char
You can reassign the variable s0
to point to a different string literal or to another variable. You cannot reassign the variable s1
to point to a different array.
"Class has two properties of the same name exception" can happen when you have a class member x with a public access level and a getter/setter for the same member.
As a java rule of thumb, it is not recommended to use a public access level together with getters and setters.
Check this for more details: Public property VS Private property with getter?
To fix that:
You can extend the abstract class with an anonymous class in your test. For example (using Junit 4):
private AbstractClassName classToTest;
@Before
public void preTestSetup()
{
classToTest = new AbstractClassName() { };
}
// Test the AbstractClassName methods.
You can also use a regular expression as a field separator. The following will print "bar" by using a regular expression to set the number "10" as a separator.
echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'
I 'tripped' across my solution after 2 days...XCODE 4.0
I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various versions...so if you are having problems, you are not alone.
I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!
--bottom line---
If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...
Figure: This shows how to find the relevant settings in XCode 4.5.
try this:
Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
intent = getIntent();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_b, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpTo(this,intent);
return true;
}
return super.onOptionsItemSelected(item);
}
Since Java 9, it is possible to use Map.of(...)
, like so:
Map<String, Integer> immutableMap = Map.of("One", 1,
"Two", 2,
"Three", 3);
This map is immutable. If you want the map to be mutable, you have to add:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.
In Info.plist set 'View controller-based status bar appearance' as NO
In AppDelegate add
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
growthRates is a sequence ([3,4,5,0,3]
). You can't multiply that sequence by a float (0.1). It looks like what you wanted to put there was i
.
Incidentally, i
is not a great name for that variable. Consider something more descriptive, like growthRate
or rate
.
You are likely running the Mac default (/usr/bin/python) which has an older version of numpy installed in the system folders. The easiest way to get python working with opencv is to use brew to install both python and opencv into /usr/local and run the /usr/local/bin/python.
brew install python
brew tap homebrew/science
brew install opencv
So you really want:
for each tweet
unless tweet is in db
insert tweet
If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.
What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.
As a general (see Stackblitz here: https://stackblitz.com/edit/angular-gh2rjx):
HTML
<select [(ngModel)]="selectedOption">
<option *ngFor="let o of options">
{{o.name}}
</option>
</select>
<button (click)="print()">Click me</button>
<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>
Typescript
export class AppComponent {
selectedOption: string;
printedOption: string;
options = [
{ name: "option1", value: 1 },
{ name: "option2", value: 2 }
]
print() {
this.printedOption = this.selectedOption;
}
}
In your specific case you can use ngModel like this:
<form class="form-inline" (ngSubmit)="HelloCorp()">
<div class="select">
<select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
<option *ngFor="let corporation of corporations"></option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
HelloCorp() {
console.log("My input: ", corporationObj);
}
Try this below code
<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>
This may help:
public string NonBlankValueOf(string strTestString)
{
return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}
You can get the filecount like so:
$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
$filecount = count($files);
}
echo "There were $filecount files";
where the "*"
is you can change that to a specific filetype if you want like "*.jpg"
or you could do multiple filetypes like this:
glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)
the GLOB_BRACE
flag expands {a,b,c} to match 'a', 'b', or 'c'
I found a better solutions in following link. Only use "object-fit" https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87
You can make an extension of UIImageView.
Swift 2.0
import Foundation
import UIKit
extension UIImageView
{
func makeBlurImage(targetImageView:UIImageView?)
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = targetImageView!.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
targetImageView?.addSubview(blurEffectView)
}
}
Usage:
override func viewDidLoad()
{
super.viewDidLoad()
let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
let sampleImage:UIImage = UIImage(named: "ic_120x120")!
sampleImageView.image = sampleImage
//Convert To Blur Image Here
sampleImageView.makeBlurImage(sampleImageView)
self.view.addSubview(sampleImageView)
}
Swift 3 Extension
import Foundation
import UIKit
extension UIImageView
{
func addBlurEffect()
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
self.addSubview(blurEffectView)
}
}
Usage:
yourImageView.addBlurEffect()
Addendum:
extension UIView {
/// Remove UIBlurEffect from UIView
func removeBlurEffect() {
let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
blurredEffectViews.forEach{ blurView in
blurView.removeFromSuperview()
}
}
Swift 5.0:
import UIKit
extension UIImageView {
func applyBlurEffect() {
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(blurEffectView)
}
}
If you have a string, parse it as an integer:
var num = '20.536';
var result = parseInt(num, 10); // 20
If you have a number, ECMAScript 6 offers Math.trunc
for completely consistent truncation, already available in Firefox 24+ and Edge:
var num = -2147483649.536;
var result = Math.trunc(num); // -2147483649
If you can’t rely on that and will always have a positive number, you can of course just use Math.floor
:
var num = 20.536;
var result = Math.floor(num); // 20
And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0
is common, and >>> 0
can be used to obtain an unsigned 32-bit integer:
var num = -20.536;
var result = num | 0; // -20
My case on Ubuntu 14.04.2 LTS was similar to others with my.cnf, but for me the cause was a ~/.my.cnf that was leftover from a previous installation. After deleting that file and purging/re-installing mysql-server, it worked fine.
We should first read the documentation on proxy_pass carefully and fully.
The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /
. Absense of trailing slash means hat URI is absent.
Proxy_pass with URI:
location /some_dir/ {
proxy_pass http://some_server/;
}
With the above, there's the following proxy:
http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/ some_subdir/some_file
Basically, /some_dir/
gets replaced by /
to change the request path from /some_dir/some_subdir/some_file
to /some_subdir/some_file
.
Proxy_pass without URI:
location /some_dir/ {
proxy_pass http://some_server;
}
With the second (no trailing slash): the proxy goes like this:
http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file
Basically, the full original request path gets passed on without changes.
So, in your case, it seems you should just drop the trailing slash to get what you want.
Caveat
Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:
location /some_dir/ {
rewrite /some_dir/(.*) /$1 break;
proxy_pass $upstream_server;
}
There are other cases where rewrite wouldn't work, that's why reading documentation is a must.
Reading your question again, it seems I may have missed that you just want to edit the html output.
For that, you can use the sub_filter directive. Something like ...
location /admin/ {
proxy_pass http://localhost:8080/;
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Basically, the string you want to replace and the replacement string
You can use the synchronizedCollection/List method in java.util.Collection
to get a thread-safe collection from a non-thread-safe one.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
it seems you can directly call:
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g._legend.set_bbox_to_anchor((.7, 1.1))
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):
Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If sender.name = "radioFit_Components" And sender.visible Then
If sender.checked Then
For Each ctrl As Control In TabControl1.SelectedTab.Controls
Select Case ctrl.Name
Case "embChartSSE_Components"
ctrl.BringToFront()
Case "embChartSSE_Fit_Curve"
ctrl.SendToBack()
Case "dgvFit_Components"
ctrl.BringToFront()
End Select
Next
End If
End If
End Sub
This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.
Found 2 issues in our case.
The Memory was halting and we where mandatory to set the startup perm size to higher value. I guess it was using memory faster then able to allocate it. In our case. -XX:PermSize=256m -XX:MaxPermSize=256m
We are using Clearcase and the plugin from Rational Clearcase SCM (7.0.0.2) was used in Eclipse. The plugin was the case of why Eclipse crashed. And at the moment we do not know why, but could be good to know for others. Was forced to disable it.
Try this,
<?php if ( ($cart->count_product) > 0) { ?>
<div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else {
print '';
} ?>
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
from selenium.webdriver.firefox.options import Options
if __name__ == "__main__":
options = Options()
options.add_argument('-headless')
driver = Firefox(executable_path='geckodriver', firefox_options=options)
wait = WebDriverWait(driver, timeout=10)
driver.get('http://www.google.com')
Tested, works as expected and this is from Official - Headless Mode | Mozilla
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
Another suggestion, Let's say you have two same words in the String
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
replace function will change every string is given in the first parameter to the second parameter
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
and you can use also replaceAll method for the same result
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
if you want to change just the first string which is positioned earlier,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.
Apart from above information, there is still an interesting history of LF (\n) and CR (\r). [Original author : ??? Source : http://www.ruanyifeng.com/blog/2006/04/post_213.html] Before computer came out, there was a type of teleprinter called Teletype Model 33. It can print 10 characters each second. But there is one problem with this, after finishing printing each line, it will take 0.2 second to move to next line, which is time of printing 2 characters. If a new characters is transferred during this 0.2 second, then this new character will be lost.
So scientists found a way to solve this problem, they add two ending characters after each line, one is 'Carriage return', which is to tell the printer to bring the print head to the left.; the other one is 'Line feed', it tells the printer to move the paper up 1 line.
Later, computer became popular, these two concepts are used on computers. At that time, the storage device was very expensive, so some scientists said that it was expensive to add two characters at the end of each line, one is enough, so there are some arguments about which one to use.
In UNIX/Mac and Linux, '\n' is put at the end of each line, in Windows, '\r\n' is put at the end of each line. The consequence of this use is that files in UNIX/Mac will be displayed in one line if opened in Windows. While file in Windows will have one ^M at the end of each line if opened in UNIX or Mac.
If the host is windows 10 then instead of forward slash, use backward slash -
docker run -it -p 12001:80 -v c:\Users\C\Desktop\dockerStorage:/root/sketches
Make sure the host drive is shared (C in this case). In my case I got a prompt asking for share permission after running the command above.
I used:
echo exec('whoami');
to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:
sudo chown -R :username /var/www/html/myapp
Hope this helps someone out there.
The "DECOMPRESSION" test fails on CygWin, one of the most potentiaally useful platforms for it, due to the "grep" check for "xz" being case sensitive. The result of the "COMPRESSION:" check is:
COMPRESSION='/dev/stdin: XZ compressed data'
Simply replacing 'grep -q' with 'grep -q -i' everywhere seems to resolve the issue well.
I've done a few updates, particularly adding some comments and using "case" instead of stacked "if" statements, and included that fix below
#!/bin/sh
#
# rpm2cpio.sh - extract 'cpio' contents of RPM
#
# Typical usage: rpm2cpio.sh rpmname | cpio -idmv
#
if [ "$# -ne 1" ]; then
echo "Usage: $0 file.rpm" 1>&2
exit 1
fi
rpm="$1"
if [ -e "$rpm" ]; then
echo "Error: missing $rpm"
fi
leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "sig il: $il dl: $dl"
sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "hdr il: $il dl: $dl"
hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
EXTRACTOR="dd if=$rpm ibs=$o skip=1"
COMPRESSION=`($EXTRACTOR |file -) 2>/dev/null`
DECOMPRESSOR="cat"
case $COMPRESSION in
*gzip*|*GZIP*)
DECOMPRESSOR=gunzip
;;
*bzip2*|*BZIP2*)
DECOMPRESSOR=bunzip2
;;
*xz*|*XZ*)
DECOMPRESSOR=unxz
;;
*cpio*|*cpio*)
;;
*)
# Most versions of file don't support LZMA, therefore we assume
# anything not detected is LZMA
DECOMPRESSOR="`which unlzma 2>/dev/null`"
case "$DECOMPRESSOR" in
/*)
DECOMPRESSOR="$DECOMPRESSOR"
;;
*)
DECOMPRESSOR=`which lzmash 2>/dev/null`
case "$DECOMPRESSOR" in
/* )
DECOMPRESSOR="lzmash -d -c"
;;
* )
echo "Warning: DECOMPRESSOR not found, assuming 'cat'" 1>&2
;;
esac
;;
esac
esac
$EXTRACTOR 2>/dev/null | $DECOMPRESSOR
Using array or set comparisons:
create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');
select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');
select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));
It is also possible to do an AND
which would not be easy with a regex if it were to match any order:
select str from t
where str like all ('{"%999%", "DDD%"}');
select str from t
where str like all (values('%999%'), ('DDD%'));
You should try HttpAutoindexModule.
Set autoindex option to on
. It is off by default.
Your example configuration should be ok
location /{
root /home/yozloy/html/;
index index.html;
autoindex on;
}
Without autoindex option you should be getting Error 403 for requests that end with /
on directories that do not have an index.html
file. With this option you should be getting a simple listing:
<html>
<head><title>Index of /</title></head>
<body bgcolor="white">
<h1>Index of /test/</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a> 19-May-2012 10:43 0
</pre><hr></body>
</html>
Edit: Updated the listing to delete any references to test
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
A pretty straight forward solution to print binary:
#include <iostream>
using namespace std;
int main()
{
int num,arr[64];
cin>>num;
int i=0,r;
while(num!=0)
{
r = num%2;
arr[i++] = r;
num /= 2;
}
for(int j=i-1;j>=0;j--){
cout<<arr[j];
}
}
It is nice to verify that the code you pushed actually got committed.
You can get a log of changes on a bare repository by explicitly setting the path using the --relative option.
$ cd test_repo
$ git log --relative=/
This will show you the committed changes as if this was a regular git repo.
There is no built-in method that allows what you intend to do.
You have to add a method to your repository, like this:
public function getWhatYouWant()
{
$qb = $this->createQueryBuilder('u');
$qb->where('u.id != :identifier')
->setParameter('identifier', 1);
return $qb->getQuery()
->getResult();
}
Hope this helps.
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
In modern MongoDB releases you can brute force this with $slice
just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push
to an array.
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$project": {
"books": { "$slice": [ "$books", 2 ] },
"count": 1
}}
])
Still not resolving SERVER-9377, but in this release $lookup
allows a new "non-correlated" option which takes an "pipeline"
expression as an argument instead of the "localFields"
and "foreignFields"
options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit
in order to return the "top-n" results.
db.books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"let": {
"addr": "$_id"
},
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr"] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
],
"as": "books"
}}
])
The other addition here is of course the ability to interpolate the variable through $expr
using $match
to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit
each result separately.
This would be the next best option to running parallel queries, and actually would be better if the $match
were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push
" as the referenced issue asks, it actually delivers something that should work better.
You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
])
Now that will give you a result like this:
{
"result" : [
{
"_id" : "address1",
"books" : [
{
"book" : "book4",
"count" : 1
},
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 3
}
],
"count" : 5
},
{
"_id" : "address2",
"books" : [
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 2
}
],
"count" : 3
}
],
"ok" : 1
}
So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.
This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$unwind": "$books" },
{ "$sort": { "count": 1, "books.count": -1 } },
{ "$group": {
"_id": "$_id",
"books": { "$push": "$books" },
"count": { "$first": "$count" }
}},
{ "$project": {
"_id": {
"_id": "$_id",
"books": "$books",
"count": "$count"
},
"newBooks": "$books"
}},
{ "$unwind": "$newBooks" },
{ "$group": {
"_id": "$_id",
"num1": { "$first": "$newBooks" }
}},
{ "$project": {
"_id": "$_id",
"newBooks": "$_id.books",
"num1": 1
}},
{ "$unwind": "$newBooks" },
{ "$project": {
"_id": "$_id",
"num1": 1,
"newBooks": 1,
"seen": { "$eq": [
"$num1",
"$newBooks"
]}
}},
{ "$match": { "seen": false } },
{ "$group":{
"_id": "$_id._id",
"num1": { "$first": "$num1" },
"num2": { "$first": "$newBooks" },
"count": { "$first": "$_id.count" }
}},
{ "$project": {
"num1": 1,
"num2": 1,
"count": 1,
"type": { "$cond": [ 1, [true,false],0 ] }
}},
{ "$unwind": "$type" },
{ "$project": {
"books": { "$cond": [
"$type",
"$num1",
"$num2"
]},
"count": 1
}},
{ "$group": {
"_id": "$_id",
"count": { "$first": "$count" },
"books": { "$push": "$books" }
}},
{ "$sort": { "count": -1 } }
])
So that will actually give you the top 2 "books" from the top two "address" entries.
But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.
The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await
syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.
index.js
const { MongoClient } = require('mongodb');
const fs = require('mz/fs');
const uri = 'mongodb://localhost:27017';
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const client = await MongoClient.connect(uri);
const db = client.db('bookDemo');
const books = db.collection('books');
let { version } = await db.command({ buildInfo: 1 });
version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);
// Clear and load books
await books.deleteMany({});
await books.insertMany(
(await fs.readFile('books.json'))
.toString()
.replace(/\n$/,"")
.split("\n")
.map(JSON.parse)
);
if ( version >= 3.6 ) {
// Non-correlated pipeline with limits
let result = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"as": "books",
"let": { "addr": "$_id" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr" ] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 },
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]
}}
]).toArray();
log({ result });
}
// Serial result procesing with parallel fetch
// First get top addr items
let topaddr = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray();
// Run parallel top books for each addr
let topbooks = await Promise.all(
topaddr.map(({ _id: addr }) =>
books.aggregate([
{ "$match": { addr } },
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray()
)
);
// Merge output
topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
log({ topaddr });
client.close();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
books.json
{ "addr": "address1", "book": "book1" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book5" }
{ "addr": "address3", "book": "book9" }
{ "addr": "address2", "book": "book5" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book1" }
{ "addr": "address15", "book": "book1" }
{ "addr": "address9", "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4", "book": "book3" }
{ "addr": "address5", "book": "book1" }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1", "book": "book1" }
Use sum formula,
class Main {
// Function to ind missing number
static int getMissingNo (int a[], int n) {
int i, total;
total = (n+1)*(n+2)/2;
for ( i = 0; i< n; i++)
total -= a[i];
return total;
}
/* program to test above function */
public static void main(String args[]) {
int a[] = {1,2,4,5,6};
int miss = getMissingNo(a,5);
System.out.println(miss);
}
}
Reference http://www.geeksforgeeks.org/find-the-missing-number/
You can use URLConnection
with setDoOutput
(true)
, getOutputStream()
(for sending data), and getInputStream()
(for receiving). Sun has an example for exactly this.
I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.
ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).
I'm still trying to find a way around this. If anyone has any input, it's most welcome.
It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have ==
in there. You can make the warning go away by adding another set of parentheses:
while ((list = list->next))
I also had same problem then I found this on there documentation page
So if you want to create a project by name of test_laravel
in directory /Applications/MAMP/htdocs/
then what you need to do is
go to your project parent directory
cd /Applications/MAMP/htdocs
and fire this command
composer create-project laravel/laravel test_laravel --prefer-dist
that's it, this is really easy and it also creates Application Key automatically for you
With Bootstrap 4, there is a css class specifically for this. The below will center row content:
<div class="row justify-content-center">
...inner divs and content...
</div>
See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.
First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like
sqlCommand.Transaction = transaction;
And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like
sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
randomNumber function return unqiue integer value between 0 to 100000
bool check[] = new bool[100001]; Random r = new Random(); public int randomNumber() { int num = r.Next(0,100000); while(check[num] == true) { num = r.Next(0,100000); } check[num] = true; return num; }
A very old thread, I know. - but for completeness:
I use <span class="bold">my text</span>
as I upload the four font styles: normal; bold; italic and bold italic into my web-site via css.
I feel the resulting output is better than simply modifying a font and is closer to the designers intention of how the boldened font should look.
The same applies for italic and bolditalic of course, which gives me additional flexibility.
Adding a directory to subversion, and ignoring the directory contents
svn propset svn:ignore '\*.*' .
or
svn propset svn:ignore '*' .
I think this drop shadow value is good for most cases:
<solid android:color="#20000000" />
let nietos = [];
function nieto(aData) {
let o = {};
for ( let i = 0; i < aData.length; i++ ) {
let key = "0" + (i + 1);
o[key] = aData[i];
}
nietos.push(o);
}
nieto( ["Band", "Ramones"] );
nieto( ["Style", "RockPunk"] );
nieto( ["", "", "", "Another String"] );
/* convert array of object into string json */
var jsonString = JSON.stringify(nietos);
document.write(jsonString);
_x000D_
I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient
Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))
Hope it helps! Cheers.
I ran into the same issue and then I noticed that I had a different domain for the og:url
Once I made sure that the domain was the same for og:url
and og:image
it worked.
Hope this helps.
declare @p varbinary(max)
set @p = 0x
declare @local table (col text)
SELECT @p = @p + 0x3B + CONVERT(varbinary(100), Email)
FROM tbCarsList
where email <> ''
group by email
order by email
set @p = substring(@p, 2, 100000)
insert @local values(cast(@p as varchar(max)))
select DATALENGTH(col) as collen, col from @local
result collen > 8000, length col value is more than 8000 chars
I'm adding this because it's not mentioned in any of the other answers. You can give a container a specific hostname at runtime with the -h directive.
docker run -h=my.docker.container.example.com ubuntu:latest
You can use backticks (or whatever equivalent your shell uses) to get the output of hosthame into the -h argument.
docker run -h=`hostname` ubuntu:latest
There is a caveat, the value of hostname will be taken from the host you run the command from, so if you want the hostname of a virtual machine that's running your docker container then using hostname as an argument may not be correct if you are using the host machine to execute docker commands on the virtual machine.
If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:
When setting elem.contentEditable
you can use either the boolean false
or the string "false"
. But when you set elem.spellcheck
, you can only use the boolean - for some reason. Your options are thus:
elem.spellcheck = false;
Or the option Mac provided in his answer:
elem.setAttribute("spellcheck", "false"); // Both string and boolean work here.
App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.
As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.
This should produce a fade effect for you in these browsers:
a {_x000D_
background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
background-color: #AD310B;_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
Note: As pointed out by Gerald in the comments, if you put the transition on the a
, instead of on a:hover
it will fade back to the original color when your mouse moves away from the link.
This might come in handy, too: CSS Fundamentals: CSS 3 Transitions
You need to define height of ul or your div and set overflow equals to auto as below:
<ul style="width: 300px; height: 200px; overflow: auto">
<li>text</li>
<li>text</li>
git fsck --unreachable | grep commit
should show the sha1, although the list it returns might be quite large. git show <sha1>
will show if it is the commit you want.
git cherry-pick -m 1 <sha1>
will merge the commit onto the current branch.
Watch out using Crypto!!!
It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py
line 77 changing t = time.clock()
int t = time.perf_counter()
While in insert mode, you can use Ctrl-R {register}
, where register can be:
+
for the clipboard,*
for the X clipboard (last selected text in X), "
for the unnamed register (last delete or yank in Vim),:h registers
).Ctrl-R {register}
inserts the text as if it were typed.
Ctrl-R Ctrl-O {register}
inserts the text with the original indentation.
Ctrl-R Ctrl-P {register}
inserts the text and auto-indents it.
Ctrl-O
can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p
can also be used, for example.
For more information, view the documentation with :h i_ctrl-r
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
In simple words
$.ajax("info.txt").done(function(data) {
alert(data);
}).fail(function(data){
alert("Try again champ!");
});
if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.
I have struggled with the matplotlib trimming methods, so I've now just made a function to do this via a bash
call to ImageMagick
's mogrify command, which works well and gets all extra white space off the figure's edge. This requires that you are using UNIX/Linux, are using the bash
shell, and have ImageMagick
installed.
Just throw a call to this after your savefig()
call.
def autocrop_img(filename):
'''Call ImageMagick mogrify from bash to autocrop image'''
import subprocess
import os
cwd, img_name = os.path.split(filename)
bashcmd = 'mogrify -trim %s' % img_name
process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)
Firefox Proxy: JAVA
String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)setFtpProxy(PROXY).setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:
<input type="radio" name="name" onclick="javascript: return false;" />
You need to group by the duplicate records according to the field(s), then hold one of the records and delete the rest. For example:
DELETE prg.Person WHERE Id IN (
SELECT dublicateRow.Id FROM
(
select MIN(Id) MinId, NationalCode
from prg.Person group by NationalCode having count(NationalCode ) > 1
) GroupSelect
JOIN prg.Person dublicateRow ON dublicateRow.NationalCode = GroupSelect.NationalCode
WHERE dublicateRow.Id <> GroupSelect.MinId)
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
This should work
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and moreover please let us know why are you importing all these class
<%@ page import="com.library.controller.*"%>
<%@ page import="com.library.dao.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.util.Date" %>
We don't need to include java.lang as it is the default package.
You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array
$object = array_shift($array);
var_dump($object->id);
Or refer to the thing by its index in the array.
var_dump( $array[0]->id );
Or, if you're not sure how many things are in the array, loop over the array
foreach($array as $key=>$value)
{
var_dump($value->id);
var_dump($array[$key]->id);
}
You may want to keep jquery.js
deferred for faster page load. However, if jquery.js
is deferred the $(window).load
may not work. Then you may try
setTimeout(function(){$('#myModal').modal('show');},3000);
it will popup your modal after page is completely loaded (including jquery)
__all__
affects how from foo import *
works.
Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*
) in a from
statement:
from foo import *
The *
requests that all attributes of module foo
(except those beginning with underscores) be bound as global variables in the importing module. When foo
has an attribute __all__
, the attribute's value is the list of the names that are bound by this type of from
statement.
If foo
is a package and its __init__.py
defines a list named __all__
, it is taken to be the list of submodule names that should be imported when from foo import *
is encountered. If __all__
is not defined, the statement from foo import *
imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py
.
Note that __all__
doesn't have to be a list. As per the documentation on the import
statement, if defined, __all__
must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:
__all__ = ('some_name',)
See also Why is “import *” bad?
From Wikipedia,
A database management system (DBMS) is a computer software application that interacts with the user, other applications, and the database itself to capture and analyze data. A general-purpose DBMS is designed to allow the definition, creation, querying, update, and administration of databases.
There are different types of DBMS products: relational, network and hierarchical
. The most widely commonly used type of DBMS today is the Relational Database Management Systems (RDBMS
)
DBMS:
RDBMS:
Have a look at this article for more details.
This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.
My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.
The supports
method makes sure that all requests that were handled by the StringHttpMessageConverter
(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite
method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).
@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
converterType === StringHttpMessageConverter::class.java
override fun beforeBodyWrite(
body: Any?,
returnType: MethodParameter,
selectedContentType: MediaType,
selectedConverterType: Class<out HttpMessageConverter<*>>,
request: ServerHttpRequest,
response: ServerHttpResponse
): Any? {
return if (request.uri.path.contains("api")) {
response.getHeaders().contentType = MediaType.APPLICATION_JSON
ob.writeValueAsString(body)
} else body
}
}
I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter
should be used for the output.
In general, if you are using white-space: nowrap;
it is probably because you know which columns are going to contain content which wraps (or stretches the cell). For those columns, I generally wrap the cell's contents in a span
with a specific class
attribute and apply a specific width
.
Example:
HTML:
<td><span class="description">My really long description</span></td>
CSS:
span.description {
display: inline-block;
overflow: hidden;
white-space: nowrap;
width: 150px;
}
I am assuming you want to pass the database name as a parameter and not just run:
SELECT *
FROM DBName.sys.tables
WHERE Name LIKE '%XXX%'
If so, you could use dynamic SQL to add the dbname to the query:
DECLARE @DBName NVARCHAR(200) = 'YourDBName',
@TableName NVARCHAR(200) = 'SomeString';
IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
BEGIN
PRINT 'DATABASE NOT FOUND';
RETURN;
END;
DECLARE @SQL NVARCHAR(MAX) = ' SELECT Name
FROM ' + QUOTENAME(@DBName) + '.sys.tables
WHERE Name LIKE ''%'' + @Table + ''%''';
EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
You can tweak the string to split by - if you use "code : "
, the second member of the returned array ([1]
) will contain "-1"
, using your example.
Similar setup here and looks like it was just a bug in my code. At the start of my app I looked for the offending URL and this worked: echo '<html>test</html>'; exit();
In my case, turns out the problem was an uninitialized variable that only failed under peculiar circumstances.
IIRC ...
setSize
sets the size of the component.
setPreferredSize
sets the preferred size.
The Layoutmanager will try to arrange that much space for your component.
It depends on whether you're using a layout manager or not ...
DB Browser for SQLite allows you to add or drop columns.
In the main view, tab Database Structure, click on the table name. A button Modify Table gets enabled, which opens a new window where you can select the column/field and remove it.
This worked for me:
#!/bin/bash
#Variables
FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv
SFTPHOSTNAME="myHost.com"
SFTPUSERNAME="myUser"
SFTPPASSWORD="myPass"
FOLDER="myFolderIfNeeded"
FILEREMOTE="fileNameRemote"
#SFTP CONNECTION
sshpass -p $SFTPPASSWORD sftp $SFTPUSERNAME@$SFTPHOSTNAME << !
cd $FOLDER
get $FILEREMOTE $FILELOCAL
ls
bye
!
Probably you have to install sshpass:
sudo apt-get install sshpass
The following code will work for google apiv2:
public void convertAddress() {
if (address != null && !address.isEmpty()) {
try {
List<Address> addressList = geoCoder.getFromLocationName(address, 1);
if (addressList != null && addressList.size() > 0) {
double lat = addressList.get(0).getLatitude();
double lng = addressList.get(0).getLongitude();
}
} catch (Exception e) {
e.printStackTrace();
} // end catch
} // end if
} // end convertAddress
Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.
In short, place black behind the image, and lower the opactiy. You can do this by wrapping the image within a div, and then lowering the opacity of the image.
For example:
<!DOCTYPE html>
<style>
.img-wrap {
background: black;
display: inline-block;
line-height: 0;
}
.img-wrap > img {
opacity: 0.8;
}
</style>
<div class="img-wrap">
<img src="http://mikecane.files.wordpress.com/2007/03/kitten.jpg" />
</div>
Here is a JSFiddle.
Also we can just kill git process. I receive the same issue via GUI app for git, something goes wrong and git makes some work infinitely. Killing process will freeze application that works with git, just restart it and everything will be ok.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void LnKB_Click(object sender, System.EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
int x = clickedRow.RowIndex;
int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
lbl.Text = yourgridviewname.Rows[x].Cells[2].Text;
}
If sql server is installed on your machine, you should check
Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Services You'll see "SQL Server (MSSQLSERVER)"
Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> TCP/IP Make sure it's using port number 1433
If you want to see if the port is open and listening try this from your command prompt... telnet 127.0.0.1 1433
And yes, SQL Express installs use localhost\SQLEXPRESS as the instance name by default.
During Tensorflow configuration I specified python3.6. But default python on my system is python2.7. Thus pip in my case means pip for 2.7. For me
pip3 install /tmp/tensorflow_pkg/NAME.whl
did the trick.
You just did, as long as your table contains two columns and is called something like 'tblPeople'.
You can always write your own SQL wrappers. I actually prefer to do it that way, I HATE generated code, in any fashion.
Maybe create a DAL
class, and have a method called GetPerson(int id)
, that queries the database for that person, and then creates your Person
object from the result set.
simple one-liner starts with a default min-height and increases to contents size.
<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
_x000D_
This is (of course) totally VM-dependent.
Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList
, .Hashtable
, .AbstractCollection
, .PriorityQueue
, and .Vector
, you can see this claim being repeated:
/** * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).
So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8
) and "attempts to allocate larger arrays may result in OutOfMemoryError".
(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
which shows that MAX_ARRAY_SIZE
does not yet have a real use.)
In my case the function throwing error was async so I followed here:
await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);
you can saperate string using the below code
String thisString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
I just use @csrf inside the form and its working fine
Summary:
PagingAndSortingRepository extends CrudRepository
JpaRepository extends PagingAndSortingRepository
The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.
The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.
Finally the JpaRepository add some more functionality that is specific to JPA.
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
The practical use of this construct? It is a javascript replaceAll() on strings.
var s = 'stackoverflow_is_cool';
s = s.split('_').join(' ');
console.log(s);
will output:
stackoverflow is cool
A different solution (not using xaml but still quite clean I think).
class ReturnKeyTextBox : TextBox
{
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (e.Key == Key.Return)
GetBindingExpression(TextProperty).UpdateSource();
}
}
Go offline
USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
Go online
USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO
Just put the following code on the top of the page
@{
Layout = "";
}
I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.
If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar
, which is available in SQLLIB/java/
folder of your db2 installation.
Since you've already received help on the query, I'll take a poke at your syntax question:
The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join
and on
clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.
Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:
select
count(*)
from Table1 as t1
join Table2 as t2
join Table3 as t3
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:
select
count(*)
from Table1 as t1
join Table3 as t3
join Table2 as t2
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.
Looks like TaskCache registry data is in ...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache
... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See @Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
I implemented the following and it works well. Basically, I set the body dimensions according to the size of the iFrame content. It does mean that our non-iFrame menu can be scrolled off the screen, but otherwise, this makes our sites functional with iPad and iPhone. "workbox" is the ID of our iFrame.
// Configure for scrolling peculiarities of iPad and iPhone
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
document.body.style.width = "100%";
document.body.style.height = "100%";
$("#workbox").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#workbox").contents().width();
if (iframeWidth > 400)
document.body.style.width = (iframeWidth + 182) + 'px';
iframeHeight = $("#workbox").contents().height();
if (iframeHeight>200)
document.body.style.height = iframeHeight + 'px';
});
}
Since you're accessing a web.config
you should probably use
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<systemPropertyVariables>
<java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
<log4j.configuration>log4j-core.properties</log4j.configuration>
</systemPropertyVariables>
</configuration>
</plugin>
http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html
In case if you don't have a fixed format for the address as mentioned above, I would use regex expression just to eliminate the symbols which are not used in the address (like specialized sybmols - &(%#$^). Result would be:
[A-Za-z0-9'\.\-\s\,]
We can use the new fs.promises API
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
Here's how you would detect if a path is a file or a directory asynchronously, which is the recommended approach in node. using fs.lstat
const fs = require("fs");
let path = "/path/to/something";
fs.lstat(path, (err, stats) => {
if(err)
return console.log(err); //Handle error
console.log(`Is file: ${stats.isFile()}`);
console.log(`Is directory: ${stats.isDirectory()}`);
console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
console.log(`Is FIFO: ${stats.isFIFO()}`);
console.log(`Is socket: ${stats.isSocket()}`);
console.log(`Is character device: ${stats.isCharacterDevice()}`);
console.log(`Is block device: ${stats.isBlockDevice()}`);
});
Note when using the synchronous API:
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try{
fs.lstatSync("/some/path").isDirectory()
}catch(e){
// Handle error
if(e.code == 'ENOENT'){
//no such file or directory
//do something
}else {
//do something else
}
}
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):
Run man tcpdump | less -Ip examples
to see some examples
Here’s a tcpdump filter for HTTP GET (GET
= 0x47
, 0x45
, 0x54
, 0x20
):
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
Here’s a tcpdump filter for HTTP POST (POST
= 0x50
, 0x4f
, 0x53
, 0x54
):
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
Monitor HTTP traffic including request and response headers and message body (source):
tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).
You should grab the standard input of the su
process just launched and write down the command there, otherwise you are running the commands with the current UID
.
Try something like this:
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
throw new Exception(e);
}catch(InterruptedException e){
throw new Exception(e);
}
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
assertEquals(res,b);
}
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String
, and you declare enums with TEST("test")
I have exactly the same problem. I haven't found a solution anywhere, but I have been able to fix it without rebooting by simply unmounting and remounting the mountpoint.
For your system the commands would be:
fusermount -uz /data
mount /data
The -z
forces the unmount, which solved the need to reboot for me. You may need to do this as sudo
depending on your setup. You may encounter the below error if the command does not have the required elevated permissions:
fusermount: entry for /data not found in /etc/mtab
I'm using Ubuntu 14.04 LTS, with the current version of mhddfs
.
If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.
The only way I though of to do that was to create a temporary vector3
and pretend to do a set_intersection
by adding all elements of vector1
to it, then doing a search for each individual element of vector2
in vector3
and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.
Really, though, just sort them first.
Use File.ReadAllText(path_to_file)
to read
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
To avoid 'Unclosed block: CssSyntaxError' errors being thrown from sass compilers add a ';' to the end of @content.
@mixin placeholder {
::-webkit-input-placeholder { @content;}
:-moz-placeholder { @content;}
::-moz-placeholder { @content;}
:-ms-input-placeholder { @content;}
}
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
When using row and column groups both, I had an issue where the colors would alternate between the columns even though it was the same row. I resolved this by using a global variable that alternates only when the row changes:
Public Dim BGColor As String = "#ffffff"
Function AlternateColor() As String
If BGColor = "#cccccc" Then
BGColor = "#ffffff"
Return "#cccccc"
Else
BGColor = "#cccccc"
Return "#ffffff"
End If
End Function
Now, in the first column of the row you want to alternate, set the color expression to:
=Code.AlternateColor()
-
In the remaining columns, set them all to:
=Code.BGColor
This should make the colors alternate only after the first column is drawn.
This may (unverifiably) improve performance, too, since it does not need to do a math computation for each column.
Which types to use in order to accomplish this in Java?
The short answer is a long
. Now, more on how to measure...
The "traditional" way to do this is indeed to use System.currentTimeMillis()
:
long startTime = System.currentTimeMillis();
// ... do something ...
long estimatedTime = System.currentTimeMillis() - startTime;
Note that Commons Lang has a StopWatch class that can be used to measure execution time in milliseconds. It has methods methods like split()
, suspend()
, resume()
, etc that allow to take measure at different points of the execution and that you may find convenient. Have a look at it.
You may prefer to use System.nanoTime()
if you are looking for extremely precise measurements of elapsed time. From its javadoc:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
Another option would be to use JAMon, a tool that gathers statistics (execution time, number of hit, average execution time, min, max, etc) for any code that comes between start() and stop() methods. Below, a very simple example:
import com.jamonapi.*;
...
Monitor mon=MonitorFactory.start("myFirstMonitor");
...Code Being Timed...
mon.stop();
Check out this article on www.javaperformancetunning.com for a nice introduction.
Finally, if you don't want to clutter your code with these measurement (or if you can't change existing code), then AOP would be a perfect weapon. I'm not going to discuss this very deeply but I wanted at least to mention it.
Below, a very simple aspect using AspectJ and JAMon (here, the short name of the pointcut will be used for the JAMon monitor, hence the call to thisJoinPoint.toShortString()
):
public aspect MonitorAspect {
pointcut monitor() : execution(* *.ClassToMonitor.methodToMonitor(..));
Object arround() : monitor() {
Monitor monitor = MonitorFactory.start(thisJoinPoint.toShortString());
Object returnedObject = proceed();
monitor.stop();
return returnedObject;
}
}
The pointcut definition could be easily adapted to monitor any method based on the class name, the package name, the method name, or any combination of these. Measurement is really a perfect use case for AOP.
If anybody decides to use replace
, you should try r'\n'
instead '\n'
mystring = mystring.replace(r'\n', ' ').replace(r'\r', '')
This is a good way to do it:
<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' ||
$_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.
I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.
export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT
sudo apt-get install openjdk-8-jdk
Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address
cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip
Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.
PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin
This had no effect for me, hence the next step
cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin
yes | sudo sdkmanager --licenses
Finally, run this inside your project
sudo ./gradlew assembleDebug
This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.
https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40
Android Command line tools sdkmanager always shows: Warning: Could not create settings
"Failed to install the following Android SDK packages as some licences have not been accepted" error
https://developer.android.com/studio/build/building-cmdline#sign_cmdline
In your route configuration you typically define a route like,
.when('somewhere/:param1/:param2')
You can then either get the route in the resolve object by using $route.current.params
or in a controller, $routeParams
. In either case the parameters is extracted using the mapping of the route, so param1
can be accessed by $routeParams.param1
in the controller.
Edit: Also note that the mapping has to be exact
/some/folder/:param1
Will only match a single parameter.
/some/folder/:param1/:param2
Will only match two parameters.
This is a bit different then most dynamic server side routes. For example NodeJS (Express) route mapping where you can supply only a single route with X number of parameters.
What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content
is undefined or not since your body is nested inside it like
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
You need not use type to check for undefined, just the strict operator !==
which compares the value by their type as well as value
In order to check for undefined, you can also use the typeof
operator like
typeof nextProps.blog.content != "undefined"
I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.
.divtagABS {
width: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
}
Basically, you use left: 50%, then back it out half of it's width with a negative margin.
First off, always keep this in mind when looking for text in the DOM.
This issue will make you pay attention to the structure of your XML / HTML.
In this pure JavaScript example, I account for the possibility of multiple text nodes that could be interleaved with other kinds of nodes. However, initially, I do not pass judgment on whitespace, leaving that filtering task to other code.
In this version, I pass a NodeList
in from the calling / client code.
/**
* Gets strings from text nodes. Minimalist. Non-robust. Pre-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
var trueTarget = target - 1,
length = nodeList.length; // Because you may have many child nodes.
for (var i = 0; i < length; i++) {
if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
return nodeList[i].nodeValue; // Done! No need to keep going.
}
}
return null;
}
Of course, by testing node.hasChildNodes()
first, there would be no need to use a pre-test for
loop.
/**
* Gets strings from text nodes. Minimalist. Non-robust. Post-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
var trueTarget = target - 1,
length = nodeList.length,
i = 0;
do {
if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
return nodeList[i].nodeValue; // Done! No need to keep going.
}
i++;
} while (i < length);
return null;
}
Here the function getTextById()
uses two helper functions: getStringsFromChildren()
and filterWhitespaceLines()
.
getStringsFromChildren()
/**
* Collects strings from child text nodes.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @version 7.0
* @param parentNode An instance of the Node interface, such as an Element. object.
* @return Array of strings, or null.
* @throws TypeError if the parentNode is not a Node object.
*/
function getStringsFromChildren(parentNode)
{
var strings = [],
nodeList,
length,
i = 0;
if (!parentNode instanceof Node) {
throw new TypeError("The parentNode parameter expects an instance of a Node.");
}
if (!parentNode.hasChildNodes()) {
return null; // We are done. Node may resemble <element></element>
}
nodeList = parentNode.childNodes;
length = nodeList.length;
do {
if ((nodeList[i].nodeType === Node.TEXT_NODE)) {
strings.push(nodeList[i].nodeValue);
}
i++;
} while (i < length);
if (strings.length > 0) {
return strings;
}
return null;
}
filterWhitespaceLines()
/**
* Filters an array of strings to remove whitespace lines.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param textArray a String associated with the id attribute of an Element.
* @return Array of strings that are not lines of whitespace, or null.
* @throws TypeError if the textArray param is not of type Array.
*/
function filterWhitespaceLines(textArray)
{
var filteredArray = [],
whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.
if (!textArray instanceof Array) {
throw new TypeError("The textArray parameter expects an instance of a Array.");
}
for (var i = 0; i < textArray.length; i++) {
if (!whitespaceLine.test(textArray[i])) { // If it is not a line of whitespace.
filteredArray.push(textArray[i].trim()); // Trimming here is fine.
}
}
if (filteredArray.length > 0) {
return filteredArray ; // Leave selecting and joining strings for a specific implementation.
}
return null; // No text to return.
}
getTextById()
/**
* Gets strings from text nodes. Robust.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param id A String associated with the id property of an Element.
* @return Array of strings, or null.
* @throws TypeError if the id param is not of type String.
* @throws TypeError if the id param cannot be used to find a node by id.
*/
function getTextById(id)
{
var textArray = null; // The hopeful output.
var idDatatype = typeof id; // Only used in an TypeError message.
var node; // The parent node being examined.
try {
if (idDatatype !== "string") {
throw new TypeError("The id argument must be of type String! Got " + idDatatype);
}
node = document.getElementById(id);
if (node === null) {
throw new TypeError("No element found with the id: " + id);
}
textArray = getStringsFromChildren(node);
if (textArray === null) {
return null; // No text nodes found. Example: <element></element>
}
textArray = filterWhitespaceLines(textArray);
if (textArray.length > 0) {
return textArray; // Leave selecting and joining strings for a specific implementation.
}
} catch (e) {
console.log(e.message);
}
return null; // No text to return.
}
Next, the return value (Array, or null) is sent to the client code where it should be handled. Hopefully, the array should have string elements of real text, not lines of whitespace.
Empty strings (""
) are not returned because you need a text node to properly indicate the presence of valid text. Returning (""
) may give the false impression that a text node exists, leading someone to assume that they can alter the text by changing the value of .nodeValue
. This is false, because a text node does not exist in the case of an empty string.
Example 1:
<p id="bio"></p> <!-- There is no text node here. Return null. -->
Example 2:
<p id="bio">
</p> <!-- There are at least two text nodes ("\n"), here. -->
The problem comes in when you want to make your HTML easy to read by spacing it out. Now, even though there is no human readable valid text, there are still text nodes with newline ("\n"
) characters in their .nodeValue
properties.
Humans see examples one and two as functionally equivalent--empty elements waiting to be filled. The DOM is different than human reasoning. This is why the getStringsFromChildren()
function must determine if text nodes exist and gather the .nodeValue
values into an array.
for (var i = 0; i < length; i++) {
if (nodeList[i].nodeType === Node.TEXT_NODE) {
textNodes.push(nodeList[i].nodeValue);
}
}
In example two, two text nodes do exist and getStringFromChildren()
will return the .nodeValue
of both of them ("\n"
). However, filterWhitespaceLines()
uses a regular expression to filter out lines of pure whitespace characters.
Is returning null
instead of newline ("\n"
) characters a form of lying to the client / calling code? In human terms, no. In DOM terms, yes. However, the issue here is getting text, not editing it. There is no human text to return to the calling code.
One can never know how many newline characters might appear in someone's HTML. Creating a counter that looks for the "second" newline character is unreliable. It might not exist.
Of course, further down the line, the issue of editing text in an empty <p></p>
element with extra whitespace (example 2) might mean destroying (maybe, skipping) all but one text node between a paragraph's tags to ensure the element contains precisely what it is supposed to display.
Regardless, except for cases where you are doing something extraordinary, you will need a way to determine which text node's .nodeValue
property has the true, human readable text that you want to edit. filterWhitespaceLines
gets us half way there.
var whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.
for (var i = 0; i < filteredTextArray.length; i++) {
if (!whitespaceLine.test(textArray[i])) { // If it is not a line of whitespace.
filteredTextArray.push(textArray[i].trim()); // Trimming here is fine.
}
}
At this point you may have output that looks like this:
["Dealing with text nodes is fun.", "Some people just use jQuery."]
There is no guarantee that these two strings are adjacent to each other in the DOM, so joining them with .join()
might make an unnatural composite. Instead, in the code that calls getTextById()
, you need to chose which string you want to work with.
Test the output.
try {
var strings = getTextById("bio");
if (strings === null) {
// Do something.
} else if (strings.length === 1) {
// Do something with strings[0]
} else { // Could be another else if
// Do something. It all depends on the context.
}
} catch (e) {
console.log(e.message);
}
One could add .trim()
inside of getStringsFromChildren()
to get rid of leading and trailing whitespace (or to turn a bunch of spaces into a zero length string (""
), but how can you know a priori what every application may need to have happen to the text (string) once it is found? You don't, so leave that to a specific implementation, and let getStringsFromChildren()
be generic.
There may be times when this level of specificity (the target
and such) is not required. That is great. Use a simple solution in those cases. However, a generalized algorithm enables you to accommodate simple and complex situations.
Your best bet is to use NET SEND
as documented on Rob van der Woude's site.
Otherwise, you'll need to use an external scripting program. Batch files are really intended to send messages via ECHO
.
Sometimes Your rake tasks doesn't get loaded in console, In that case you can try the following commands
require "rake"
YourApp::Application.load_tasks
Rake::Task["Namespace:task"].invoke
.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:
RangeError: Maximum call stack size exceeded
I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.
use
Objective-C
[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];
Swift
headingButton.setTitleColor(.black, for: .normal)
In macOS 10.10+ / iOS 8.0+ (NS)DateComponentsFormatter
has been introduced to create a readable string.
It considers the user's locale und language.
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)
The available unit styles are positional
, abbreviated
, short
, full
, spellOut
and brief
.
For more information please read the documenation.
I would not recommend you to start session just to get some unique id. Instead, use such things as uniqid()
because it's intended to return unique id.
However, if you already have session, then, of course, use session_id()
to get your session id - but do not rely on that, because "unique id" isn't same as "session id" in common sense: for example, multiple tabs in most browsers will use same process, thus, use same session identifier in result - and, therefore, different connections will have same id. It's your decision about desired behavior, I've mentioned this just to show the difference between session id and unique id.
If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables. Otherwise, definitely make it static.
There are several disadvantages of using a dll. There is additional overhead for loading and unloading it. There is also an additional dependency. If you change the dll to make it incompatible with your executalbes, they will stop working. On the other hand, if you change a static library, your compiled executables using the old version will not be affected.
@bogatron has it right, you can use where
, it's worth noting that you can do this natively in pandas:
df1 = df.where(pd.notnull(df), None)
Note: this changes the dtype of all columns to object
.
Example:
In [1]: df = pd.DataFrame([1, np.nan])
In [2]: df
Out[2]:
0
0 1
1 NaN
In [3]: df1 = df.where(pd.notnull(df), None)
In [4]: df1
Out[4]:
0
0 1
1 None
Note: what you cannot do recast the DataFrames dtype
to allow all datatypes types, using astype
, and then the DataFrame fillna
method:
df1 = df.astype(object).replace(np.nan, 'None')
Unfortunately neither this, nor using replace
, works with None
see this (closed) issue.
As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.
However, in this specific case it seems you do (at least at the time of this answer).
Come on guys :) We could do it simpler, by examples:
/this-is-an-endpoint
/another/endpoint
/some/other/endpoint
/login
/accounts
/cart/items
and when put under a domain, it would look like:
https://example.com/this-is-an-endpoint
https://example.com/another/endpoint
https://example.com/some/other/endpoint
https://example.com/login
https://example.com/accounts
https://example.com/cart/items
Can be either http or https, we use https in the example.
Also endpoint can be different for different HTTP methods, for example:
GET /item/{id}
PUT /item/{id}
would be two different endpoints - one for retrieving (as in "cRud" abbreviation), and the other for updating (as in "crUd")
And that's all, really that simple!
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
Here is a simple function to convert csv to html table using php:
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table>';
//display header row if true
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
One can call this function like jj_readcsv('image_links.csv',true);
if second parameter is true then the first row of csv will be taken as header/title.
Hope this helps somebody. Please comment for any flaws in this code.
If your PHP app is holding open many SQL Server connections, then, as you may know, you have a problem with your app's database code. It should be releasing/disposing those connections after use and using connection pooling. Have a look here for a decent article on the topic...
http://www.c-sharpcorner.com/UploadFile/dsdaf/ConnPooling07262006093645AM/ConnPooling.aspx
I'd just like to add a general note of caution.
If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!
Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.
` Please include either of these:
`#include<sstream>`
using std::istringstream;
Here is your code in a jsfiddle example. I have tested it and it looks fine.
http://jsfiddle.net/dimshik/9DbEP/4/
I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.
<table border="1" cellpadding="3" id="printTable">
<tbody><tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.
If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.
However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.
My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.
You have done the stored procedure correctly but I think you have not referenced the valido
variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido
This statement SELECT valido;
should be like this SELECT @valido;
Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido
I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
You can find them in /var/log
within your root Magento installation
There will usually be two files by default, exception.log
and system.log
.
If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes
Its simple
$(function() {
$("#datePicker").datetimepicker({
defaultDate:'now'
});
});
This will set today as default
Just download MySQL workbench to log in. It will prompt you to change the password immediately and automatically.
Make sure that the value of the column is really NULL and not an empty string or 0.
function exportToExcel() {_x000D_
var tab_text = "<tr bgcolor='#87AFC6'>";_x000D_
var textRange; var j = 0, rows = '';_x000D_
tab = document.getElementById('student-detail');_x000D_
tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";_x000D_
var tableData = $('#student-detail').DataTable().rows().data();_x000D_
for (var i = 0; i < tableData.length; i++) {_x000D_
rows += '<tr>'_x000D_
+ '<td>' + tableData[i].value1 + '</td>'_x000D_
+ '<td>' + tableData[i].value2 + '</td>'_x000D_
+ '<td>' + tableData[i].value3 + '</td>'_x000D_
+ '<td>' + tableData[i].value4 + '</td>'_x000D_
+ '<td>' + tableData[i].value5 + '</td>'_x000D_
+ '<td>' + tableData[i].value6 + '</td>'_x000D_
+ '<td>' + tableData[i].value7 + '</td>'_x000D_
+ '<td>' + tableData[i].value8 + '</td>'_x000D_
+ '<td>' + tableData[i].value9 + '</td>'_x000D_
+ '<td>' + tableData[i].value10 + '</td>'_x000D_
+ '</tr>';_x000D_
}_x000D_
tab_text += rows;_x000D_
var data_type = 'data:application/vnd.ms-excel;base64,',_x000D_
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',_x000D_
base64 = function (s) {_x000D_
return window.btoa(unescape(encodeURIComponent(s)))_x000D_
},_x000D_
format = function (s, c) {_x000D_
return s.replace(/{(\w+)}/g, function (m, p) {_x000D_
return c[p];_x000D_
})_x000D_
}_x000D_
_x000D_
var ctx = {_x000D_
worksheet: "Sheet 1" || 'Worksheet',_x000D_
table: tab_text_x000D_
}_x000D_
document.getElementById("dlink").href = data_type + base64(format(template, ctx));_x000D_
document.getElementById("dlink").download = "StudentDetails.xls";_x000D_
document.getElementById("dlink").traget = "_blank";_x000D_
document.getElementById("dlink").click();_x000D_
}
_x000D_
Here Value 1 to 10 are column names that you are getting
So you can use the following :
td {
white-space: normal !important; // To consider whitespace.
}
If this doesn't work:
td {
white-space: normal !important;
word-wrap: break-word;
}
table {
table-layout: fixed;
}
The problem is you're not doing anything with the result of replace
. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
I agree that it is not possible in general.
The only thing CSS3 can do (which helped in my case) is to select elements that have no children:
table td:empty
{
background-color: white;
}
Or have any children (including text):
table td:not(:empty)
{
background-color: white;
}
Seems odd to be inserting a value into an automatically incrementing field.
Also, have you tried the insert() method instead of execSQL?
ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);
I believe that it can be done by simply setting your FormBorderStyle Property to None and the WindowState to Maximized. If you are using Visual Studio both of those can be found in the IDE so there is no need to do so programmatically. Make sure to include some way of closing/exiting the program before doing this cause this will remove that oh so helpful X in the upper right corner.
EDIT:
Try this instead. It is a snippet that I have kept for a long time. I can't even remember who to credit for it, but it works.
/*
* A function to put a System.Windows.Forms.Form in fullscreen mode
* Author: Danny Battison
* Contact: [email protected]
*/
// a struct containing important information about the state to restore to
struct clientRect
{
public Point location;
public int width;
public int height;
};
// this should be in the scope your class
clientRect restore;
bool fullscreen = false;
/// <summary>
/// Makes the form either fullscreen, or restores it to it's original size/location
/// </summary>
void Fullscreen()
{
if (fullscreen == false)
{
this.restore.location = this.Location;
this.restore.width = this.Width;
this.restore.height = this.Height;
this.TopMost = true;
this.Location = new Point(0,0);
this.FormBorderStyle = FormBorderStyle.None;
this.Width = Screen.PrimaryScreen.Bounds.Width;
this.Height = Screen.PrimaryScreen.Bounds.Height;
}
else
{
this.TopMost = false;
this.Location = this.restore.location;
this.Width = this.restore.width;
this.Height = this.restore.height;
// these are the two variables you may wish to change, depending
// on the design of your form (WindowState and FormBorderStyle)
this.WindowState = FormWindowState.Normal;
this.FormBorderStyle = FormBorderStyle.Sizable;
}
}
Use
document.getElementById("file-id").files[0].name;
instead of
document.getElementById('file-id').value
You can use the following function to highlight any word in your text.
function color_word(text_id, word, color) {
words = $('#' + text_id).text().split(' ');
words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });
new_words = words.join(' ');
$('#' + text_id).html(new_words);
}
Simply target the element that contains the text, choosing the word to colorize and the color of choice.
Here is an example:
<div id='my_words'>
This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.
</div>
Usage,
color_word('my_words', 'possible', 'hotpink')
DECODE(SUBSTR(STATUS,1,1),'a','Active','i','Inactive','t','Terminated','N/A')
Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.
.inner {_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner">1</div>_x000D_
<div class="inner">2</div>_x000D_
<div class="inner">3</div>_x000D_
<div class="inner">4</div>_x000D_
</div>
_x000D_
In my opinion the best tool for such testing is curl. Its --upload-file
option uploads a file by PUT
, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):
curl http://myservice --upload-file file.txt
The accepted answer works well and one can also just use the
If Exists (...) Then ... End If;
syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert
One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!
You should have if row[2] != "0"
. Otherwise it's not checking to see if the string value is equal to 0.
Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
SELECT COLUMN_NAME, TABLE_NAME,table_schema
FROM INFORMATION_SCHEMA.COLUMNS;
You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode
and Microsoft.AspNetCore.Http.StatusCodes
to form your response, if you don't wish to hardcode specific numbers.
return StatusCode(StatusCodes.Status500InternalServerError);
UPDATE: Aug 2019
Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions
I found that I had to construct a new StatusCodeResult
object found in the Microsoft.AspNetCore.Mvc.Core
assembly. My code now looks like this;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:
FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);
Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@
becomes d/m/yy h.mm;@
) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
I found this simple and usefull. Works even if first day of week is Sunday or Monday.
DECLARE @BaseDate AS Date
SET @BaseDate = GETDATE()
DECLARE @FisrtDOW AS Date
SELECT @FirstDOW = DATEADD(d,DATEPART(WEEKDAY,@BaseDate) *-1 + 1, @BaseDate)
The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller
Thx guys, I finally found the solution, a really basic one.. In my controller I have
$scope.mySplit = function(string, nb) {
var array = string.split(',');
return array[nb];
}
and in my view
{{mySplit(string,0)}}
Both .done()
and .success()
are callback functions and they essentially function the same way.
Here's the documentation. The difference is that .success()
is deprecated as of jQuery 1.8. You should use .done()
instead.
In case you don't want to click the link:
Deprecation Notice
The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
Had the same issue, in the terminal you can type:
export ANDROID_HOME=$HOME/Android/Sdk
or any other location depending on where you installed the sdk.
export PATH=$PATH:$ANDROID_HOME/platform-tools
Hope it helps!
The short answer is:
$milliseconds = round(microtime(true) * 1000);
Change:
RANK() OVER (PARTITION BY ContenderNum ORDER BY totals ASC) AS xRank
to:
RANK() OVER (ORDER BY totals DESC) AS xRank
Have a look at this example:
You might also want to have a look at the difference between RANK (Transact-SQL) and DENSE_RANK (Transact-SQL):
RANK (Transact-SQL)
If two or more rows tie for a rank, each tied rows receives the same rank. For example, if the two top salespeople have the same SalesYTD value, they are both ranked one. The salesperson with the next highest SalesYTD is ranked number three, because there are two rows that are ranked higher. Therefore, the RANK function does not always return consecutive integers.
DENSE_RANK (Transact-SQL)
Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.
To extract a single number from a string you can use re.search()
, which returns the first match (or None
):
>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158
In Python 3.6+ you can also index into a match object instead of using group()
:
>>> int(re.search(r'\d+', string)[0])
3158
A extends B:
A and B are both classes or both interfaces
A implements B
A is a class and B is an interface
The remaining case where A is an interface and B is a class is not legal in Java.
In the case you want to return an array of enums as a list you can do the following.
using System.Linq;
public List<DayOfWeek> DaysOfWeek
{
get
{
return Enum.GetValues(typeof(DayOfWeek))
.OfType<DayOfWeek>()
.ToList();
}
}
There is some news based on Mozilla Foundation, and sitepoint
Do not use this value (
http-equiv=content-type
) as it is obsolete. Prefer thecharset
attribute on the <meta
> element.
Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:
http://jsfiddle.net/maayan/byT76/
That's the basic css that enables it:
.clip1 {
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
}
.slice1 {
position:absolute;
width:200px;
height:200px;
clip:rect(0px,100px,200px,0px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
.clip2
{
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0,100px,200px,0px);
}
.slice2
{
position:absolute;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
and the js rotates it as required.
quite easy to understand..
Hope it helps, Maayan