This is a combined answer of the two answers at top, if anyone wants a working implementation.
package com.yourapplication;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
public abstract class OnSwipeListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeListener(Context context){
gestureDetector = new GestureDetector(context, new OnSwipeGestureListener(context));
gestureDetector.setIsLongpressEnabled(false);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class OnSwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
private final int minSwipeDelta;
private final int minSwipeVelocity;
private final int maxSwipeVelocity;
private OnSwipeGestureListener(Context context) {
ViewConfiguration configuration = ViewConfiguration.get(context);
// We think a swipe scrolls a full page.
//minSwipeDelta = configuration.getScaledTouchSlop();
minSwipeDelta = configuration.getScaledPagingTouchSlop();
minSwipeVelocity = configuration.getScaledMinimumFlingVelocity();
maxSwipeVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public boolean onDown(MotionEvent event) {
// Return true because we want system to report subsequent events to us.
return true;
}
// NOTE: see http://stackoverflow.com/questions/937313/android-basic-gesture-detection
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX,
float velocityY) {
boolean result = false;
try {
float deltaX = event2.getX() - event1.getX();
float deltaY = event2.getY() - event1.getY();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (absDeltaX > absDeltaY) {
if (absDeltaX > minSwipeDelta && absVelocityX > minSwipeVelocity
&& absVelocityX < maxSwipeVelocity) {
if (deltaX < 0) {
onSwipeLeft();
} else {
onSwipeRight();
}
}
result = true;
} else if (absDeltaY > minSwipeDelta && absVelocityY > minSwipeVelocity
&& absVelocityY < maxSwipeVelocity) {
if (deltaY < 0) {
onSwipeTop();
} else {
onSwipeBottom();
}
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public void onSwipeLeft() {}
public void onSwipeRight() {}
public void onSwipeTop() {}
public void onSwipeBottom() {}
}
Use this ^[a-zA-Z0-9_]*$
See here for more info.
In the old language, to delete the entry with key k
from the map represented by m
, one wrote the statement,
m[k] = value, false
This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.
In Go 1, that syntax has gone; instead there is a new built-in function, delete
. The call
delete(m, k)
will delete the map entry retrieved by the expression m[k]
. There is no return value. Deleting a non-existent entry is a no-op.
Updating: Running go fix
will convert expressions of the form m[k] = value, false
into delete(m, k)
when it is clear that the ignored value can be safely discarded from the program and false
refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.
Use this after saving the image
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});
In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table id='ddReferences'>
<tr>
<td>dfsdf</td>
<td>sdfs</td>
<td>frtyr</td>
<td>hjhj</td>
</tr>
</table>
<script>
var refTab = document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
</script>
</body>
</html>
I came across the same problem, read a couple of answers from different related questions and came up with my own class.
public class IndexableMap<K, V> extends HashMap<K, V> {
private LinkedList<K> keyList = new LinkedList<>();
@Override
public V put(K key, V value) {
if (!keyList.contains(key))
keyList.add(key);
return super.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
keyList.clear();
super.clear();
}
public List<K> getKeys() {
return keyList;
}
public int getKeyIndex(K key) {
return keyList.indexOf(key);
}
public K getKeyAt(int index) {
if (keyList.size() > index)
return keyList.get(index);
return null;
}
public V getValueAt(int index) {
K key = getKeyAt(index);
if (key != null)
return get(key);
return null;
}
}
Example (types are differing from OPs question just for clarity):
Map<String, Double> myMap = new IndexableMap<>();
List<String> keys = myMap.getKeys();
int keyIndex = myMap.getKeyIndex("keyString");
String key = myMap.getKeyAt(2);
Double value myMap.getValueAt(2);
Keep in mind that it does not override any of the complex methods, so you will need to do this on your own if you want to reliably access one of these.
Edit: I made a change to the putAll() method, because the old one had a rare chance to cause HashMap and LinkedList being in different states.
In [14]: b = np.reshape(a, (np.product(a.shape),))
In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])
or, simply:
In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])
If you are constrained to using an <img>
tag:
I've found it much easier to set a <div>
or any other element of your choice with a background-image
, width: 100%
and background-size: 100%
.
This isn't the end all be all to responsive images, but it's a start. Also, try messing around with background-size: cover
and maybe some positioning with background-position: center
.
CSS:
.image-container{
height: 100%; /* It doesn't have to be '%'. It can also use 'px'. */
width: 100%;
margin: 0 auto;
padding: 0;
background-image: url(../img/exampleImage.jpg);
background-position: top center;
background-repeat: no-repeat;
background-size: 100%;
}
HMTL:
<div class="image-container"></div>
Possible reason: The reason can be that this image is currently used by a running container. In such case, you can list running containers, stop the relevant container and then remove the image:
docker ps
docker stop <containerid>
docker rm <containerid>
docker rmi <imageid>
If you cannnot find container by docker ps, you can use this to list all already exited containers and remove them.
docker ps -a | grep 60afe4036d97
docker rm <containerid>
Note: Be careful of deleting all exited containers at once in case you use Volume-Only
containers. These stay in Exit
state, but contains useful data.
# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
commonMode=true
fi
# using ----------------
if $commonMode; then
echo 'YES, Common Mode'
else
echo 'NO, no Common Mode'
fi
$commonMode && echo 'commonMode is ON ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'
Unicode string literals (string literals prefixed by u
) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.
If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'
. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n
to your string literal. So when you print the 'hello\nworld'
string, the words will be printed on separate lines. That's very handy!
On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:
'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'
In such situations you can just prefix the string literal with the r
character like this: r'hello\nworld'
and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.
Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.
From the lexical definition of a string literal:
string ::= "'" stringitem* "'"
stringitem ::= stringchar | escapeseq
stringchar ::= <any source character except "\" or newline or the quote>
escapeseq ::= "\" <any source character>
It is clear that string literals (raw or not) containing a bare quote character: 'hello'world'
or ending with a backslash: 'hello world\'
are not valid.
The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:
The PDF files are not centered (still working on it)
<!DOCTYPE HTML>
<html>
<head>
<title>Testing iFrames on iPad</title>
<style>
div {
border: solid 1px green;
height:100px;
}
.scroller{
border:solid 1px #66AA66;
height: 400px;
width: 400px;
overflow: auto;
text-align:center;
}
</style>
<table>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
</table>
<div> Here are some additional contents.</div>
Wait function using timers, no UI locks.
public void wait(int milliseconds)
{
var timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
// Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
// Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
Usage: just placing this inside your code that needs to wait:
wait(1000); //wait one second
if I select the second row -
Dim jason As DataRowView
jason = dg1.SelectedItem
noteText.Text = jason.Item(0).ToString()
noteText will be 646. This is VB, but you get it.
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
This is how I solved this problem
$scope.downloadPDF = function () {
var link = document.createElement("a");
link.setAttribute("href", "path_to_pdf_file/pdf_filename.pdf");
link.setAttribute("download", "download_name.pdf");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "download_name.pdf"
}
Please note: for Bootstrap 4+ users, please consider Christophe's solution (Bootstrap 4 introduced flexbox, which provides for a more elegant CSS-only solution). The following will work for earlier versions of Bootstrap...
See http://jsfiddle.net/jhfrench/bAHfj/ for a working solution.
//for each element that is classed as 'pull-down', set its margin-top to the difference between its own height and the height of its parent
$('.pull-down').each(function() {
var $this = $(this);
$this.css('margin-top', $this.parent().height() - $this.height())
});
On the plus side:
pull-down
.Now the bad news:
Just create a button element with jQuery, and add the event handler when you create it :
var div = $('<div />', {'data-role' : 'fieldcontain'}),
btn = $('<input />', {
type : 'button',
value : 'Dynamic Button',
id : 'btn_a',
on : {
click: function() {
alert ( this.value );
}
}
});
div.append(btn).appendTo( $('#pg_menu_content').empty() );
Use the dir
command. Type in dir /?
for help and options.
dir /a:d /b
Then use a redirect to save the list to a file.
> list.txt
dir /a:d /b > list.txt
This will output just the names of the directories. if you want the full path of the directories use this below.
for /f "delims=" %%D in ('dir /a:d /b') do echo %%~fD
other method just using the for
command. See for /?
for help and options. This can output just the name %%~nxD
or the full path %%~fD
for /d %%D in (*) do echo %%~fD
To use these commands directly on the command line, change the double percent signs to single percent signs. %%
to %
To redirect the for
methods, just add the redirect after the echo statements. Use the double arrow >>
redirect here to append to the file, else only the last statement will be written to the file due to overwriting all the others.
... echo %%~fD>> list.txt
Having seen simply too many edge cases, I went for a simpler check:
^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$
The first thing one may point out is allowing repetition of "ext", but the purpose of this regex is to prevent users from accidentally entering email ids etc. instead of phone numbers, which it does.
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
There is no problem at all using Jupyter with existing or new Python .py modules. With Jupyter running, simply fire up Spyder (or any editor of your choice) to build / modify your module class definitions in a .py file, and then just import the modules as needed into Jupyter.
One thing that makes this really seamless is using the autoreload magic extension. You can see documentation for autoreload here:
http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html
Here is the code to automatically reload the module any time it has been modified:
# autoreload sets up auto reloading of modified .py modules
import autoreload
%load_ext autoreload
%autoreload 2
Note that I tried the code mentioned in a prior reply to simulate loading .ipynb files as modules, and got it to work, but it chokes when you make changes to the .ipynb file. It looks like you need to restart the Jupyter development environment in order to reload the .ipynb 'module', which was not acceptable to me since I am making lots of changes to my code.
If you have proportioned elements, you could use:
.valid {
background-position: 98% center;
}
.half .valid {
background-position: 96% center;
}
In this example, .valid
would be the class with the picture and .half
would be a row with half the size of the standard one.
Dirty, but works as a charm and it's reasonably manageable.
I had the same problem using rvm
on Ubuntu
, was fixed by setting the source
on my terminal as a short-term solution:
source $HOME/.rvm/scripts/rvm
or
source /home/$USER/.rvm/scripts/rvm
and configure a default Ruby Version, 2.3.3
in my case.
rvm use 2.3.3 --default
And a long-term Solution is to add your source
to your .bashrc
file to permanently make Ubuntu look in .rvm
for all the Ruby files.
Add:
source .rvm/scripts/rvm
into
$HOME/.bashrc
file.
You can also do it using reredirect
(https://github.com/jerome-pouiller/reredirect/).
The command bellow redirects the outputs (standard and error) of the process PID
to FILE
:
reredirect -m FILE PID
The README
of reredirect
also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.
The tool also provides relink
, a script allowing to redirect the outputs to the current terminal:
relink PID
relink PID | grep usefull_content
(reredirect
seems to have same features than Dupx described in another answer but, it does not depend on Gdb).
df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])
df
A B
100 a 54
200 b 67
300 c 89
In [19]:
df.loc[100]
Out[19]:
A a
B 54
Name: 100, dtype: object
In [20]:
df.iloc[0]
Out[20]:
A a
B 54
Name: 100, dtype: object
In [24]:
df2 = df.set_index([df.index,'A'])
df2
Out[24]:
B
A
100 a 54
200 b 67
300 c 89
In [25]:
df2.ix[100, 'a']
Out[25]:
B 54
Name: (100, a), dtype: int64
date -j -f "%Y-%m-%d %H:%M:%S" "2020-04-07 00:00:00" "+%s"
It will print the dynamic seconds when without %H:%M:%S
and 00:00:00
.
Just to offer some variety, the comma operator can be used too but some might say "noooooo!", but it works:
<input type="button" onclick="one(), two(), three(), four()"/>
Is there some command to create this folder?
If smb face this issue again, you should know the most simple way to create .m2
folder.
If you unzipped maven and set up maven path variable - just try mvn clean
command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.
If you are looking for a programmatical modal creation, you might love this:
http://nakupanda.github.io/bootstrap3-dialog/
Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.
With Spring you can do:
String path = new UrlPathHelper().getPathWithinApplication(request);
Installed products consist of installed software elements and features so it's worth checking wmic alias's for PRODUCT as well as checking SOFTWAREELEMENT and SOFTWAREFEATURE:
wmic product get name,version
wmic softwareelement get name,version
wmic softwarefeature get name,version
I think you should re-format your code a bit:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
mkdir -p /home/mlzboy/b2c2/shared/db;
fi;
There is a small difference between both.
Second declaration assignates the reference associated to the constant SOME
to the variable str
First declaration creates a new String having for value the value of the constant SOME
and assignates its reference to the variable str
.
In the first case, a second String has been created having the same value that SOME
which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOME
are transformed into the same instance, which uses far less memory.
As a consequence, always prefer second syntax.
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
This has only been tested on Windows:
You can do the following:
import os
os.startfile("C:/Users/TestFile.txt", "print")
This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os
module which comes with the standard library
A short way to run 'em all:
[first_function, ..., nth_function].forEach (function(f) {
f('a string');
});
In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.
Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".
Whenever you start Visual Studio run it as administrator. It works for me.
As Mehrdad said, you cannot just seek to the n-th line without reading the file. However, you don't need to store the entire file in memory - just discard the data you don't need.
string line;
using (StreamReader sr = new StreamReader(path))
for (int i = 0; i<15; i++)
{
line = sr.ReadLine();
if (line==null) break; // there are less than 15 lines in the file
}
Note also that "key" does not necessarily mean primary key. Something like this will work:
CREATE TABLE book (
isbn BIGINT NOT NULL PRIMARY KEY,
id INT NOT NULL AUTO_INCREMENT,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
INDEX(id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is a contrived example and probably not the best idea, but it can be very useful in certain cases.
What you want is called a pivot, and it's not directly supported in MySQL, check this answer out for the options you've got:
I did it in this way:
git --version
, it should give you the latest version.Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>
, though the semantics of sets and lists are a bit different.
i faced an issue something like this...
Actually, in two ways you can process find
command output in copy
command
If find
command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:
Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>
Example: find -mtime -1 -type f | xargs cp -t inner/
But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:
Syntax: find <path> <condition> -exec cp '{}' <copy path> \;
Example find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, last part i.e semi-colon is also considered as part of find
command, that should be escaped before press the enter button. Otherwise you will get an error something like this
find: missing argument to `-exec'
In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend
. The following command will work:
find /home/shantanu/processed/ -name '*2011*.xml' -exec cp {} /home/shantanu/tosend \;
Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!
From the JUnit javadoc:
delta - the maximum delta between expected and actual for which both numbers are still considered equal.
It's probably overkill, but I typically use a really small number, e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertEquals(123.456, 123.456, DELTA);
}
If you're using hamcrest assertions, you can just use the standard equalTo()
with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo()
(see javadoc), e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertThat(123.456, equalTo(123.456));
assertThat(123.456, closeTo(123.456, DELTA));
}
FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals()
with two doubles. The implementation (if you're interested) is:
private static boolean doublesAreEqual(double value1, double value2) {
return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}
Use the dec argument to set ","
as the decimal point by adding:
ce <- read.table("file.txt", header = TRUE, dec = ",")
You can use the visible selector:
Way late, but I just ran into a similar issue.
My solution was pseudo elements - no additional markup, and you get to draw the border without affecting the width.
Position the pseudo element absolutely (with the main positioned relatively) and whammo.
See below, JSFiddle here.
.hello {
position: relative;
/* Styling not important */
background: black;
color: white;
padding: 20px;
width: 200px;
height: 200px;
}
.hello::before {
content: "";
position: absolute;
display: block;
top: 0;
left: -5px;
right: -5px;
bottom: 0;
border-left: 5px solid red;
border-right: 5px solid red;
z-index: -1;
}
For multicolumn listbox extract data from any column of selected row by
listboxControl.List(listboxControl.ListIndex,col_num)
where col_num is required column ( 0 for first column)
To change image onclik with javascript you need to have image with id:
<p>
<img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
</p>
Then you could call javascript function when image is clicked:
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png")
{
document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
}
else
{
document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
}
}
</script>
This code will set image to maximize.png if current img.src is set to minimize.png and vice versa. For more details visit: Change image onclick with javascript link
This is something easy to do and it worked for me:
//Create a Javascript executor
JavascriptExecutor jst= (JavascriptExecutor) driver;
jst.executeScript("arguments[1].value = arguments[0]; ", 55, driver.findElement(By.id("id")));
55 = value assigned
Update using NuGet Package Manager
Console in your Visual Studio
Update-Package -reinstall Microsoft.AspNet.Mvc
Acording with the documentation, the method getEntity in Jax rs 2.0 return a InputStream. If you need to convert to InputStream to String with JSON format, you need to cast the two formats. For example in my case, I implemented the next method:
private String processResponse(Response response) {
if (response.getEntity() != null) {
try {
InputStream salida = (InputStream) response.getEntity();
StringWriter writer = new StringWriter();
IOUtils.copy(salida, writer, "UTF-8");
return writer.toString();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
return null;
}
why I implemented this method. Because a read in differets blogs that many developers they have the same problem whit the version in jaxrs using the next methods
String output = response.readEntity(String.class)
and
String output = response.getEntity(String.class)
The first works using jersey-client from com.sun.jersey library and the second found using the jersey-client from org.glassfish.jersey.core.
This is the error that was being presented to me: org.glassfish.jersey.client.internal.HttpUrlConnector$2 cannot be cast to java.lang.String
I use the following maven dependency:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>
What I do not know is why the readEntity method does not work.I hope you can use the solution.
Carlos Cepeda
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.
startActivity(new Intent(this,your-new-screen.class));
finishAffinity();
The finishAffinity(); method clears back button stack.
DECLARE @x VARCHAR(32) = 'MS-SQL-Server';
SELECT
SUBSTRING(@x,0,CHARINDEX('-',LTRIM(RTRIM(@x)))) A,
SUBSTRING(@x,CHARINDEX('-',LTRIM(RTRIM(@x)))+1,CHARINDEX('-'
,LTRIM(RTRIM(@x)))) B,
SUBSTRING(@x,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x))))+1,LEN(@x)-1) C
A B C
MS SQL Server
Or if you prefer to use your own gui tool:
git difftool ./filepath
You can set your gui tool guided by this post: How do I view 'git diff' output with a visual diff program?
Hello, below is my working solution for all browsers supporting flexbox. No negative margins.
_x000D_
.flexbox {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
flex-wrap: wrap;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.flexbox > div {_x000D_
/*_x000D_
1/3 - 3 columns per row_x000D_
10px - spacing between columns _x000D_
*/_x000D_
box-sizing: border-box;_x000D_
margin: 10px 10px 0 0;_x000D_
outline: 1px dotted red;_x000D_
width: calc(1/3*100% - (1 - 1/3)*10px);_x000D_
}_x000D_
_x000D_
/*_x000D_
align last row columns to the left_x000D_
3n - 3 columns per row_x000D_
*/_x000D_
.flexbox > div:nth-child(3n) {_x000D_
margin-right: 0;_x000D_
}_x000D_
_x000D_
.flexbox::after {_x000D_
content: '';_x000D_
flex: auto;_x000D_
}_x000D_
_x000D_
/*_x000D_
remove top margin from first row_x000D_
-n+3 - 3 columns per row _x000D_
*/_x000D_
.flexbox > div:nth-child(-n+3) {_x000D_
margin-top: 0;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
<div>col</div>_x000D_
<div>col</div>_x000D_
<div>col</div>_x000D_
<div>col</div>_x000D_
<div>col</div>_x000D_
</div>
_x000D_
Take a note this code can be shorter using SASS
Update 2020.II.11 Aligned columns on the last row to the left
Update 2020.II.14 Removed margin-bottom in the last row
In Python 2.x just put a ,
at the end of your print
statement. If you want to avoid the blank space that print
puts between items, use sys.stdout.write
.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep
that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep
)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
If you are using an Alpine based image, you have to
RUN
... \
apk add --no-cache curl \
curl ...
...
To use the class ActionBarOverlayLayout
you need to include this in the dependencies section of build.gradle file:
compile 'com.android.support:design:24.1.1'
Sync the project once again and then you will find no problem
You can also add
<Resource
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="20"
maxIdle="10"
maxWait="-1"
name="ds/flexeraDS"
type="javax.sql.DataSource"
url="jdbc:derby:flexeraDB;create=true"
/>
under META-INF/context.xml
file (This will be only at application level).
We do it that way: First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
I had the same problem with Pool()
in Python 3.6.3.
Error received: TypeError: can't pickle _thread.RLock objects
Let's say we want to add some number num_to_add
to each element of some list num_list
in parallel. The code is schematically like this:
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list))
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
def run_parallel(self, num, shared_new_num_list):
new_num = num + self.num_to_add # uses class parameter
shared_new_num_list.append(new_num)
The problem here is that self
in function run_parallel()
can't be pickled as it is a class instance. Moving this parallelized function run_parallel()
out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add
and then you have to pass it as an argument.
Solution:
def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
new_num = num + to_add
shared_new_num_list.append(new_num)
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
Other suggestions above didn't help me.
If you're like me running in a restricted environment without administrative privileges, that means your only way to get node up and running is to grab the executable (node.exe) without using the installer. You also cannot change the path variable which makes it that much more challenging.
Here's what I did (for Windows)
npm install -g express
Running the installers through npm will now auto install packages where they need to be located (node_modules and the root)
Don't forget you will not be able to set the path variable if you do not have proper permissions. So your best route is to open a command prompt in the node.exe directory (shift right-click "Open command window here")
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
You should not be repeating the string
part when sending parameters.
int wordLength = wordLengthFunction(word); //you do not put string word here.
Im attempting this now, this is what i came up with;
placeholder = 1
while placeholder is not None:
try:
#Code
placeholder = None
except Exception as e:
print(str(datetime.time(datetime.now()))[:8] + str(e)) #To log the errors
placeholder = e
time.sleep(0.5)
continue
Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
I had the same problem. Try this :
Right Click the project -> Maven -> Update Project
Then Re-run the project. Hope it work for you too.
You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).
Does not work for multidimensional arrays, because references are used here.
import numpy as np
# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)
# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
See also Swap slices of Numpy arrays
Knowing this thread is marked as solved, it shows up early on Google Search for the given term. So I thought it might be useful to mention another reason that can lead to this error.
If you enabled "safe/secure cookies", that has to be disabled for phpMyAdmin as it wont work with them being activated. So make sure you have nothing like:
Header set Set-Cookie HttpOnly;Secure
in your config.
To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.
To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.
try
{
// code causing TargetInvocationException
}
catch (Exception e)
{
if (e.InnerException != null)
{
string err = e.InnerException.Message;
}
}
Okay, I've figured this out. Postgresql does not detect changes to the folder /var/lib/postgresql once it's launched, at least not the kind of changes I want it do detect.
The first solution is to start a container with bash instead of starting the postgres server directly, restore the data, and then start the server manually.
The second solution is to use a data container. I didn't get the point of it before, now I do. This data container allows to restore the data before starting the postgres container. Thus, when the postgres server starts, the data are already there.
class ArrayPrinter
{
#region Declarations
static bool isLeftAligned = false;
const string cellLeftTop = "+";
const string cellRightTop = "+";
const string cellLeftBottom = "+";
const string cellRightBottom = "+";
const string cellHorizontalJointTop = "-";
const string cellHorizontalJointbottom = "-";
const string cellVerticalJointLeft = "+";
const string cellTJoint = "+";
const string cellVerticalJointRight = "¦";
const string cellHorizontalLine = "-";
const string cellVerticalLine = "¦";
#endregion
#region Private Methods
private static int GetMaxCellWidth(string[,] arrValues)
{
int maxWidth = 1;
for (int i = 0; i < arrValues.GetLength(0); i++)
{
for (int j = 0; j < arrValues.GetLength(1); j++)
{
int length = arrValues[i, j].Length;
if (length > maxWidth)
{
maxWidth = length;
}
}
}
return maxWidth;
}
private static string GetDataInTableFormat(string[,] arrValues)
{
string formattedString = string.Empty;
if (arrValues == null)
return formattedString;
int dimension1Length = arrValues.GetLength(0);
int dimension2Length = arrValues.GetLength(1);
int maxCellWidth = GetMaxCellWidth(arrValues);
int indentLength = (dimension2Length * maxCellWidth) + (dimension2Length - 1);
//printing top line;
formattedString = string.Format("{0}{1}{2}{3}", cellLeftTop, Indent(indentLength), cellRightTop, System.Environment.NewLine);
for (int i = 0; i < dimension1Length; i++)
{
string lineWithValues = cellVerticalLine;
string line = cellVerticalJointLeft;
for (int j = 0; j < dimension2Length; j++)
{
string value = (isLeftAligned) ? arrValues[i, j].PadRight(maxCellWidth, ' ') : arrValues[i, j].PadLeft(maxCellWidth, ' ');
lineWithValues += string.Format("{0}{1}", value, cellVerticalLine);
line += Indent(maxCellWidth);
if (j < (dimension2Length - 1))
{
line += cellTJoint;
}
}
line += cellVerticalJointRight;
formattedString += string.Format("{0}{1}", lineWithValues, System.Environment.NewLine);
if (i < (dimension1Length - 1))
{
formattedString += string.Format("{0}{1}", line, System.Environment.NewLine);
}
}
//printing bottom line
formattedString += string.Format("{0}{1}{2}{3}", cellLeftBottom, Indent(indentLength), cellRightBottom, System.Environment.NewLine);
return formattedString;
}
private static string Indent(int count)
{
return string.Empty.PadLeft(count, '-');
}
#endregion
#region Public Methods
public static void PrintToStream(string[,] arrValues, StreamWriter writer)
{
if (arrValues == null)
return;
if (writer == null)
return;
writer.Write(GetDataInTableFormat(arrValues));
}
public static void PrintToConsole(string[,] arrValues)
{
if (arrValues == null)
return;
Console.WriteLine(GetDataInTableFormat(arrValues));
}
#endregion
static void Main(string[] args)
{
int value = 997;
string[,] arrValues = new string[5, 5];
for (int i = 0; i < arrValues.GetLength(0); i++)
{
for (int j = 0; j < arrValues.GetLength(1); j++)
{
value++;
arrValues[i, j] = value.ToString();
}
}
ArrayPrinter.PrintToConsole(arrValues);
Console.ReadLine();
}
}
What about something like:
Alter Table Products
Add LastUpdate varchar(200) null
Do you need something more complex than this?
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
$(document).ready(function(){
$('#mySelect').append("<option>BMW</option>")
})
Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:
sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh
There's actually a simpler way than having a view for each redirect - you can do it directly in urls.py
:
from django.http import HttpResponsePermanentRedirect
urlpatterns = patterns(
'',
# ...normal patterns here...
(r'^bad-old-link\.php',
lambda request: HttpResponsePermanentRedirect('/nice-link')),
)
A target can be a callable as well as a string, which is what I'm using here.
I meet this problem when I try to use mingw to compile the xgboost lib in Win10. Finally I found the solution.
Create a file named as .bashrc in your home directory (usually the C:\Users\username). Then add the path to it. Remember to use quotes if your path contains blank, and remember to use /c/ instead of C:/
For example:
PATH=$PATH:"/c/Program Files/mingw-w64/x86_64-7.2.0-posix-seh-rt_v5-rev1/mingw64/bin"
Try:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children...)
When you don't care about removing the Html Dom-Element, use *ngIf.
Otherwise, use this:
<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
COUNTER: {{numberOfUnreadAlerts}}
</div>
You cannot play a video inside a view. It has to be played fullscreen.
Need to add a reference to Microsoft.Outlook. it is in Project references, from the visual basic window top menu.
Private Sub sendemail_Click()
Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Set OutlookApp = New Outlook.Application
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail
.Display
.To = email
.Subject = "subject"
Dim wdDoc As Object ' Word.Document
Dim wdRange As Object ' Word.Range
Set wdDoc = .GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0) ' Create Range at character position 0 with length of 0 character s.
' if you need rtl:
wdRange.Paragraphs.ReadingOrder = 0 ' 0 is rtl , 1 is ltr
wdRange.InsertAfter "mytext"
End With
End Sub
Step 1:- Stop-all.sh
Step 2:- got to this path
cd /usr/local/hadoop/bin
Step 3:- Run that command hadoop datanode
Now DataNode work
I think your second option is the best bet. Generally in floating-point comparison you often only care that one value is within a certain tolerance of another value, controlled by the selection of epsilon.
There are different ways to achieve this, but I'm not sure which one is the best (I don't even know is there is a best way). I know at least two different ways to do this in a ListView:
1. Set divider to null:
1.1. Programmatically
yourListView.setDivider(null);
1.2. XML
This goes inside your ListView element.
android:divider="@null"
2. Set divider to transparent and set its height to 0 to avoid adding space between listview elements:
2.1. Programmatically:
yourListView.setDivider(new ColorDrawable(android.R.color.transparent));
yourListView.setDividerHeight(0);
2.2. XML
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
The UIWindow.tintColor
method wasn't working for me in iOS8 (it was still black), so I had to do this:
let b = UIButton.buttonWithType(UIButtonType.System) as UIButton
var color = b.titleColorForState(.Normal)
This gave the proper blue tint seen in a UIBarButtonItem
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
wget utility retrieves files from World Wide Web (WWW) using widely used protocols like HTTP, HTTPS and FTP. Wget utility is freely available package and license is under GNU GPL License. This utility can be install any Unix-like Operating system including Windows and MAC OS. It’s a non-interactive command line tool. Main feature of Wget is it’s robustness. It’s designed in such way so that it works in slow or unstable network connections. Wget automatically start download where it was left off in case of network problem. Also downloads file recursively. It’ll keep trying until file has be retrieved completely.
Install wget in linux machine sudo apt-get install wget
Create a folder where you want to download files . sudo mkdir myimages cd myimages
Right click on the webpage and for example if you want image location right click on image and copy image location. If there are multiple images then follow the below:
If there are 20 images to download from web all at once, range starts from 0 to 19.
wget http://joindiaspora.com/img{0..19}.jpg
I found the following to work on Chrome, Firefox and IE11:
$('iframe').load(function () {
$('iframe').height($('iframe').contents().height());
});
When the Iframes content is done loading the event will fire and it will set the IFrames height to that of its content. This will only work for pages within the same domain as that of the IFrame.
It is possible to create a unique constraint on a Clustered Indexed View
You can create the View like this:
CREATE VIEW dbo.VIEW_OfYourTable WITH SCHEMABINDING AS
SELECT YourUniqueColumnWithNullValues FROM dbo.YourTable
WHERE YourUniqueColumnWithNullValues IS NOT NULL;
and the unique constraint like this:
CREATE UNIQUE CLUSTERED INDEX UIX_VIEW_OFYOURTABLE
ON dbo.VIEW_OfYourTable(YourUniqueColumnWithNullValues)
Use the nowrap style:
<td style="white-space:nowrap;">...</td>
It's CSS!
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
Example:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Or press Ctrl-Z at a raw_input()
prompt (Windows, Ctrl-Z Linux)
The normal case would be to annotate on a service layer level, but this really depends on your requirements.
Annotating on a service layer will result in longer transactions than annotating on DAO level. Depending on the transaction isolation level that can youse problems, as concurrent transactions wont see each other's changes in eg. REPEATABLE READ.
Annotating on the DAOs will keep the transactions as short as possible, with the drawback that the functionality your service layer is exposing wont be done in a single (rollbackable) transaction.
It does not make sense to annotate both layers if the propagation mode is set to default.
I think the easiest way to accomplish it is to use querystring instead of HTTP headers.
Had been over looking the issue having surfaced it. Believe this will be a good read for others who come down here with the same issue:
Java's Double
class has members containing the Min and Max value for the type.
2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.
Check out the Min_VALUE
and MAX_VALUE
static final members of Double
.
(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.
Updated to Swift 4, leveraging userInfo:
class TimerSample {
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 5.0,
target: self,
selector: #selector(eventWith(timer:)),
userInfo: [ "foo" : "bar" ],
repeats: true)
}
// Timer expects @objc selector
@objc func eventWith(timer: Timer!) {
let info = timer.userInfo as Any
print(info)
}
}
It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.
After some googling I found this link:
The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged
So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.
Update 2019
Remember that whatever CSS overrides you define must be the same CSS specificity or greater in order to properly override Bootstrap's CSS.
Bootstrap 4.1+
The Navbar is transparent by default. If you only want to change the background color, it can be done simply by applying the color to the <navbar class="bg-custom">
, but remember that won't change the other colors such as the links, hover and dropdown menu colors.
Here's CSS that will change any relevant Navbar colors in Bootstrap 4...
/* change the background color */
.navbar-custom {
background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:focus .nav-link,
.navbar-custom .nav-item:hover .nav-link {
color: #ffffff;
}
Demo: http://www.codeply.com/go/U9I2byZ3tS
Override Navbar Light or Dark
If you're using the Bootstrap 4 Navbar navbar-light
or navbar-dark
classes, then use this in the overrides. For example, changing the Navbar link colors...
.navbar-light .nav-item.active .nav-link,
.navbar-light .nav-item:focus .nav-link,
.navbar-light .nav-item:hover .nav-link {
color: #ffffff;
}
When making any Bootstrap customizations, you need to understand CSS Specificity. Overrides in your custom CSS need to use selectors that are as specific as the bootstrap.css. Read more
Transparent Navbar
Notice that the Bootstrap 4 Navbar is transparent by default. Use navbar-dark
for dark/bold background colors, and use navbar-light
if the navbar is a lighter color. This will effect the color of the text and color of the toggler icon as explained here.
Contrary to the accepted answer which suggests a permanent scroll bar on the browser window even if the content doesn't overflow the screen, I would prefer using:
html{
height:101%;
}
This is because the appearance of scroll bar makes more sense if the content actually overflows.
If you are using jQuery:
$('#sel').val('bike');
I used java print statements for easy understanding.
To check Element Present:
if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
Or
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
To check Visible:
if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
To check Enable:
if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}
To check text present
if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}
Try this,
new Date().toString().split("GMT")[1].split(" (")[0]
npm pack
+ package.json
This is what worked for me:
module project
, execute npm pack
:This will build a <package-name>-<version>.tar.gz
file.
consumer project
Ideally you can put all such files in a tmp
folder in your consumer-project
root:
package.json
:"dependencies": {
"my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}
Install
the packages:npm install
or npm i
or yarn
consumer-project's node_modules
folder.Good Luck...
You want in page A to know the URL of page B?
Or to know in page B the URL of page A?
In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?
In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains
Matrix m
with size 3 rows and 5 columns (remove .fill(0)
to not init by zero)
[...Array(3)].map(x=>Array(5).fill(0))
let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));
let m = Array2D(3,5);
m[1][0] = 2; // second row, first column
m[2][4] = 8; // last row, last column
// print formated array
console.log(JSON.stringify(m)
.replace(/(\[\[)(.*)(\]\])/g,'[\n [$2]\n]').replace(/],/g,'],\n ')
);
_x000D_
If you just want the list, then you should ask here: http://unix.stackexchange.com
The answer is: cd / && find -name *.js
If you want to implement this, you have to specify the language.
There is a library daff (short for data diff) which helps in comparing tables, producing a summary of their diffs, and using such a summary as a patch file.
It is written in Haxe, so it can be compiled in major languages.
I have made an Excel Diff Tool in Javascript with help of this library. It works well with numbers & small strings but the output is not ideal for long strings (e.g. a long sentence with with minor character change).
The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:
string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342
This is an improved version of this answer.
String.equal = function (s1, s2, ignoreCase, useLocale) {
if (s1 == null || s2 == null)
return false;
if (!ignoreCase) {
if (s1.length !== s2.length)
return false;
return s1 === s2;
}
if (useLocale) {
if (useLocale.length)
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
else
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
}
else {
if (s1.length !== s2.length)
return false;
return s1.toLowerCase() === s2.toLowerCase();
}
}
String.equal = function (s1, s2, ignoreCase, useLocale) {_x000D_
if (s1 == null || s2 == null)_x000D_
return false;_x000D_
_x000D_
if (!ignoreCase) {_x000D_
if (s1.length !== s2.length)_x000D_
return false;_x000D_
_x000D_
return s1 === s2;_x000D_
}_x000D_
_x000D_
if (useLocale) {_x000D_
if (useLocale.length)_x000D_
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)_x000D_
else_x000D_
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()_x000D_
}_x000D_
else {_x000D_
if (s1.length !== s2.length)_x000D_
return false;_x000D_
_x000D_
return s1.toLowerCase() === s2.toLowerCase();_x000D_
}_x000D_
}_x000D_
_x000D_
// If you don't mind extending the prototype._x000D_
String.prototype.equal = function(string2, ignoreCase, useLocale) {_x000D_
return String.equal(this.valueOf(), string2, ignoreCase, useLocale);_x000D_
}_x000D_
_x000D_
// ------------------ TESTS ----------------------_x000D_
console.log("Tests...");_x000D_
_x000D_
console.log('Case sensitive 1');_x000D_
var result = "Abc123".equal("Abc123");_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Case sensitive 2');_x000D_
result = "aBC123".equal("Abc123");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('Ignore case');_x000D_
result = "AbC123".equal("aBc123", true);_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Ignore case + Current locale');_x000D_
result = "AbC123".equal("aBc123", true);_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Turkish test 1 (ignore case, en-US)');_x000D_
result = "IiiI".equal("iiII", true, "en-US");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('Turkish test 2 (ignore case, tr-TR)');_x000D_
result = "IiiI".equal("iiII", true, "tr-TR");_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Turkish test 3 (case sensitive, tr-TR)');_x000D_
result = "IiiI".equal("iiII", false, "tr-TR");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-1');_x000D_
result = "AAA".equal(null);_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-2');_x000D_
result = String.equal(null, "BBB");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-3');_x000D_
result = String.equal(null, null);_x000D_
console.assert(result === false);
_x000D_
Simple way - you can specify .* in the beginning because find matches the whole path.
$ find . -regextype egrep -regex '.*[a-f0-9\-]{36}\.jpg$'
find version
$ find --version
find (GNU findutils) 4.6.0
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION
FTS(FTS_CWDFD) CBO(level=2)
If using in fragment then simply write
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something on UiThread
}
});
In C# this is how to get the resolution Screen:
button click or form load:
string screenWidth = Screen.PrimaryScreen.Bounds.Width.ToString();
string screenHeight = Screen.PrimaryScreen.Bounds.Height.ToString();
Label1.Text = ("Resolution: " + screenWidth + "x" + screenHeight);
public class Shift {
public static void main(String[] args) {
Byte b = Byte.parseByte("00101011",2);
System.out.println(b);
byte val = b.byteValue();
Byte shifted = new Byte((byte) (val >> 2));
System.out.println(shifted);
// often overloked are the methods of Integer
int i = Integer.parseInt("00101011",2);
System.out.println( Integer.toBinaryString(i));
i >>= 2;
System.out.println( Integer.toBinaryString(i));
}
}
Output:
43
10
101011
1010
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);
That should do the trick without casting.
Try
location ~ ^/(first/location|second/location)/ {
...
}
The ~
means to use a regular expression for the url. The ^
means to check from the first character. This will look for a /
followed by either of the locations and then another /
.
Textbox.Focus()
"Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus()
will not work. So make sure that your element is visible before calling Focus()
.
in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)
import java.util.Stack;
public static void main(String[] args) {
//String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{([)]}" is _not_ balanced
String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
String[] answers = new String[arrayOfBraces.length];
String openers = "([{";
String closers = ")]}";
String stringToInspect = "";
Stack<String> stack = new Stack<String>();
for (int i = 0; i < arrayOfBraces.length; i++) {
stringToInspect = arrayOfBraces[i];
for (int j = 0; j < stringToInspect.length(); j++) {
if(stack.isEmpty()){
if (openers.indexOf(stringToInspect.charAt(j))>=0) {
stack.push(""+stringToInspect.charAt(j));
}
else{
answers[i]= "NO";
j=stringToInspect.length();
}
}
else if(openers.indexOf(stringToInspect.charAt(j))>=0){
stack.push(""+stringToInspect.charAt(j));
}
else{
String comparator = stack.pop();
int compLoc = openers.indexOf(comparator);
int thisLoc = closers.indexOf(stringToInspect.charAt(j));
if (compLoc != thisLoc) {
answers[i]= "NO";
j=stringToInspect.length();
}
else{
if(stack.empty() && (j== stringToInspect.length()-1)){
answers[i]= "YES";
}
}
}
}
}
System.out.println(answers.length);
for (int j = 0; j < answers.length; j++) {
System.out.println(answers[j]);
}
}
This was always the question I had when I was working on one of my application which created massive number of threads per request.
So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
- Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.
2. Whether I should start my Application with lower heap size
- So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
- For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
- If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.
The answer of Pascal Thivent helped me out, too.
But if you manage your plugins within the <pluginManagement>
element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install
.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>main.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins> <!-- did NOT work without this -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<!-- dependencies commented out to shorten example -->
</dependencies>
</project>
You can do this using the Class.cast()
method, which dynamically casts the supplied parameter to the type of the class instance you have. To get the class instance of a particular field, you use the getType()
method on the field in question. I've given an example below, but note that it omits all error handling and shouldn't be used unmodified.
public class Test {
public String var1;
public Integer var2;
}
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("var1", "test");
map.put("var2", 1);
Test t = new Test();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Field f = Test.class.getField(entry.getKey());
f.set(t, f.getType().cast(entry.getValue()));
}
System.out.println(t.var1);
System.out.println(t.var2);
}
}
You cannot do this with standard LINQ operators because LINQ provides query, not update support.
But you can generate a new list and replace the old one.
var authorsList = GetAuthorList();
authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();
Or you could remove all items in authors
in a second pass.
var authorsList = GetAuthorList();
var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();
foreach (var author in authors)
{
authorList.Remove(author);
}
In the scikit-learn 'metrics' library there is a confusion_matrix method which gives you the desired output.
You can use any classifier that you want. Here I used the KNeighbors as example.
from sklearn import metrics, neighbors
clf = neighbors.KNeighborsClassifier()
X_test = ...
y_test = ...
expected = y_test
predicted = clf.predict(X_test)
conf_matrix = metrics.confusion_matrix(expected, predicted)
>>> print conf_matrix
>>> [[1403 87]
[ 56 3159]]
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
If you're using react-native then please try the below commands first before running your project:
Now run your project again. Hope this will work.
You cannot create migration scripts for existing models.
Resources:
If going the classic way, you'll have to recreate the models via the CLI:
sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text
It will generate these files:
models/myuser.js:
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
var MyUser = sequelize.define("MyUser", {_x000D_
first_name: DataTypes.STRING,_x000D_
last_name: DataTypes.STRING,_x000D_
bio: DataTypes.TEXT_x000D_
}, {_x000D_
classMethods: {_x000D_
associate: function(models) {_x000D_
// associations can be defined here_x000D_
}_x000D_
}_x000D_
});_x000D_
return MyUser;_x000D_
};
_x000D_
migrations/20150210104840-create-my-user.js:
"use strict";_x000D_
module.exports = {_x000D_
up: function(migration, DataTypes, done) {_x000D_
migration.createTable("MyUsers", {_x000D_
id: {_x000D_
allowNull: false,_x000D_
autoIncrement: true,_x000D_
primaryKey: true,_x000D_
type: DataTypes.INTEGER_x000D_
},_x000D_
first_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
last_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
bio: {_x000D_
type: DataTypes.TEXT_x000D_
},_x000D_
createdAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
},_x000D_
updatedAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
}_x000D_
}).done(done);_x000D_
},_x000D_
down: function(migration, DataTypes, done) {_x000D_
migration.dropTable("MyUsers").done(done);_x000D_
}_x000D_
};
_x000D_
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
A variant of @Daniel LaFavers' answer.
var mask = function (background, foreground) {
bg = (new String(background));
fg = (new String(foreground));
bgl = bg.length;
fgl = fg.length;
bgs = bg.substring(0, Math.max(0, bgl - fgl));
fgs = fg.substring(Math.max(0, fgl - bgl));
return bgs + fgs;
};
For example:
mask('00000', 11 ); // '00011'
mask('00011','00' ); // '00000'
mask( 2 , 3 ); // '3'
mask('0' ,'111'); // '1'
mask('fork' ,'***'); // 'f***'
mask('_____','dog'); // '__dog'
window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh
window.history.back()
window.location.reload()
However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true
Here is how i did it.
'use strict';
angular.module('tryme5App')
.factory('RouterTracker', function RouterTracker($rootScope) {
var routeHistory = [];
var service = {
getRouteHistory: getRouteHistory
};
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
routeHistory = [];
routeHistory.push({route: from, routeParams: fromParams});
});
function getRouteHistory() {
return routeHistory;
}
return service;
});
Make sure you have included this js file from you index.html
<script src="scripts/components/util/route.service.js"></script>
Now from you stateprovider or controller you can access this service and navigate
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
or alternatively even perform checks and conditional routing
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
$state.go('seat', null, { reload: true });
} else {
window.history.back()
}
Make sure you have added RouterTracker as an argument in your function in my case it was :
.state('seat.new', {
parent: 'seat',
url: '/new',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
$uibModal.open({
//....Open dialog.....
}).result.then(function(result) {
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
}, function() {
$state.go('^');
})
There are subtle differences as to how the fileName
you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream()
and Class.getResourceAsStream()
. These two methods will locate the resource differently.
In Class.getResourceAsStream(path)
, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt")
will look for a file in your classpath at the following location: "java/lang/myfile.txt"
. If your path starts with a /
, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt")
will look at the following location in your class path ./myfile.txt
.
ClassLoader.getResourceAsStream(path)
will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt")
and String.class.getClassLoader().getResourceAsStream("/myfile.txt")
will both look for a file in your classpath at the following location: ./myfile.txt
.
Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.
In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
instead of this.getClass().getClassLoader().getResourceAsStream(fileName)
. this.getClass().getResourceAsStream()
will also work.
Read this article for more detailed information about that particular problem.
One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.
So I've looked at the source code of Tomcat's WebAppClassLoader
for several versions of Tomcat. The implementation of findResource(String name)
(which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.
In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt")
may not produce the same result as classLoader.getResourceAsStream("resource.txt")
event though it should (since that what the Javadoc specifies). [source code]
In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]
As a result, you have to be extra careful when using ClassLoader.getResourceAsStream()
or Class.getResourceAsStream()
on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt")
actually calls classLoader.getResourceAsStream("resource.txt")
(the leading /
is stripped).
open this file: '/usr/share/phpmyadmin/libraries/sql.lib.php'
sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php
press ctrl+w to search (count($analyzed_sql_results['select_expr'] == 1)
Find: count($analyzed_sql_results['select_expr'] == 1)
Replace With: (count($analyzed_sql_results['select_expr']) == 1)
Restart the server
sudo service apache2 restart
moreover, If you still facing same issue then do following.
open this file /usr/share/phpmyadmin/libraries/plugin_interface.lib.php
sudo nano /usr/share/phpmyadmin/libraries/plugin_interface.lib.php
Find : if ($options != null && count($options) > 0) {
Ctrl+w : if ($options != null && count($options) > 0) {
replace with following code
if ($options != null && count((array)$options) > 0) {
now save and restart the server
sudo /etc/init.d/apache2 restart
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.
In the first example the StackTrace will be changed to reflect the current method.
Example:
static string ReadAFile(string fileName) {
string result = string.Empty;
try {
result = File.ReadAllLines(fileName);
} catch(Exception ex) {
throw ex; // This will show ReadAFile in the StackTrace
throw; // This will show ReadAllLines in the StackTrace
}
$('.button1').click(function() {
window.location = "www.example.com/index.php?id=" + this.id;
});
First of all using window.location
is better as according to specification document.location
value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page
And for the second - using attr
jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id
as the value assigned to this
is normal DOM element.
if (value){
value = (value.length > 1) ? value[0].toUpperCase() + value.substr(1).toLowerCase() : value.toUpperCase();
}
For basic data retrieval I would be going for Linq without hesitation.
Since moving to Linq I've found the following advantages:
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
This is very old post but if anyone ran into similar problem and need quick answer:
listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
e.Clicks == 2
The following function can be copied to any object to add an XML save function using the System.Xml namespace.
/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
using (var writer = new System.IO.StreamWriter(FileName))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
}
}
To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.
/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
using (var stream = System.IO.File.OpenRead(FileName))
{
var serializer = new XmlSerializer(typeof([ObjectType]));
return serializer.Deserialize(stream) as [ObjectType];
}
}
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
Since asking the same question but for C++ is considered a duplicate I might as well supply C++ code as an answer.
// hello-2args.cpp
// https://stackoverflow.com/questions/1352749
#include <iostream>
#include <omp.h>
#include <pthread.h>
using namespace std;
typedef struct thread_arguments {
int thrnr;
char *msg;
} thargs_t;
void *print_hello(void *thrgs) {
cout << ((thargs_t*)thrgs)->msg << ((thargs_t*)thrgs)->thrnr << "\n";
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
cout << " Hello C++!\n";
const int NR_THRDS = omp_get_max_threads();
pthread_t threads[NR_THRDS];
thargs_t thrgs[NR_THRDS];
for(int t=0;t<NR_THRDS;t++) {
thrgs[t].thrnr = t;
thrgs[t].msg = (char*)"Hello World. - It's me! ... thread #";
cout << "In main: creating thread " << t << "\n";
pthread_create(&threads[t], NULL, print_hello, &thrgs[t]);
}
for(int t=0;t<NR_THRDS;t++) {
pthread_join(threads[t], NULL);
}
cout << "After join: I am always last. Byebye!\n";
return EXIT_SUCCESS;
}
Compile and run by using one of the following:
g++ -fopenmp -pthread hello-2args.cpp && ./a.out # Linux
g++ -fopenmp -pthread hello-2args.cpp && ./a.exe # MSYS2, Windows
Use Connection.isClosed()
function.
The JavaDoc states:
Retrieves whether this
Connection
object has been closed. A connection is closed if the method close has been called on it or if certain fatal errors have occurred. This method is guaranteed to returntrue
only when it is called after the method Connection.close has been called.
It's very simple.
You create a css property to this image.
img { transition: all 0.3s ease-in-out 0s; }
You add an animation like that:
img:hover
{
cursor: default;
transform: rotate(360deg);
transition: all 0.3s ease-in-out 0s;
}
RESTORE DATABASE {DatabaseName}
FROM DISK = '{databasename}.bak'
WITH REPLACE, RECOVERY
You can use file -i file_name
to check what exactly your original file format is.
Once you get that, you can do the following:
iconv -f old_format -t utf-8 input_file -o output_file
date("Y-m-d",strtotime("last day of +1 month",strtotime($anydate)))
Well array.length
should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent]
from decorator.
import {myDirective} from './myDirective';
Here I what I did to have an ImageButton which always have a width equals to its height (and avoid stupid empty margins in one direction...which I consider a as a bug of the SDK...):
I defined a SquareImageButton class which extends from ImageButton:
package com.myproject;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;
public class SquareImageButton extends ImageButton {
public SquareImageButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public SquareImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public SquareImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
int squareDim = 1000000000;
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int h = this.getMeasuredHeight();
int w = this.getMeasuredWidth();
int curSquareDim = Math.min(w, h);
// Inside a viewholder or other grid element,
// with dynamically added content that is not in the XML,
// height may be 0.
// In that case, use the other dimension.
if (curSquareDim == 0)
curSquareDim = Math.max(w, h);
if(curSquareDim < squareDim)
{
squareDim = curSquareDim;
}
Log.d("MyApp", "h "+h+"w "+w+"squareDim "+squareDim);
setMeasuredDimension(squareDim, squareDim);
}
}
Here is my xml:
<com.myproject.SquareImageButton
android:id="@+id/speakButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="@drawable/icon_rounded_no_shadow_144px"
android:background="#00ff00"
android:layout_alignTop="@+id/searchEditText"
android:layout_alignBottom="@+id/searchEditText"
android:layout_alignParentLeft="true"
/>
Works like a charm !
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
<input type="text" (keypress)="keyPress($event)">
keyPress(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (event.keyCode != 8 && !pattern.test(inputChar)) {
event.preventDefault();
}
}
Chrome 37.
for non fixed table
:
td {
width: 30px;
max-width: 30px;
overflow: hidden;
}
first two important! else - its flow away!
You can do it this way:
xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")
where xml is a XDocument.
Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.
At a place where you want javadoc, type in /**
<NEWLINE> and it will create the template.
Well, wait a minute. I don't think the base tag deserves this bad reputation.
The nice thing about the base tag is that it enables you to do complex URL rewrites with less hassle.
Here's an example. You decide to move http://example.com/product/category/thisproduct to http://example.com/product/thisproduct. You change your .htaccess file to rewrite the first URL to the second URL.
With the base tag in place, you do your .htaccess rewrite and that's it. No problem. But without the base tag, all of your relative links will break.
URL rewrites are often necessary, because tweaking them can help your site's architecture and search engine visibility. True, you'll need workarounds for the "#" and '' problems that folks mentioned. But the base tag deserves a place in the toolkit.
Another option is to add it on the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
... I found this in here
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.
Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .
To stop this behaviour we need to return the function to onClick.
The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!
Use -
onClick={() => { this.props.removeTaskFunction(todo) }}
which means-
var onClick = function() {
return this.props.removeTaskFunction(todo);
}.bind(this);
Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Version ver = assembly.GetName().Version;
Important: It should be noted that this is not the best answer to the original question. Don't forget to read more on this page.
If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().
Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....
You can get all the required file properties by using the code below:
FOR %%? IN (file_to_be_queried) DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Parent Folder : %%~dp?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
Lambda Expression Java 8
In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.
Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Here is an example where a Lambda Expression is used:
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
Random rand = new Random(47);
int i=0;
while(i<5){
i++;
int key = rand.nextInt(20);
int value = rand.nextInt(50);
System.out.println("Inserting key: "+key+" Value: "+value);
Integer imap =hm.put(key,value);
if( imap == null){
System.out.println("Inserted");
}
else{
System.out.println("Replaced with "+imap);
}
}
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Output:
Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
Also one can use Spliterator for the same.
Spliterator sit = hm.entrySet().spliterator();
UPDATE
Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
The below code is working,
<style>
.PanelFloat {
position: fixed;
overflow: hidden;
z-index: 2400;
opacity: 0.70;
right: 30px;
top: 0px !important;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
</style>
<script>
//The below script will keep the panel float on normal state
$(function () {
$(document).on('scroll', function () {
//Multiplication value shall be changed based on user window
$('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
});
});
//To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
$(document).on('click', '.btnSearchView', function () {
$('#MyFloatPanel').addClass('PanelFloat');
});
$(document).on('click', '.btnSearchClose', function () {
$('#MyFloatPanel').removeClass('PanelFloat');
});
</script>
<div class="col-lg-12 col-md-12">
<div class="col-lg-8 col-md-8" >
//My scrollable content is here
</div>
//This below panel will float while scrolling the above div content
<div class="col-lg-4 col-md-4" id="MyFloatPanel">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">Panel Head </div>
<div class="panel-body ">//Your panel content</div>
</div>
</div>
</div>
</div>
One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)
See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software https://github.com/sockjs/sockjs-client/issues/94
I assume there aren't as many issues with Server-Sent Events. But I don't know.
That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)
Adding an item to the list:
List< ? extends X > doesn't allow to add anything, except for null
into the list.
List< ? super X > allows to add anything that is-a X (X or its subtype), or null.
Getting an item from the list:
Object
.Some examples:
List<? extends Number> list1 = new ArrayList<Integer>();
list1.add(null); //OK
Number n = list1.get(0); //OK
Serializable s = list1.get(0); //OK
Object o = list1.get(0); //OK
list1.add(2.3); //ERROR
list1.add(5); //ERROR
list1.add(new Object()); //ERROR
Integer i = list1.get(0); //ERROR
List<? super Number> list2 = new ArrayList<Number>();
list2.add(null); //OK
list2.add(2.3); //OK
list2.add(5); //OK
Object o = list2.get(0); //OK
list2.add(new Object()); //ERROR
Number n = list2.get(0); //ERROR
Serializable s = list2.get(0); //ERROR
Integer i = list2.get(0); //ERROR
For me the accepted answer did not yet work. I started off as suggested here:
ln -s /usr/bin/nodejs /usr/bin/node
After doing this I was getting the following error:
/usr/local/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3
The solution was to download the most recent version of node from https://nodejs.org/en/download/ .
Then I did:
sudo tar -xf node-v10.15.0-linux-x64.tar.xz --directory /usr/local --strip-components 1
Now the update was finally successful: npm -v
changed from 3.2.1 to 6.4.1
You are looking for the jQuery extend method. This will allow you to add other members to your already created JS object.
Mathematicians have their own little funny ways, so instead of saying "then we call function f
passing it x
as a parameter" as we programmers would say, they talk about "applying function f
to its argument x
".
In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia
apply
serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int
parameter and returns an Int
will have OO type of Function1[Int,Int]
.
// define a function in scala
(x:Int) => x + 1
// assign an object representing the function to a variable
val f = (x:Int) => x + 1
Since everything is an object in Scala f
can now be treated as a reference to Function1[Int,Int]
object. For example, we can call toString
method inherited from Any
, that would have been impossible for a pure function, because functions don't have methods:
f.toString
Or we could define another Function1[Int,Int]
object by calling compose
method on f
and chaining two different functions together:
val f2 = f.compose((x:Int) => x - 1)
Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply
method on the Function1[Int,Int]
object:
f2.apply(2)
Writing f.apply(args)
every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args)
. That's where Scala compiler steps in and whenever we have a reference f
to a function object and write f (args)
to apply arguments to the represented function the compiler silently expands f (args)
to the object method call f.apply (args)
.
Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply
method. Such objects can be used in the function notation:
// we will be able to use this object as a function, as well as an object
object Foo {
var y = 5
def apply (x: Int) = x + y
}
Foo (1) // using Foo object in function notation
There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply
object to a set of arguments to create a new instance of an associated class:
List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation
// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3)
So apply
method is just a handy way of closing the gap between functions and objects in Scala.
If you are using redux and redux-thunk the best solution will be using react-router-redux
// then, in redux actions for example
import { push } from 'react-router-redux'
dispatch(push('/some/path'))
It's important to see the docs to do some configurations.
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.
Using Lloyd's clue, the following batch file (.bat) worked for me.
Type the tab character within the double quotes.
C:\>cat foo.bat
sort -k3 -t" " tabfile.txt
Instead of this LAST_INSERT_ID()
try to use this one
mysqli_insert_id(connection)
I encounter similar situation. I would like to have background of the last .item
to be yellow in the elements that look like...
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
...
<div class="item">item x</div>
<div class="other">I'm here for some reasons</div>
</div>
I use nth-last-child(2)
to achieve it.
.item:nth-last-child(2) {
background-color: yellow;
}
It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick
Have you tried using :
git dif | grep -B <number of before lines to show> <regex>
In my case, i try to search where do i put a debug statement in the many files, i need to see which file already got this debug statement like this :
git diff | grep -B 5 dd\(
My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.
SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;
Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.
You use an addtional attribute; fill-opacity
: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.
For example:
<rect ... fill="#044B94" fill-opacity="0.4"/>
Additionally you have the following:
stroke-opacity
attribute for the strokeopacity
for the entire object1) paste the myapp.apk in platform-tools folder , in my case C:\Users\mazbizxam\AppData\Local\Android\android-sdk\platform-tools, this is the link in my case it may change to you people
2)open the directory in CMD CD C:\Users\mazbizxam\AppData\Local\Android\android-sdk\platform-tools
3)Now you are in platform-tools folder , just type adb install myapp.apk
please ensure that your emulator is turn on , if every thing is ok apk will install
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
it could be done when the RowDataBound
event fires
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Hide the edit button when some condition is true
// for example, the row contains a certain property
if (someCondition)
{
Button btnEdit = (Button)e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
}
Here's a demo page
markup
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView OnRowDataBound Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="name" />
<asp:BoundField HeaderText="Age" DataField="age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace GridViewDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
protected override void OnInit(EventArgs e)
{
GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
base.OnInit(e);
}
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
int age;
if (int.TryParse(e.Row.Cells[1].Text, out age))
if (age == 30)
{
Button btnEdit = (Button) e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
private static List<Customer> GetCustomers()
{
List<Customer> results = new List<Customer>();
results.Add(new Customer("Steve", 30));
results.Add(new Customer("Brian", 40));
results.Add(new Customer("Dave", 50));
results.Add(new Customer("Bill", 25));
results.Add(new Customer("Rich", 22));
results.Add(new Customer("Bert", 30));
return results;
}
}
public class Customer
{
public string Name {get;set;}
public int Age { get; set; }
public Customer(string name, int age)
{
Name = name;
Age = age;
}
}
}
In the demo, the Edit Button is not Visible (the HTML markup is not sent to the client) in those rows where the Customer's age is 30.
The cause of my installation failure:
install.sh
inserts path.bash.inc
into my .bash_profile
fix:
cd [whereever]/google-cloud-sdk && ./install.sh
vi ~/.bash_profile
path.bash.inc
with path.zsh.inc
os config:
ref:
You can use this ng-switch:
<div ng-app ng-controller="friendsCtrl">
<label>Search: </label><input ng-model="searchText" type="text">
<div ng-init="filtered = (friends | filter:searchText)">
<h3>'Found '{{(friends | filter:searchText).length}} friends</h3>
<div ng-switch="(friends | filter:searchText).length">
<span class="ng-empty" ng-switch-when="0">No friends</span>
<table ng-switch-default>
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</tbody>
</table>
</div>
varbinary(max)
is the way to go (introduced in SQL Server 2005)
Just FYI, if you are unable to set any locale, the problem might be below attribute in your app level gradle file:
resConfigs "en", "hi" //to specify allowed locales for your app
So, if you want to support any locale other than English and Hindi, specify your locale here or just remove above line. By default your app will support all the locales.
Thanks :)
I encountered the exact same problem today, Ryan.
In my src (or your root) directory, my log4j.properties file now has the following addition
# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN
Thanks for the heads up as to how to do this, Benjamin.
select 'abcd' + ltrim(str(1)) + ltrim(str(2))
This image presents both orientation(Landscape/Portrait)
To get MaxX and MaxY, read on.
For Android device screen coordinates, below concept will work.
Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x;
int maxY = mdispSize.y;
EDIT:- ** **for devices supporting android api level older than 13. Can use below code.
Display mdisp = getWindowManager().getDefaultDisplay();
int maxX= mdisp.getWidth();
int maxY= mdisp.getHeight();
(x,y) :-
1) (0,0) is top left corner.
2) (maxX,0) is top right corner
3) (0,maxY) is bottom left corner
4) (maxX,maxY) is bottom right corner
here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.
So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.
One way I solved this problem was by making the beginning of the path relative. For your case:
gulp.src([
'index.php',
'*css/**/*',
'*js/**/*',
'*src/**/*',
])
.pipe(gulp.dest('/var/www/'));
The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)
This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/
at the same level as js
, you would end up matching both.
This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.