copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
dst
to be a directory (instead of the complete target filename), in which case the basename of src
is used for creating the new file;Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
Based upon your source variable (sourcePath = "C:\Minecraft\bin\"
) I suspect your hard code is pointing at the wrong place
fso.CopyFile "C:\Minecraft\options.txt", destinationPath, false
should be
fso.CopyFile "C:\Minecraft\bin\options.txt", destinationPath
or
fso.CopyFile sourcePath & "options.txt", destinationPath
docker run -dit --rm IMAGE
docker cp CONTAINER:SRC_PATH DEST_PATH
https://docs.docker.com/engine/reference/commandline/run/ https://docs.docker.com/engine/reference/commandline/cp/
It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.
Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)
byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations
You see that we simply apply the .decode(utf8)
function.
https://docs.python.org/3.3/library/stdtypes.html#bytes
https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals
stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "u" | "R" | "U"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
stringescapeseq ::= "\" <any source character>
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
Here's a good place to use the FormArray
https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
To start we'll build up our array of controls either with a FormBuilder
or newing up a FormArray
FormBuilder
this.checkboxGroup = _fb.group({
myValues: _fb.array([true, false, true])
});
new FormArray
let checkboxArray = new FormArray([
new FormControl(true),
new FormControl(false),
new FormControl(true)]);
this.checkboxGroup = _fb.group({
myValues: checkboxArray
});
Easy enough to do, but then we're going to change our template and let the templating engine handle how we bind to our controls:
template.html
<form [formGroup]="checkboxGroup">
<input *ngFor="let control of checkboxGroup.controls['myValues'].controls"
type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>
Here we're iterating over our set of FormControls
in our myValues
FormArray
and for each control we're binding [formControl]
to that control instead of to the FormArray
control and <div>{{checkboxGroup.controls['myValues'].value}}</div>
produces true,false,true
while also making your template syntax a little less manual.
You can use this example: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview to poke around
Have you tried using a simple img tag?
<img scr="https://www.typomania.co.uk/pdfs/lipsum.pdf">
Maybe something turns off error output. (I understand that you are trying to say that other scripts properly output their errors to the errorlog?)
You could start debugging the script by determining where it exits the script (start by adding a echo 1; exit;
to the first line of the script and checking whether the browser outputs 1
and then move that line down).
I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent
as a parameter to the YouTube URL:
<iframe title=<your frame title goes here>
src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"
scrolling="no"
frameborder="0"
width="640"
height="390"
style="border:none;">
</iframe>
This allows the iframe to inherit the z-index of its container so your opaque <div>
would be in front of the iframe.
If you wish to escape HTML in a URL:
This is probably NOT what the OP wanted (the question doesn't clearly indicate in which context the escaping is meant to be used), but Python's native library urllib has a method to escape HTML entities that need to be included in a URL safely.
The following is an example:
#!/usr/bin/python
from urllib import quote
x = '+<>^&'
print quote(x) # prints '%2B%3C%3E%5E%26'
The server name should be same as the first/last name which you give while create a certificate
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Try this to get all the list at first, then your desired element (say the First in your case):
var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem =>
{
desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();
To get directly the first element value without a lot of foreach iteration and variable assignment:
var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.
Same result, different computation ;)
Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.
E.g. jumps would be generated as relative rather than absolute.
Pseudo-assembly:
PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP
Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP
EDIT: In response to comment.
If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.
partials are incredibly useful.
For instance, in a 'pipe-lined' sequence of function calls (in which the returned value from one function is the argument passed to the next).
Sometimes a function in such a pipeline requires a single argument, but the function immediately upstream from it returns two values.
In this scenario, functools.partial
might allow you to keep this function pipeline intact.
Here's a specific, isolated example: suppose you want to sort some data by each data point's distance from some target:
# create some data
import random as RND
fnx = lambda: RND.randint(0, 10)
data = [ (fnx(), fnx()) for c in range(10) ]
target = (2, 4)
import math
def euclid_dist(v1, v2):
x1, y1 = v1
x2, y2 = v2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
To sort this data by distance from the target, what you would like to do of course is this:
data.sort(key=euclid_dist)
but you can't--the sort method's key parameter only accepts functions that take a single argument.
so re-write euclid_dist
as a function taking a single parameter:
from functools import partial
p_euclid_dist = partial(euclid_dist, target)
p_euclid_dist
now accepts a single argument,
>>> p_euclid_dist((3, 3))
1.4142135623730951
so now you can sort your data by passing in the partial function for the sort method's key argument:
data.sort(key=p_euclid_dist)
# verify that it works:
for p in data:
print(round(p_euclid_dist(p), 3))
1.0
2.236
2.236
3.606
4.243
5.0
5.831
6.325
7.071
8.602
Or for instance, one of the function's arguments changes in an outer loop but is fixed during iteration in the inner loop. By using a partial, you don't have to pass in the additional parameter during iteration of the inner loop, because the modified (partial) function doesn't require it.
>>> from functools import partial
>>> def fnx(a, b, c):
return a + b + c
>>> fnx(3, 4, 5)
12
create a partial function (using keyword arg)
>>> pfnx = partial(fnx, a=12)
>>> pfnx(b=4, c=5)
21
you can also create a partial function with a positional argument
>>> pfnx = partial(fnx, 12)
>>> pfnx(4, 5)
21
but this will throw (e.g., creating partial with keyword argument then calling using positional arguments)
>>> pfnx = partial(fnx, a=12)
>>> pfnx(4, 5)
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
pfnx(4, 5)
TypeError: fnx() got multiple values for keyword argument 'a'
another use case: writing distributed code using python's multiprocessing
library. A pool of processes is created using the Pool method:
>>> import multiprocessing as MP
>>> # create a process pool:
>>> ppool = MP.Pool()
Pool
has a map method, but it only takes a single iterable, so if you need to pass in a function with a longer parameter list, re-define the function as a partial, to fix all but one:
>>> ppool.map(pfnx, [4, 6, 7, 8])
You can specialize your templates based on what's passed into their parameters like this:
template <> void foo<animal> {
}
Note that this creates an entirely new function based on the type that's passed as T
. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.
The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):
$.getJSON("json/products.json").done(function (data) {
var allProducts = [data].map(function (item) {
return new getData(item);
});
});
Here, [data] is an array, and the ".map" method can be used on it. It works for me!
textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);
This will set gravity of your textview.
After trial and error I came up with this function, works with iframe too.
function bringElIntoView(el) {
var elOffset = el.offset();
var $window = $(window);
var windowScrollBottom = $window.scrollTop() + $window.height();
var scrollToPos = -1;
if (elOffset.top < $window.scrollTop()) // element is hidden in the top
scrollToPos = elOffset.top;
else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
if (scrollToPos !== -1)
$('html, body').animate({ scrollTop: scrollToPos });
}
Bootstrap by default can scale up to 12 columns? This means if we want to create a 12-column layout of equal width, we would write inside div class="col-md-1" twelve times.
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">1</div>
<div class="col-md-2">2</div>
<div class="col-md-2">3</div>
<div class="col-md-2">4</div>
<div class="col-md-2">5</div>
<div class="col-md-1"></div>
</div>
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
using (B a = new B())
{
DoSomethingWith(a);
}
is equivalent to
B a = new B();
try
{
DoSomethingWith(a);
}
finally
{
((IDisposable)a).Dispose();
}
If you happen to use CRA with default yarn
package manager use the following. Worked for me.
yarn remove node-sass
yarn add [email protected]
The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.
Launch Powershell or CMD, enter ssh yourAccountName@diskstation
The first time it will cache off your certificate.
Further detailed explanations can be found on the synology docs page:
The simplest approach if you are sure the file physically exists on the disk:
Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)
If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:
fileName = Mid(filePath, InStrRev(filePath, "\") + 1)
if you are using centOs then use
sudo chown -R centos:centos /var/www/html
sudo chmod -R 755 /var/www/html
For Ubuntu
sudo chown -R ubuntu:ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
For Amazon ami
sudo chown -R ec2-user:ec2-user /var/www/html
sudo chmod -R 755 /var/www/html
I hope this will help you:
final TextView t1=new TextView(this);
t1.setText("Hello Android");
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
t1.setTextSize(progress);
Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();
}
});
$('#element').on('change', function() {
$(this).val($(this).prop("defaultValue"));
});
Vohuman's answer lead me to my own implementation:
$(document).on("vclick", ".className", function() {
// Whatever you want to do
});
Instead of:
$(document).ready(function($) {
$('.className').click(function(){
// Whatever you want to do
});
});
I hope this helps!
Just an update for Mysqli users :
$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase);
if (mysqli_connect_errno())
die('Could not connect: ' . mysql_error());
$return_arr = array();
if ($result = mysqli_query( $base, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
}
mysqli_close($base);
echo json_encode($return_arr);
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
The following bash code will pass $file to command where $file will represent every file in /dir
for file in /dir/*
do
cmd [option] "$file" >> results.out
done
Example
el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt
If you have several threads executing the methods m1 and m2 in the code below:
class SomeClass {
private int i = 0;
public void m1() { i = 5; }
public int m2() { return i; }
}
you have the guarantee that any thread calling m2
will either read 0 or 5.
On the other hand, with this code (where i
is a long):
class SomeClass {
private long i = 0;
public void m1() { i = 1234567890L; }
public long m2() { return i; }
}
a thread calling m2
could read 0, 1234567890L, or some other random value because the statement i = 1234567890L
is not guaranteed to be atomic for a long
(a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i
in between).
This module works well for comparing two fields. Works great with Angular 1.3+. Simple to use https://www.npmjs.com/package/angular-password
It also allows saving the module as a generic. Just include them in packages list of your module.
A quick fix to "plot overlap" is to use plt.tight_layout():
for i,var in enumerate(categorical_variables):
plt.title(var)
plt.xticks(rotation=45)
df[var].hist()
plt.subplot(len(categorical_variables)/2, 2, i+1)
plt.tight_layout()
There are 2 scenario's where Bash performance is at least equal I believe:
That said, I usually don't really concern myself with performance of the scripting language itself. If performance is a real issue you don't script but program (possibly in Python).
This is how I solved it on Windows. I have git installed separately, and Idea just picks git's options automatically (Default Idea config, as I would get from clean installer).
Open the project in the command line. Make some changes there. And commit and push files via git which is installed on my machine. During push it will open a windows asking me to enter username and password. After that, when I make a commit-push from idea, it will simply work.
It works for me:
=SUMPRODUCT(NOT(ISBLANK(F2:F)))
Count of all non-empty cells from F2 to the end of the column
It worked for me, when I set error_reporting in two places at same time
somewhere in PHP code
ini_set('error_reporting', 30711);
and in .htaccess file
php_value error_reporting 30711
$this
is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
if
takes a command and checks its return value. [
is just a command.
if grep -q ...
then
....
else
....
fi
Simple elegant working solution:
img {
width: 600px; /*width of parent container*/
height: 350px; /*height of parent container*/
object-fit: contain;
position: relative;
top: 50%;
transform: translateY(-50%);
}
There are now safer methods to accomplish this. The docs have been updated with these methods.
Other Methods
Easiest - Use Unicode, save the file as UTF-8 and set the charset
to UTF-8.
<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using dangerouslySetInnerHTML
.
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
A non-committed transaction can be reverted by issuing the command ROLLBACK
But if you are running in auto-commit mode there is nothing you can do....
The easiest way as many have mentioned already is to do a DESCRIBE TABLE
However you can also get some the same + additional information from
db2> SELECT * SYSCAT.TABLES
db2> SELECT * FROM SYSCAT.COLUMNS
I usually use SYSCAT.COLUMNS to find the related tables in the database where I already know the column name :)
Another good way if you want to get the DDL of a particular table or the whole database is to use the db2look
# db2look -d *dbname* -t *tablename* > tablestructure.out
This will generate the ".out" file for you which will contain the particular table's DDL script.
# db2look -d *dbname* -e > dbstructure.out
This will generate the entire database's DDL as a single script file, this is usually used to replicate the database, "-e" is to indicate that one wants to export DDL suitable recreate exact same setup in a new database.
Hope this can help someone looking for such answers :)
Weirdly, I found that REMOVING &characterEncoding=UTF-8
from the JDBC url
did the trick for me with similar issues.
Based on my properties,
jdbc_url=jdbc:mysql://localhost:3306/dbName?useUnicode=true
I think this supports what @Esailija has said above, i.e. my MySQL, which is indeed 5.5, is figuring out its own favorite flavor of UTF-8 encoding.
(Note, I'm also specifying the InputStream
I'm reading from as UTF-8
in the java code, which probably doesn't hurt)...
Add "\"
before double quote to escape it, instead of \
#! /bin/csh -f
set dbtable = balabala
set dbload = "load data local infile "\""'gfpoint.csv'"\"" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"\""' LINES TERMINATED BY "\""'\n'"\"" IGNORE 1 LINES"
echo $dbload
# load data local infile "'gfpoint.csv'" into table balabala FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "''" IGNORE 1 LINES
I am a little late, but if you like fluent interface you might design your setters for chained calls like this:
type myType struct {
s string
a, b int
}
func New(s string, err *error) *myType {
if s == "" {
*err = errors.New(
"Mandatory argument `s` must not be empty!")
}
return &myType{s: s}
}
func (this *myType) setA (a int, err *error) *myType {
if *err == nil {
if a == 42 {
*err = errors.New("42 is not the answer!")
} else {
this.a = a
}
}
return this
}
func (this *myType) setB (b int, _ *error) *myType {
this.b = b
return this
}
And then call it like this:
func main() {
var err error = nil
instance :=
New("hello", &err).
setA(1, &err).
setB(2, &err)
if err != nil {
fmt.Println("Failed: ", err)
} else {
fmt.Println(instance)
}
}
This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:
err
variable and zeroing it.There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.
Just add @pause
at the end.
Example:
@echo off
ipconfig
@pause
Or you can also use:
cmd /k ipconfig
If you wanna add autoplay function to it. Simply replace
this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
with
this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
also you can do the same with vimeo
this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
with
this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',
You can use this little PHP library. It sends the headers and give you an object to use it easily.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
Suppose the data is in the B column, write in the C column the formula:
=SUBSTITUTE(B1," ","")
Copy&Paste the formula in the whole C column.
edit: using commas or semicolons as parameters separator depends on your regional settings (I have to use the semicolons). This is weird I think. Thanks to @tocallaghan and @pablete for pointing this out.
if the page have one <a>
It Works,but,many <a>
,have to use var href = $(this).attr('href');
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Style1.java
*
* Created on May 5, 2011, 6:31:16 AM
*/
package Test;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author Sameera
*/
public class Style2 extends javax.swing.JFrame {
/** Creates new form Style1 */
public Style2() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
cmd_SH = new javax.swing.JButton();
pnl_2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
cmd_SH.setText("Hide");
cmd_SH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmd_SHActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(558, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(236, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2);
pnl_2.setLayout(pnl_2Layout);
pnl_2Layout.setHorizontalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 621, Short.MAX_VALUE)
);
pnl_2Layout.setVerticalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(evt.getActionCommand());
if (evt.getActionCommand().equals("Hide")) {
pnl_2.setVisible(false);
cmd_SH.setText("Show");
this.setSize(643, 294);
this.pack();
}
if (evt.getActionCommand().equals("Show")) {
pnl_2.setVisible(true);
cmd_SH.setText("Hide");
this.setSize(643, 583);
this.pack();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Style1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmd_SH;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel pnl_2;
// End of variables declaration
}
these solutions are more faster (about 11%) than using numel
;)
for idx = reshape(array,1,[]),
element = element + idx;
end
or
for idx = array(:)',
element = element + idx;
end
UPD. tnx @rayryeng for detected error in last answer
The timing information that this post has referenced is incorrect and inaccurate due to a fundamental typo that was made (see comments stream below as well as the edit history - specifically look at the first version of this answer). Caveat Emptor.
I just added JS
part of bootstrap
to my index page, then it worked
Paste this, if you're using the latest version of bootstrap
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
You Must use
-(void)viewWillAppear:(BOOL)animated
and set your entries like you want...
Do you have an activity set up the be the launched activity when the application starts?
This is done in your Manifest.xml file, something like:
<activity android:name=".Main" android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
100% robust approach.
In my case, I didn't have access to the XML layout source file, since I get Checkbox from a 3-rd party MaterialDialog lib. So I have to solve this programmatically.
res/color/checkbox_tinit_dark_theme.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white"
android:state_checked="false"/>
<item android:color="@color/positiveButtonBg"
android:state_checked="true"/>
</selector>
Then apply it to the checkbox:
ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme);
CompoundButtonCompat.setButtonTintList(checkbox, darkStateList);
P.S. In addition if someone is interested, here is how you can get your checkbox from MaterialDialog dialog (if you set it with .checkBoxPromptRes(...)
):
CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);
Hope this helps.
Here's a creative idea using box-shadow
:
#header {
background-image: url("apple.jpg");
box-shadow: inset 0 0 99999px rgba(0, 120, 255, 0.5);
}
The background
sets the background for your element.
The box-shadow
is the important bit. It basically sets a really big shadow on the inside of the element, on top of the background, that is semi-transparent
Create a Hashtable called "Properties" and add your properties to it.
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterpressing Enter when the focus in on a form control (input) normally triggers a submit
(onSubmit) event on the form itself (not the input) so you could bind your this.handleInput
to the form onSubmit.
Alternatively you could bind it to the blur
(onBlur) event on the input
which happens when the focus is removed (e.g. tabbing to the next element that can get focus)
Do i really have to copy all constructors from
Foo
intoBar
andBah
? And then if i change a constructor signature inFoo
, do i have to update it inBar
andBah
?
Yes, if you use constructors to create instances.
Is there no way to inherit constructors?
Nope.
Is there no way to encourage code reuse?
Well, I won't get into whether inheriting constructors would be a good or bad thing and whether it would encourage code reuse, since we don't have them and we're not going to get them. :-)
But here in 2014, with the current C#, you can get something very much like inherited constructors by using a generic create
method instead. It can be a useful tool to have in your belt, but you wouldn't reach for it lightly. I reached for it recently when faced with needing to pass something into the constructor of a base type used in a couple of hundred derived classes (until recently, the base didn't need any arguments, and so the default constructor was fine — the derived classes didn't declare constructors at all, and got the automatically-supplied one).
It looks like this:
// In Foo:
public T create<T>(int i) where: where T : Foo, new() {
T obj = new T();
// Do whatever you would do with `i` in `Foo(i)` here, for instance,
// if you save it as a data member; `obj.dataMember = i;`
return obj;
}
That says that you can call the generic create
function using a type parameter which is any subtype of Foo
that has a zero-arguments constructor.
Then, instead of doing Bar b new Bar(42)
, you'd do this:
var b = Foo.create<Bar>(42);
// or
Bar b = Foo.create<Bar>(42);
// or
var b = Bar.create<Bar>(42); // But you still need the <Bar> bit
// or
Bar b = Bar.create<Bar>(42);
There I've shown the create
method being on Foo
directly, but of course it could be in a factory class of some sort, if the information it's setting up can be set by that factory class.
Just for clarity: The name create
isn't important, it could be makeThingy
or whatever else you like.
Full Example
using System.IO;
using System;
class Program
{
static void Main()
{
Bar b1 = Foo.create<Bar>(42);
b1.ShowDataMember("b1");
Bar b2 = Bar.create<Bar>(43); // Just to show `Foo.create` vs. `Bar.create` doesn't matter
b2.ShowDataMember("b2");
}
class Foo
{
public int DataMember { get; private set; }
public static T create<T>(int i) where T: Foo, new()
{
T obj = new T();
obj.DataMember = i;
return obj;
}
}
class Bar : Foo
{
public void ShowDataMember(string prefix)
{
Console.WriteLine(prefix + ".DataMember = " + this.DataMember);
}
}
}
The CloseReason
enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...
You can do different actions, according to the reason, like:
void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
// Prompt user to save his data
if(e.CloseReason == CloseReason.WindowsShutDown)
// Autosave and clear up ressources
}
But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a CloseReason.UserClosing
reason.
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.
It means that a Lambda expression of type TDelegate
which contains a ([parameters]) => { some code };
cannot be converted to an Expression<TDelegate>
. It's the rule.
Simplify your query. The one you provided can be rewritten as the following and will compile:
Arr[] myArray = objects.Select(o => new Obj()
{
Var1 = o.someVar,
Var2 = o.var2
} ).ToArray();
There is no str
accessor for datetimes and you can't do dates.astype(str)
either, you can call apply
and use datetime.strftime
:
In [73]:
dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0 2001-01-01
1 2001-03-31
dtype: object
You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.
Update
As of version 0.17.0
you can do this using dt.strftime
dates.dt.strftime('%Y-%m-%d')
will now work
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
I suspect that your GIT_SSH
environment variable is set to %ProgramFiles(x86)%\putty\plink.exe
.
For some reason, PLink does not use the .ssh/known_hosts
file in your user directory to store the remote hosts keys.
If this is actually your case, and it might be so on purpose if you want to use pageant, you need to use PLink to connect to the host first.
"$GIT_SSH" user@hostname
You should get a similar message
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
Once you have answered y
to the question and successfully connected to the remote host, you should be all set. Go ahead and try your push again.
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
Check name folder too long or not.
Why don't you examine System.getProperty("os.arch")
value in your code?
In ASP.NET MVC 4, the namespace is not System.Web.WebPages.Razor, but System.Web.Razor
That worked for me, change your web.config.
Goto Nuget Package manager and search for openxml. And install DocumentFormat.OpenXml
simply change <div>
to <tbody>
<table id="authenticationSetting" style="display: none">
<tbody id="authenticationOuterIdentityBlock" style="display: none;">
<tr>
<td class="orionSummaryHeader">
<orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
<td class="orionSummaryColumn">
<orion:textbox id="authenticationOuterIdentity" size="30" />
</td>
</tr>
</tbody>
</table>
Create a new Date()
object and call getFullYear()
:
new Date().getFullYear()
// returns the current year
Hijacking the accepted answer to provide some basic example context like a footer that always shows the current year:
<footer>
© <span id="year"></span>
</footer>
Somewhere else executed after the HTML above has been loaded:
<script>
document.getElementById("year").innerHTML = new Date().getFullYear();
</script>
document.getElementById("year").innerHTML = new Date().getFullYear();
_x000D_
footer {_x000D_
text-align: center;_x000D_
font-family: sans-serif;_x000D_
}
_x000D_
<footer>_x000D_
© <span id="year">2018</span> by FooBar_x000D_
</footer>
_x000D_
None of the answers here worked for me. What I had to do is:
After that it works fine.
<!DOCTYPE html>
<html>
<head></head>
<body>
<p data-foo="0"></p>
<h6 data-foo="1"></h6>
<script>
var a = document.querySelectorAll('[data-foo]');
for (var i in a) if (a.hasOwnProperty(i)) {
alert(a[i].getAttribute('data-foo'));
}
</script>
</body>
</html>
HTML Code
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" class="send_upload" value="upload" />
jQuery Code using bind method
$(document).ready(function() {
$('#upload').bind("click",function()
{ if(!$('#uploadImage').val()){
alert("empty");
return false;} }); });
I see this subject is not solved. I coded this and it's working very well. It insert a tabulation at the cursor index. Without using jquery
<textarea id="myArea"></textarea>
<script>
document.getElementById("myArea").addEventListener("keydown",function(event){
if(event.code==="Tab"){
var cIndex=this.selectionStart;
this.value=[this.value.slice(0,cIndex),//Slice at cursor index
"\t", //Add Tab
this.value.slice(cIndex)].join('');//Join with the end
event.stopPropagation();
event.preventDefault(); //Don't quit the area
this.selectionStart=cIndex+1;
this.selectionEnd=cIndex+1; //Keep the cursor in the right index
}
});
</script>
You could do this (ugly but it works):
INSERT INTO dbo.MyTable (ID, Name)
select * from
(
select 123, 'Timmy'
union all
select 124, 'Jonny'
union all
select 125, 'Sally'
...
) x
An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.
Change USER_NAME and FOLDER in accordance to your computer.
For Windows
driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")
For Linux/Mac
driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")
You can try element[0].scrollTop, in my opinion this solution is faster.
Here you have bigger example - http://cvmlrobotics.blogspot.de/2013/03/angularjs-get-element-offset-position.html
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
You should add return statement while you are forwarding or redirecting the flow.
Example:
if forwardind,
request.getRequestDispatcher("/abs.jsp").forward(request, response);
return;
if redirecting,
response.sendRedirect(roundTripURI);
return;
as prior ans remove the height attrib. if u want your expansion along with its min height then use min-height: 102px
instead of height: 102px.
note ie 6 and min-height http://www.dustindiaz.com/min-height-fast-hack/
I like visual answers.
When you click #btn
, two event handlers get called and they output what you see in the picture.
Demo here: https://jsfiddle.net/ujhe1key/
The same error solved like this
using UnityEngine;
using System.Collections;
using UnityEditor.Callbacks;
using UnityEditor;
using System;
using UnityEditor.iOS.Xcode;
using System.IO;
public class AutoIncrement : MonoBehaviour {
[PostProcessBuild]
public static void ChangeXcodePlist(BuildTarget buildTarget, string pathToBuiltProject)
{
if (buildTarget == BuildTarget.iOS)
{
// Get plist
string plistPath = pathToBuiltProject + "/Info.plist";
var plist = new PlistDocument();
plist.ReadFromString(File.ReadAllText(plistPath));
// Get root
var rootDict = plist.root;
// Change value of NSCameraUsageDescription in Xcode plist
var buildKey = "NSCameraUsageDescription";
rootDict.SetString(buildKey, "Taking screenshots");
var buildKey2 = "ITSAppUsesNonExemptEncryption";
rootDict.SetString(buildKey2, "false");
// Write to file
File.WriteAllText(plistPath, plist.WriteToString());
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
//A new build has happened so lets increase our version number
BumpBundleVersion();
}
// Bump version number in PlayerSettings.bundleVersion
private static void BumpBundleVersion()
{
float versionFloat;
if (float.TryParse(PlayerSettings.bundleVersion, out versionFloat))
{
versionFloat += 0.01f;
PlayerSettings.bundleVersion = versionFloat.ToString();
}
}
[MenuItem("Leman/Build iOS Development", false, 10)]
public static void CustomBuild()
{
BumpBundleVersion();
var levels= new String[] { "Assets\\ShootTheBall\\Scenes\\MainScene.unity" };
BuildPipeline.BuildPlayer(levels,
"iOS", BuildTarget.iOS, BuildOptions.Development);
}
}
For android 2.2+ (api level8), you can use ScaleGestureDetector.
you need a member:
private ScaleGestureDetector mScaleDetector;
in your constructor (or onCreate()) you add:
mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
return false;
}
});
You override onTouchEvent:
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
return true;
}
If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().
CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.
Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.
Try something like this:
var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
//your code when success
}).
error(function(status) {
//your code when fails
});
You can use this method for any minute / hour / period (aka am/pm) combination:
- (NSDate *)todayModifiedWithHours:(NSString *)hours
minutes:(NSString *)minutes
andPeriod:(NSString *)period
{
NSDate *todayModified = NSDate.date;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];
[components setMinute:minutes.intValue];
int hour = 0;
if ([period.uppercaseString isEqualToString:@"AM"]) {
if (hours.intValue == 12) {
hour = 0;
}
else {
hour = hours.intValue;
}
}
else if ([period.uppercaseString isEqualToString:@"PM"]) {
if (hours.intValue != 12) {
hour = hours.intValue + 12;
}
else {
hour = 12;
}
}
[components setHour:hour];
todayModified = [calendar dateFromComponents:components];
return todayModified;
}
Requested Example:
NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
minutes:@"00"
andPeriod:@"am"];
How to kill a windows service using PID -
netstat -ano
taskkill /f /pid 5760
Thanks
The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User)
property.
Extending the existing User model
…
If you wish to store information related to
User
, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.
That said, extending django.contrib.auth.models.User
and supplanting it also works...
Substituting a custom User model
Some kinds of projects may have authentication requirements for which Django’s built-in
User
model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.[Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]
I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.
Newest version has better support literally for any generated Makefiles, through the compiledb
Three steps:
install compiledb
pip install compiledb
run a dry make
compiledb -n make
(do the autogen, configure if needed)
there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3
Orignal post: Working with Makefiles in CLion using Compilation DB
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
}
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );
bufferedImage will contain a full screenshot, this was tested with three monitors
you want these four lines of code in your Run.bat:
@echo off //this makes it so you have an empty cmd window on startup
javac Main.java //this compiles the .java into a .class
java Main // this runs the .class file
pause //this prevents the window from instantly closing after program end
Pretty straight forward, use relative path
string[] offerFiles = Directory.GetFiles(Server.MapPath("~/offers"), "*.csv");
try using getchar(); instead
syntax:
void main() {
char ch;
ch = getchar();
}
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
Python Extension. From the Python Docs:
The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).
Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python
That's because, it gets returned after validateView();;
Use this:
OnClientClick="var ret = validateView();ShowDiv1(); return ret;"
Why not a/b/(c|d|e)
? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work.
abc.xml
is the doc described by OP.
(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
#<XdmNode <d>D1</d>>
#<XdmNode <e>E1</e>>
#<XdmNode <c>C2</c>>
#<XdmNode <d>D2</d>>
#<XdmNode <e>E1</e>>)
Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...
e.g.
in Column A we have field called company....
Column A Column B Column C
Company_Name Value
Monster 25000
Naukri 30000
WNS 80000
American Express 40000
Bank of America 50000
Alcatel Lucent 35000
Google 75000
Microsoft 60000
Monster 35000
Bank of America 15000
Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem
Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)
..........Result will be Monster_1
for first line item and for row no 10 & 11.....Monster_2, Bank of America_2
respectively....Here you go now you have the unique value so now you can pick any data easily now..
Cheers!!! Anil Dhawan
Tensorflow now works with python 3.6.4, don't use python builds that came after 3.6.4 and most importantly tensorflow doesn't work on Python 3.7.2. You can download 3.6.4 for windows from here python 3.6.4.
Then just simply run pip install tensorflow-gpu
NETWORK SERVICE and LocalSystem will authenticate themselves always as the correpsonding account locally (builtin\network service and builtin\system) but both will authenticate as the machine account remotely.
If you see a failure like Login failed for user 'DOMAIN\MACHINENAME$'
it means that a process running as NETWORK SERVICE or as LocalSystem has accessed a remote resource, has authenticated itself as the machine account and was denied authorization.
Typical example would be an ASP application running in an app pool set to use NETWORK SERVICE credential and connecting to a remote SQL Server: the app pool will authenticate as the machine running the app pool, and is this machine account that needs to be granted access.
When access is denied to a machine account, then access must be granted to the machine account. If the server refuses to login 'DOMAIN\MACHINE$', then you must grant login rights to 'DOMAIN\MACHINE$' not to NETWORK SERVICE. Granting access to NETWORK SERVICE would allow a local process running as NETWORK SERVICE to connect, not a remote one, since the remote one will authenticate as, you guessed, DOMAIN\MACHINE$.
If you expect the asp application to connect to the remote SQL Server as a SQL login and you get exceptions about DOMAIN\MACHINE$ it means you use Integrated Security in the connection string. If this is unexpected, it means you screwed up the connection strings you use.
L = ['L','O','L']
makeitastring = ''.join(map(str, L))
After jQuery 1.6, using promise seems like a better option.
var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
fadeoOutDone.then(function(){
$div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
$div1.fadeIn();
});
});
For me, I always choose non-thread safe version because I always use nginx, or run PHP from the command line.
The non-thread safe version should be used if you install PHP as a CGI binary, command line interface or other environment where only a single thread is used.
A thread-safe version should be used if you install PHP as an Apache module in a worker MPM (multi-processing model) or other environment where multiple PHP threads run concurrently.
"title" is widely implemented in browsers. Try:
<a href="#" title="hello">asf</a>
select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0)) as total_hours
from hours_t
group by type, craft
order by type, craft
You say you don't want to use the system("pause")
hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit()
. If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit()
call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
static class Constants
{
public const int MIN_LENGTH = 5;
public const int MIN_WIDTH = 5;
public const int MIN_HEIGHT = 6;
}
// elsewhere
public CBox()
{
length = Constants.MIN_LENGTH;
width = Constants.MIN_WIDTH;
height = Constants.MIN_HEIGHT;
}
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
Check the "tsconfig.json"
file for compilation options "include"
and "exclude"
. If it does not exist, just add them by informing your root directory.
// tsconfig.json
{
"compilerOptions": {
...
"include": [
"src",
],
"exclude": [
"node_modules",
]
}
I solved my silly problem just by removing the extension statement "*.spec.ts"
from the "exclude"
, because when including the "import"
in these files, there were always problems.
I think you do not need to use shape if I understood you.
If you are looking as shown in following image then use following layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#1bd4f6"
android:paddingBottom="4dp" >
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="#ababb2"
android:padding="5dp"
android:text="Hello Android" />
</RelativeLayout>
</RelativeLayout>
EDIT
play with these properties you will get result
android:top="dimension"
android:right="dimension"
android:bottom="dimension"
android:left="dimension"
try like this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item android:top="20px"
android:left="0px">
<shape android:shape="line" >
<padding android:bottom="1dp" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
This code achieves what you want --- also its weird and certainly buggy:
I observed that it works when:
a) you specify the index_col
rel. to the number of columns you really use -- so its three columns in this example, not four (you drop dummy
and start counting from then onwards)
b) same for parse_dates
c) not so for usecols
;) for obvious reasons
d) here I adapted the names
to mirror this behaviour
import pandas as pd
from StringIO import StringIO
csv = """dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5
"""
df = pd.read_csv(StringIO(csv),
index_col=[0,1],
usecols=[1,2,3],
parse_dates=[0],
header=0,
names=["date", "loc", "", "x"])
print df
which prints
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
You can set custom font in two ways : design time
and run-time
.
First you need to download required font
(.ttf file format). Then, double click on the file to install it.
This will show a pop-up. Click on 'install font
' button.
'Fonts'
window.Add to targets
' is checked.Copy Bundle Resources'
present in Build Phases
of Targets
of your project.Info.plist
of your project.
Create a new key with 'Font Provided by application
' with type as Array.
Add a the font as an element with type String in Array.A. Design mode :
Font
attribute present in Attribute inspector
of Utilities
.B. Run-time mode :
self.lblWelcome.font = UIFont(name: "BananaYeti-Extrabold Trial", size: 16)
It seems that run-time mode doesn't work for dynamically formed string like
self.lblWelcome.text = "Welcome, " + fullname + "!"
Note that in above case only design-time approach worked correctly for me.
What you want is the outer HTML, not the inner HTML :
$('<some element/>')[0].outerHTML;
Using ES6 modules can be useful for 'tree shaking'; i.e. enabling Webpack 2, Rollup (or other bundlers) to identify code paths that are not used/imported, and therefore don't make it into the resulting bundle. This can significantly reduce its file size by eliminating code you'll never need, but with CommonJS is bundled by default because Webpack et al have no way of knowing whether it's needed.
This is done using static analysis of the code path.
For example, using:
import { somePart } 'of/a/package';
... gives the bundler a hint that package.anotherPart
isn't required (if it's not imported, it can't be used- right?), so it won't bother bundling it.
To enable this for Webpack 2, you need to ensure that your transpiler isn't spitting out CommonJS modules. If you're using the es2015
plug-in with babel, you can disable it in your .babelrc
like so:
{
"presets": [
["es2015", { modules: false }],
]
}
Rollup and others may work differently - view the docs if you're interested.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Alternate Link (2019) : https://reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas
It uses a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details.)
Suppose your application named MyApp contains the following components.
In order to filter the logging output from your application MyApp using logcat you would type the following.
adb logcat MyActivity1:v MyActivity2:v MyActivity3:v MyService:v *:s
However this requires you to know the TAG names for all of the components in your application rather than filtering using the application name MyApp. See logcat for specifics.
One solution to allow filtering at the application level would be to add a prefix to each of your unique TAG's.
Now a wild card filter on the logcat output can be performed using the TAG prefix.
adb logcat | grep MyApp
The result will be the output from the entire application.
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
Here's a straightforward and generic example.
The filter:
sampleApp.filter('unique', function() {
// Take in the collection and which field
// should be unique
// We assume an array of objects here
// NOTE: We are skipping any object which
// contains a duplicated value for that
// particular key. Make sure this is what
// you want!
return function (arr, targetField) {
var values = [],
i,
unique,
l = arr.length,
results = [],
obj;
// Iterate over all objects in the array
// and collect all unique values
for( i = 0; i < arr.length; i++ ) {
obj = arr[i];
// check for uniqueness
unique = true;
for( v = 0; v < values.length; v++ ){
if( obj[targetField] == values[v] ){
unique = false;
}
}
// If this is indeed unique, add its
// value to our values and push
// it onto the returned array
if( unique ){
values.push( obj[targetField] );
results.push( obj );
}
}
return results;
};
})
The markup:
<div ng-repeat = "item in items | unique:'name'">
{{ item.name }}
</div>
<script src="your/filters.js"></script>
To return to your Activity
, you will need to listen to TelephonyStates
. On that listener
you can send an Intent
to re-open your Activity
once the phone is idle.
At least thats how I will do it.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
Something like this will do it:
Rows("12:12").Select
Selection.Delete
So in your code it would look like something like this:
Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete
I faced the same problem! Just delete bin folder and restart your VS
.
That's all.
tested in VS 2013
.
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
You can use
git log -p filename
to let git generate the patches for each log entry.
See
git help log
for more options - it can actually do a lot of nice things :) To get just the diff for a specific commit you can
git show HEAD
or any other revision by identifier. Or use
gitk
to browse the changes visually.
Sounds like you executed another statement in the same connection before traversing the result set from the first statement. If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
You can use curl
this way:
curl -OL https://raw.githubusercontent.com/<username>/<repo-name>/<branch-name>/path/to/file
O
means that curl downloads the content
L
means that curl follows the redirection
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist
"edition".intern # :edition
Actually, in C++14 it can be done with a very few lines of code.
This is a very similar in idea to @Paul's solution. Due to things missing from C++11, that solution is a bit unnecessarily bloated (plus defining in std smells). Thanks to C++14 we can make it a lot more readable.
The key observation is that range-based for-loops work by relying on begin()
and end()
in order to acquire the range's iterators. Thanks to ADL, one doesn't even need to define their custom begin()
and end()
in the std:: namespace.
Here is a very simple-sample solution:
// -------------------------------------------------------------------
// --- Reversed iterable
template <typename T>
struct reversion_wrapper { T& iterable; };
template <typename T>
auto begin (reversion_wrapper<T> w) { return std::rbegin(w.iterable); }
template <typename T>
auto end (reversion_wrapper<T> w) { return std::rend(w.iterable); }
template <typename T>
reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; }
This works like a charm, for instance:
template <typename T>
void print_iterable (std::ostream& out, const T& iterable)
{
for (auto&& element: iterable)
out << element << ',';
out << '\n';
}
int main (int, char**)
{
using namespace std;
// on prvalues
print_iterable(cout, reverse(initializer_list<int> { 1, 2, 3, 4, }));
// on const lvalue references
const list<int> ints_list { 1, 2, 3, 4, };
for (auto&& el: reverse(ints_list))
cout << el << ',';
cout << '\n';
// on mutable lvalue references
vector<int> ints_vec { 0, 0, 0, 0, };
size_t i = 0;
for (int& el: reverse(ints_vec))
el += i++;
print_iterable(cout, ints_vec);
print_iterable(cout, reverse(ints_vec));
return 0;
}
prints as expected
4,3,2,1,
4,3,2,1,
3,2,1,0,
0,1,2,3,
NOTE std::rbegin()
, std::rend()
, and std::make_reverse_iterator()
are not yet implemented in GCC-4.9. I write these examples according to the standard, but they would not compile in stable g++. Nevertheless, adding temporary stubs for these three functions is very easy. Here is a sample implementation, definitely not complete but works well enough for most cases:
// --------------------------------------------------
template <typename I>
reverse_iterator<I> make_reverse_iterator (I i)
{
return std::reverse_iterator<I> { i };
}
// --------------------------------------------------
template <typename T>
auto rbegin (T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
// const container variants
template <typename T>
auto rbegin (const T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (const T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
Remember to use the server's local name, not the domain name, when resolving the name
IIS AppPool\DefaultAppPool
(just a reminder because this tripped me up for a bit):
They're basically the same, except clone will setup additional remote tracking branches, not just master. Check out the man page:
Clones a repository into a newly created directory, creates remote-tracking branches for each branch in the cloned repository (visible using git branch -r), and creates and checks out an initial branch that is forked from the cloned repository's currently active branch.
.Net provides the TimeSpan class to do the math for you.
var time1 = new Date(YYYY, MM, DD, 0, 0, 0, 0)
var time2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0)
Dim ts As TimeSpan = time2.Subtract(time1)
ts.TotalSeconds
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
Delegates Overview
Delegates have the following properties:
- Delegates are similar to C++ function pointers, but are type safe.
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
- Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
- C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.
In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.
Trying to get property of non-object
For Example:
if (!empty($this->xml_data->thing1->thing2))
{
foreach ($this->xml_data->thing1->thing2 as $thing)
{
}
}
nickf's solution modified:
function addhttp($url) {
if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
$url = "http://" . $url;
}
return $url;
}
This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string
, like so:
require 'json'
JSON.parse(json_string)
If you’re using an older Ruby, you may need to install the json gem.
There are also other implementations of JSON for Ruby that may fit some use-cases better:
You can await setTimeout
with Node.js 15 or above:
const timersPromises = require('timers/promises');
(async () => {
const result = await timersPromises.setTimeout(2000, 'resolved')
// Executed after 2 seconds
console.log(result); // "resolved"
})()
Timers Promises API: https://nodejs.org/api/timers.html#timers_timers_promises_api (library already built in Node)
Note: Stability: 1 - Use of the feature is not recommended in production environments.
One more way. Select the target table in the left panel in phpMyAdmin, click on Export tab, unselect Data block and click on Go button.
Two possibilities :
via script task and builtin javascript engine (if using jdk >= 1.6)
<project>
<property name="propA" value="This is a value"/>
<script language="javascript">
project.setProperty('propB', project.getProperty('propA').
replace(" ", "_"));
</script>
<echo>$${propB} => ${propB}</echo>
</project>
or using Ant addon Flaka
<project xmlns:fl="antlib:it.haefelinger.flaka">
<property name="propA" value="This is a value"/>
<fl:let> propB := replace('${propA}', '_', ' ')</fl:let>
<echo>$${propB} => ${propB}</echo>
</project>
to overwrite exisiting property propA simply replace propB with propA
I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:
f, ax = plt.subplots(figsize=(16, 12))
at the meantime until you get a matched size colobar. This worked for me.
That's an odd approach with isUserAnswer
. Are you really going to send all three choices back to the server where it will loop through each one checking for isUserAnswer == true
? If so, you can try this:
HTML:
<input type="radio" name="response" value="true" ng-click="setChoiceForQuestion(question1, choice)"/>
JavaScript:
$scope.setChoiceForQuestion = function (q, c) {
angular.forEach(q.choices, function (c) {
c.isUserAnswer = false;
});
c.isUserAnswer = true;
};
Alternatively, I'd recommend changing your tack:
<input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>
That way you can just send {{question1.userChoiceId}}
back to the server.
If you want to insert a list into a list, you can do this:
>>> a = [1,2,3,4,5]
>>> for x in reversed(['a','b','c']): a.insert(2,x)
>>> a
[1, 2, 'a', 'b', 'c', 3, 4, 5]
Unfortunately you can't use that tuple assignment syntax in (ECMA|Java)Script.
EDIT: Someone linked to Mozilla/JS 1.7 - this wouldn't work cross-browser but if that is not required then there's your answer.
You don't have to call the external basename
command. Instead, you could use the following commands:
$ s=/the/path/foo.txt
$ echo "${s##*/}"
foo.txt
$ s=${s##*/}
$ echo "${s%.txt}"
foo
$ echo "${s%.*}"
foo
Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash
, dash
, ksh
, etc.).
Source: Shell Command Language 2.6.2 Parameter Expansion
More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html
You can use triple quotes (single ' or double "):
a = """
text
text
text
"""
print(a)
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
If you want to count the number of records in your table, simply run:
SELECT COUNT(*) FROM your_table;
The imports have changed for core-js version 3.0.1 - for example
import 'core-js/es6/array';
and
import 'core-js/es7/array';
can now be provided simply by the following
import 'core-js/es/array';
if you would prefer not to bring in the whole of core-js
Step1: copy all the rpm pkg in given locations
Step2: if createrepo is not already installed, as it will not be by default, install it.
[root@pavangildamysql1 8.0.11_rhel7]# yum install createrepo
Step3: create repository metedata and give below permission
[root@pavangildamysql1 8.0.11_rhel7]# chown -R root.root /scratch/PVN/8.0.11_rhel7
[root@pavangildamysql1 8.0.11_rhel7]# createrepo /scratch/PVN/8.0.11_rhel7
Spawning worker 0 with 3 pkgs
Spawning worker 1 with 3 pkgs
Spawning worker 2 with 3 pkgs
Spawning worker 3 with 2 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
[root@pavangildamysql1 8.0.11_rhel7]# chmod -R o-w+r /scratch/PVN/8.0.11_rhel7
Step4: Create repository file with following contents at /etc/yum.repos.d/mysql.repo
[local]
name=My Awesome Repo
baseurl=file:///scratch/PVN/8.0.11_rhel7
enabled=1
gpgcheck=0
Step5 Run this command to install
[root@pavangildamysql1 local]# yum --nogpgcheck localinstall mysql-commercial-server-8.0.11-1.1.el7.x86_64.rpm
You can give like this....
<a href="@(IsProduction.IsProductionUrl)Index/LogOut">
Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.
One way to do this that correctly uses group by
:
select l.*
from table l
inner join (
select
m_id, max(timestamp) as latest
from table
group by m_id
) r
on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc
How this works:
m_id
in the subquerytable
that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)Try this:
System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
credentialCache.Add(
new System.Uri("http://www.yoururl.com/"),
"Basic",
new System.Net.NetworkCredential("username", "password")
);
...
...
httpWebRequest.Credentials = credentialCache;
Have your tried using the 'return' keyword?
def rps():
return True
setInterval is the function you want. That repeats every x miliseconds.
window.setInterval(function() {
alert('test');
}, 10000);
Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely
and up:
# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely
# Options
$option1 = New-ScheduledJobOption –StartIfIdle
$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"
Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
you can use java http/https url connection to get the response code from the website and other information as well here is a sample code.
try {
url = new URL("https://www.google.com"); // create url object for the given string
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(https_url.startsWith("https")){
connection = (HttpsURLConnection) url.openConnection();
}
((HttpURLConnection) connection).setRequestMethod("HEAD");
connection.setConnectTimeout(50000); //set the timeout
connection.connect(); //connect
String responseMessage = connection.getResponseMessage(); //here you get the response message
responseCode = connection.getResponseCode(); //this is http response code
System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}
Try like this
ImageButton imagetrans=(ImageButton)findViewById(R.id.ImagevieID);
imagetrans.setBackgroundColor(Color.TRANSPARENT);
OR
include this in your .xml file in res/layout
android:background="@android:color/transparent
According to MDN: Determining the dimensions of elements
offsetWidth
and offsetHeight
return the "total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border"
clientWidth
and clientHeight
return "how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars"
scrollWidth
and scrollHeight
return the "actual size of the content, regardless of how much of it is currently visible"
So it depends on whether the measured content is expected to be out of the current viewable area.
Simply in SASS:
.some_class{
// styles...
&.active {
pointer-events:none;
}
}
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
This should work for you.
In .html:
<div class="my_class" (click)="clickEvent()"
[ngClass]="status ? 'success' : 'danger'">
Some content
</div>
In .ts:
status: boolean = false;
clickEvent(){
this.status = !this.status;
}
Most (if not all) of these answers assume you are happy to install packages globally. This answer is for you if you:
(Note: this answer adds a python2 kernel to a python3-jupyter install, but it's conceptually easy to swap things around.)
Prerequisites
Create a python3 venv and install jupyter
python3 -m venv .venv
. .venv/bin/activate
pip install jupyterlab
. This will create locally all the essential infrastructure for running notebooks. $PWD/.venv/share/jupyter/kernels/python3/
. If you want to install and run jupyter elsewhere, and only use this venv for organizing all your kernels, then you only need: pip install ipykernel
jupyter lab
(and go to your browser to the url displayed in the console). So far, you'll only see one kernel option called 'Python 3'. (This name is determined by the display_name
entry in your kernel.json
file.)Add a python2 kernel
ctrl-c
deactivate
virtualenv -p python2 .venv2
. .venv2/bin/activate
pip install ipykernel
. This will also generate default kernel specs for this python2 venv in .venv2/share/jupyter/kernels/python2
python -m ipykernel install --prefix=$PWD/.venv
. This basically just copies the dir $PWD/.venv2/share/jupyter/kernels/python2
to $PWD/.venv/share/jupyter/kernels/
deactivate; . .venv/bin/activate; jupyter lab
. If all went well, you'll see a Python 2
option in your list of kernels. You can test that they're running real python2/python3 interpreters by their handling of a simple print 'Hellow world'
vs print('Hellow world')
command.TL;DR
R -e "install.packages('IRkernel',repos='https://cran.mtu.edu/')"
. (This will install to your standard R-packages location; for home-brewed-installed R on a Mac, this will look like /usr/local/Cellar/r/3.5.2_2/lib/R/library/IRkernel
.)R -e "IRkernel::installspec(prefix=paste(getwd(),'/.venv',sep=''))"
. If you now look in $PWD/.venv/share/jupyter/kernels/
you'll find an ir
directory with kernel.json
file that looks something like this:{
"argv": ["/usr/local/Cellar/r/3.5.2_2/lib/R/bin/R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
"display_name": "R",
"language": "R"
}
In summary, a kernel just 'is' an invocation of a language-specific executable from a kernel.json
file that jupyter looks for in the .../share/jupyter/kernels
dir and lists in its interface; in this case, R is being called to run the function IRkernel::main()
, which will send messages back and forth to the Jupiter server. Likewise, the python2 kernel just 'is' an invocation of the python2 interpreter with module ipykernel_launcher
as seen in .venv/share/jupyter/kernels/python2/kernel.json
, etc.
Here is a script if you want to run all of these instructions in one fell swoop.
Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line
error_log /var/log/nginx/error.log debug;
And then restart nginx:
sudo service nginx restart
That way you can detail what nginx is doing and why it is returning the status code 400.
From the JVM™ Tool Interface documentation…
Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a
JAVA_TOOL_OPTIONS
variable is provided so that agents may be launched in these cases.
By setting the (Windows) environment variable JAVA_TOOL_OPTIONS
to -Dfile.encoding=UTF8
, the (Java) System
property will be set automatically every time a JVM is started. You will know that the parameter has been picked up because the following message will be posted to System.err
:
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.
div {_x000D_
-webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
-moz-box-shadow: 0 4px 6px -6px #222;_x000D_
box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
covered in depth here
This will do:
▢
It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)
Or
◻
as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)
Two with shadow:
❏
❑
as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).
You can also use
☐
which is ?
(known as a "BALLOT BOX").
A sample is at http://jsfiddle.net/S2QCt/267/
(a note: on the Mac, ▢
is quite nice, because it is bigger and somewhat more elegant than ☐
On Windows, ☐
looks more standard, while ▢
is somewhat small.)
Shift + Insert usually works throughout X11.
Since Java is a statically typed language, I would expect that a abs-method which takes an int returns an int, if it expects a float returns a float, for a Double, return a Double. Maybe it could return always the boxed or unboxed type for doubles and Doubles and so on.
So you need one method per type, but now you have a new problem: For byte, short, int, long the range for negative values is 1 bigger than for positive values.
So what should be returned for the method
byte abs (byte in) {
// @todo
}
If the user calls abs on -128? You could always return the next bigger type so that the range is guaranteed to fit to all possible input values. This will lead to problems for long, where no normal bigger type exists, and make the user always cast the value down after testing - maybe a hassle.
The second option is to throw an arithmetic exception. This will prevent casting and checking the return type for situations where the input is known to be limited, such that X.MIN_VALUE can't happen. Think of MONTH, represented as int.
byte abs (byte in) throws ArithmeticException {
if (in == Byte.MIN_VALUE) throw new ArithmeticException ("abs called on Byte.MIN_VALUE");
return (in < 0) ? (byte) -in : in;
}
The "let's ignore the rare cases of MIN_VALUE" habit is not an option. First make the code work - then make it fast. If the user needs a faster, but buggy solution, he should write it himself. The simplest solution that might work means: simple, but not too simple.
Since the code doesn't rely on state, the method can and should be made static. This allows for a quick test:
public static void main (String args []) {
System.out.println (abs(new Byte ( "7")));
System.out.println (abs(new Byte ("-7")));
System.out.println (abs((byte) 7));
System.out.println (abs((byte) -7));
System.out.println (abs(new Byte ( "127")));
try
{
System.out.println (abs(new Byte ("-128")));
}
catch (ArithmeticException ae)
{
System.out.println ("Integer: " + Math.abs (new Integer ("-128")));
}
System.out.println (abs((byte) 127));
System.out.println (abs((byte) -128));
}
I catch the first exception and let it run into the second, just for demonstration.
There is a bad habit in programming, which is that programmers care much more for fast than for correct code. What a pity!
If you're curious why there is one more negative than positive value, I have a diagram for you.
To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
? productID =26%20via%20@LFS
Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
Run
gradlew -q app:dependencies
It will remove what is wrong.
You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject
You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.
I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6
but essentially you add following dependencies -
"devDependencies": {
"@angular-builders/custom-webpack": "^7.0.0",
"@angular-builders/dev-server": "^7.0.0",
"@angular-devkit/build-angular": "~0.11.0",
In angular.json make following changes -
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {"path": "./custom-webpack.config.js"},
Notice change in builder and new option customWebpackConfig. Also change
"serve": {
"builder": "@angular-builders/dev-server:generic",
Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.
However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.
Try:
System.Environment.GetEnvironmentVariable("USERPROFILE");
Edit:
If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder
enumeration:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
Open with append:
pFile2 = fopen("myfile2.txt", "a");
then just write to pFile2
, no need to fseek()
.
I had the same issue on a Windows 10 PC. I copied the project from my old computer to the new one, both 64 bits, and I installed the Oracle Client 64 bit on the new machine. I got the same error message, but after trying many solutions to no effect, what actually worked for me was this: In your Visual Studio (mine is 2017) go to Tools > Options > Projects and Solutions > Web Projects
On that page, check the option that says: Use the 64 bit version of IIS Express for Websites and Projects
Does the server actually get the requests, and are you handling the host name (alias) properly?
after adding to my .hosts file
Check your webserver log, to see how the request came in...
curl has options to dump the request sent, and response received, it is called trace, which will will be saved to a file.
--trace
If you are missing host or header information - you can force those headers with the config option.
I would get the curl request working on the command line, and then try to implement in PHP.
the config option is
-K/--config
the options that are relevant in curl are here
--trace Enables a full trace dump of all incoming and outgoing data, including descriptive information, to the given output file. Use "-" as filename to have the output sent to stdout.
This option overrides previous uses of -v/--verbose or --trace-ascii.
If this option is used several times, the last one will be used.
-K/--config Specify which config file to read curl arguments from. The config file is a text file in which command line arguments can be written which then will be used as if they were written on the actual command line. Options and their parameters must be specified on the same config file line, separated by whitespace, colon, the equals sign or any combination thereof (however, the preferred separa- tor is the equals sign). If the parameter is to contain whitespace, the parameter must be enclosed within quotes. Within double quotes, the following escape sequences are available: \, \", \t, \n, \r and \v. A backslash preceding any other letter is ignored. If the first column of a config line is a '#' character, the rest of the line will be treated as a comment. Only write one option per physical line in the config file.
Specify the filename to -K/--config as '-' to make curl read the file from stdin.
Note that to be able to specify a URL in the config file, you need to specify it using the --url option, and not by simply writing the URL on its own line. So, it could look similar to this:
url = "http://curl.haxx.se/docs/"
Long option names can optionally be given in the config file without the initial double dashes.
When curl is invoked, it always (unless -q is used) checks for a default config file and uses it if found. The default config file is checked for in the following places in this order:
1) curl tries to find the "home dir": It first checks for the CURL_HOME and then the HOME environment variables. Failing that, it uses getpwuid() on UNIX-like systems (which returns the home dir
given the current user in your system). On Windows, it then checks for the APPDATA variable, or as a last resort the '%USERPROFILE%\Application Data'.
2) On windows, if there is no _curlrc file in the home dir, it checks for one in the same dir the curl executable is placed. On UNIX-like systems, it will simply try to load .curlrc from the deter-
mined home dir.
# --- Example file ---
# this is a comment
url = "curl.haxx.se"
output = "curlhere.html"
user-agent = "superagent/1.0"
# and fetch another URL too
url = "curl.haxx.se/docs/manpage.html"
-O
referer = "http://nowhereatall.com/"
# --- End of example file ---
This option can be used multiple times to load multiple config files.
The init func runs first and then main. It's used for setting something first before your program runs, for example:
Accessing a template, Running the program using all cores, Checking the Goos and arch etc...
Recently, I too have the same problem... In Delphi It's very similar to Objective-C.
procedure TForm1.FormPaint(Sender: TObject);
var ARect: TRect;
AWidth, AHeight: Integer;
ABasePoint: TPoint;
AAngle: Extended;
begin
FCenter := Point(Width div 2, Height div 2);
AWidth := Width div 4;
AHeight := Height div 4;
ABasePoint := Point(FCenter.X+AWidth, FCenter.Y);
ARect := Rect(Point(FCenter.X - AWidth, FCenter.Y - AHeight),
Point(FCenter.X + AWidth, FCenter.Y + AHeight));
AAngle := ArcTan2(ClickPoint.Y-Center.Y, ClickPoint.X-Center.X) * 180 / pi;
AngleLabel.Caption := Format('Angle is %5.2f', [AAngle]);
Canvas.Ellipse(ARect);
Canvas.MoveTo(FCenter.X, FCenter.Y);
Canvas.LineTo(FClickPoint.X, FClickPoint.Y);
Canvas.MoveTo(FCenter.X, FCenter.Y);
Canvas.LineTo(ABasePoint.X, ABasePoint.Y);
end;
Flexible Box Layout Module - 8.1. Aligning with auto margins
Auto margins on flex items have an effect very similar to auto margins in block flow:
During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
Therefore you could use margin-top: auto
to distribute the space between the other elements and the last element.
This will position the last element at the bottom.
p:last-of-type {
margin-top: auto;
}
.container {
display: flex;
flex-direction: column;
border: 1px solid #000;
min-height: 200px;
width: 100px;
}
p {
height: 30px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-top: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
</div>
_x000D_
Likewise, you can also use margin-left: auto
or margin-right: auto
for the same alignment horizontally.
p:last-of-type {
margin-left: auto;
}
.container {
display: flex;
width: 100%;
border: 1px solid #000;
}
p {
height: 50px;
width: 50px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-left: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
_x000D_
I had this error 2 times. Each time it was solved by changing the ajax type. Either GET to POST or POST to GET.
$.ajax({
type:'GET', // or 'POST'
url: "file.cfm?action=get_table&varb=" + varb
});
Since Steve Tjoa's answer always pops up first and mostly lonely when I search for multiple y-axes at Google, I decided to add a slightly modified version of his answer. This is the approach from this matplotlib example.
Reasons:
mpl_toolkits.axisartist
, mpl_toolkits.axes_grid1
).import matplotlib.pyplot as plt
# Create figure and subplot manually
# fig = plt.figure()
# host = fig.add_subplot(111)
# More versatile wrapper
fig, host = plt.subplots(figsize=(8,5)) # (width, height) in inches
# (see https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html)
par1 = host.twinx()
par2 = host.twinx()
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
color1 = plt.cm.viridis(0)
color2 = plt.cm.viridis(0.5)
color3 = plt.cm.viridis(.9)
p1, = host.plot([0, 1, 2], [0, 1, 2], color=color1, label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], color=color2, label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], color=color3, label="Velocity")
lns = [p1, p2, p3]
host.legend(handles=lns, loc='best')
# right, left, top, bottom
par2.spines['right'].set_position(('outward', 60))
# no x-ticks
par2.xaxis.set_ticks([])
# Sometimes handy, same for xaxis
#par2.yaxis.set_ticks_position('right')
# Move "Velocity"-axis to the left
# par2.spines['left'].set_position(('outward', 60))
# par2.spines['left'].set_visible(True)
# par2.yaxis.set_label_position('left')
# par2.yaxis.set_ticks_position('left')
host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
# Adjust spacings w.r.t. figsize
fig.tight_layout()
# Alternatively: bbox_inches='tight' within the plt.savefig function
# (overwrites figsize)
# Best for professional typesetting, e.g. LaTeX
plt.savefig("pyplot_multiple_y-axis.pdf")
# For raster graphics use the dpi argument. E.g. '[...].png", dpi=200)'
Not absolutely what you are asking for, but you may be interested by my plugin vim-notebook which allows the user to keep a background process alive and to make it evaluate part of the current document (and to write the output in the document). It is intended to be used on notebook-style documents containing pieces of code to be evaluated.