I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
You can use python code directly in batch file, https://gist.github.com/jadient/9849314.
@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")
See explanation, Python command line -x option.
Make it simple and use R basic functions:
# To get the LEFT part:
> substr(a, 1, 4)
[1] "left"
>
# To get the MIDDLE part:
> substr(a, 3, 7)
[1] "ftrig"
>
# To get the RIGHT part:
> substr(a, 5, 10)
[1] "right"
The substr()
function tells you where start and stop substr(x, start, stop)
.SILENT:
Type " .SILENT: " in the beginning of your script without colons.
It says timer() is not available on android? You might find this article useful.
http://developer.android.com/resources/articles/timed-ui-updates.html
I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:
schedule(TimerTask task, Date when) // Schedule a task for single execution.
Or you cancel it after the first execution:
cancel() // Cancels the Timer and all scheduled tasks.
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
curl
without any options will perform a GET request. It will simply return the data from the URI specified. Not retrieve the file itself to your local machine.
When you do,
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
You will receive binary data:
|?>?$! <R?HP@T*?Pm?Z??jU???ZP+UAUQ@?
??{X\? K???>0c?yF[i?}4?!?V¸?H_?)nO#?;I??vg^_ ??-Hm$$N0.
???%Y[?L?U3?_^9??P?T?0'u8?l?4 ...
In order to save this, you can use:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png > image.png
to store that raw image data inside of a file.
An easier way though, is just to use wget
.
$ wget https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
$ ls
.
..
apple-touch-icon-144x144-precomposed.png
Create your partial view something like:
@model YourModelType
<div>
<!-- HTML to render your object -->
</div>
Then in your view use:
@Html.Partial("YourPartialViewName", Model)
If you do not want a strongly typed partial view remove the @model YourModelType
from the top of the partial view and it will default to a dynamic
type.
Update
The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/
in the path below.
@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
yes, by using css styles white-space: pre-wrap; in the .dropdown class of the bootstrap by overriding it. Earlier it is white-space: nowrap; so it makes the dropdown wrapped into one line. pre-wrap makes it as according to the width.
Here is a sample implementation:
import java.util.*;
public class MyBSTree<K,V> implements MyTree<K,V>{
private BSTNode<K,V> _root;
private int _size;
private Comparator<K> _comparator;
private int mod = 0;
public MyBSTree(Comparator<K> comparator){
_comparator = comparator;
}
public Node<K,V> root(){
return _root;
}
public int size(){
return _size;
}
public boolean containsKey(K key){
if(_root == null){
return false;
}
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return true;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
return false;
}
private int compare(K k1, K k2){
if(_comparator != null){
return _comparator.compare(k1,k2);
}
else {
Comparable<K> comparable = (Comparable<K>)k1;
return comparable.compareTo(k2);
}
}
public V get(K key){
Node<K,V> node = node(key);
return node != null ? node.value() : null;
}
private BSTNode<K,V> node(K key){
if(_root != null){
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return node;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
}
return null;
}
public void add(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
if(_root == null){
_root = new BSTNode<K, V>(key, value);
}
BSTNode<K,V> prev = null, curr = _root;
boolean lastChildLeft = false;
while(curr != null){
int comparison = compare(key, curr.key());
prev = curr;
if(comparison == 0){
curr._value = value;
return;
}else if(comparison < 0){
curr = curr._left;
lastChildLeft = true;
}
else{
curr = curr._right;
lastChildLeft = false;
}
}
mod++;
if(lastChildLeft){
prev._left = new BSTNode<K, V>(key, value);
}else {
prev._right = new BSTNode<K, V>(key, value);
}
}
private void removeNode(BSTNode<K,V> curr){
if(curr.left() == null && curr.right() == null){
if(curr == _root){
_root = null;
}else{
if(curr.isLeft()) curr._parent._left = null;
else curr._parent._right = null;
}
}
else if(curr._left == null && curr._right != null){
curr._key = curr._right._key;
curr._value = curr._right._value;
curr._left = curr._right._left;
curr._right = curr._right._right;
}
else if(curr._left != null && curr._right == null){
curr._key = curr._left._key;
curr._value = curr._left._value;
curr._right = curr._left._right;
curr._left = curr._left._left;
}
else { // both left & right exist
BSTNode<K,V> x = curr._left;
// find right-most node of left sub-tree
while (x._right != null){
x = x._right;
}
// move that to current
curr._key = x._key;
curr._value = x._value;
// delete duplicate data
removeNode(x);
}
}
public V remove(K key){
BSTNode<K,V> curr = _root;
V val = null;
while(curr != null){
int comparison = compare(key, curr.key());
if(comparison == 0){
val = curr._value;
removeNode(curr);
mod++;
break;
}else if(comparison < 0){
curr = curr._left;
}
else{
curr = curr._right;
}
}
return val;
}
public Iterator<MyTree.Node<K,V>> iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<Node<K,V>>{
int _startMod;
Stack<BSTNode<K,V>> _stack;
public MyIterator(){
_startMod = MyBSTree.this.mod;
_stack = new Stack<BSTNode<K, V>>();
BSTNode<K,V> node = MyBSTree.this._root;
while (node != null){
_stack.push(node);
node = node._left;
}
}
public void remove(){
throw new UnsupportedOperationException();
}
public boolean hasNext(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
return !_stack.empty();
}
public Node<K,V> next(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
if(!hasNext()){
throw new NoSuchElementException();
}
BSTNode<K,V> node = _stack.pop();
BSTNode<K,V> x = node._right;
while (x != null){
_stack.push(x);
x = x._left;
}
return node;
}
}
@Override
public String toString(){
if(_root == null) return "[]";
return _root.toString();
}
private static class BSTNode<K,V> implements Node<K,V>{
K _key;
V _value;
BSTNode<K,V> _left, _right, _parent;
public BSTNode(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
_key = key;
_value = value;
}
public K key(){
return _key;
}
public V value(){
return _value;
}
public Node<K,V> left(){
return _left;
}
public Node<K,V> right(){
return _right;
}
public Node<K,V> parent(){
return _parent;
}
boolean isLeft(){
if(_parent == null) return false;
return _parent._left == this;
}
boolean isRight(){
if(_parent == null) return false;
return _parent._right == this;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
try{
BSTNode<K,V> node = (BSTNode<K,V>)o;
return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
}catch (ClassCastException ex){
return false;
}
}
@Override
public int hashCode(){
int hashCode = _key.hashCode();
if(_value != null){
hashCode ^= _value.hashCode();
}
return hashCode;
}
@Override
public String toString(){
String leftStr = _left != null ? _left.toString() : "";
String rightStr = _right != null ? _right.toString() : "";
return "["+leftStr+" "+_key+" "+rightStr+"]";
}
}
}
Building on the existing answers here, you could define this in your REPL:
__dirname = path.resolve(path.dirname(''));
Or:
__dirname = path.resolve();
Or @Jthorpe's alternatives:
__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD
The command chkconfig
is no longer available in Ubuntu.The equivalent command to chkconfig
is update-rc.d
.This command nearly supports all the new versions of ubuntu.
The similar commands are
update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service> remove
There are many ways git log -1
is the easiest and most common, I think
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
I had the same issue and here is how I manage to pass through:
In your case you have addToCount()
which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"
in your function implementation you can receive the params like:
addToCount(paramContactID){
// the paramContactID contains the value you passed into the function when you called it
// you can do what you want to do with the paramContactID in here!
}
list[:10]
will give you the first 10 elements of this list using slicing.
However, note, it's best not to use list
as a variable identifier as it's already used by Python: list()
To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
I solved this on my WAMP setup by enabling the php_openssl
extension, since the URL I was loading from used https://
.
3Hub is discontinued. There's a better solution, you can use Transmit (Mac only), then you just connect to your bucket and choose Show Item Count
from the View
menu.
You can simply fetch a single commit of a remote repo with
git fetch <repo> <commit>
where,
<repo>
can be a remote repo name (e.g. origin
) or even a remote repo URL (e.g. https://git.foo.com/myrepo.git
)<commit>
can be the SHA1 commitfor example
git fetch https://git.foo.com/myrepo.git 0a071603d87e0b89738599c160583a19a6d95545
after you fetched the commit (and the missing ancestors) you can simply checkout it with
git checkout FETCH_HEAD
Note that this will bring you in the "detached head" state.
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
Try:
Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;
Jon Skeet is right as usually :)
Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:
YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");
mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))
There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".
There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.
Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).
This matter has been debated for a long time.
do like this :
child{
position:absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Without looping
I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):
for %%f in ("%filename%") do set filename=%%~nf
If you want to strip the extension from a full path, use %%dpnf
instead:
for %%f in ("%path%") do set path=%%~dpnf
Example:
(Use directly in the console)
@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf
OUTPUT:
file name
C:\Dir\file
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
Let me make it easy for all of you with an example.
For simplicity purpose, let's assume there are 32 elements in an array in the sorted order out of which we are searching for an element using binary search.
1 2 3 4 5 6 ... 32
Assume we are searching for 32. after the first iteration, we will be left with
17 18 19 20 .... 32
after the second iteration, we will be left with
25 26 27 28 .... 32
after the third iteration, we will be left with
29 30 31 32
after the fourth iteration, we will be left with
31 32
In the fifth iteration, we will find the value 32.
So, If we convert this into a mathematical equation, we will get
(32 X (1/25)) = 1
=> n X (2-k) = 1
=> (2k) = n
=> k log22 = log2n
=> k = log2n
Hence the proof.
No, its easy to do this. In Xcode, set the Active Configuration to Release. Change the device from Simulator to Device - whatever SDK. If you want to directly export to your iPhone, connect it to your computer. Press Build and Go. If your iPhone is not connected to your computer, a message will come up saying that your iPhone is not connected.
If this applies to you: (iPhone was not connected)
Go to your projects folder and then to the build folder inside. Go to the Release-iphoneos folder and take the app inside, drag and drop on iTunes icon. When you sync your iTouch device, it will copy it to your device. It will also show up in iTunes as a application for the iPhone.
Hope this helps!
P.S.: If it says something about a certificate not being valid, just click on the project in Xcode, the little project icon in the file stack to the left, and press Apple+I, or do Get Info from the menu bar. Click on Build at the top. Under Code Signing, change Code Signing Identity - Any iPhone OS Device to be Don't Sign.
Boost has the statechart library. http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html
I can't speak to the use of it, though. Not used it myself (yet)
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
For ENTER key, why not use (keyup.enter)
:
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="values=box.value">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
values = '';
}
From https://golang.org/doc/effective_go.html#composite_literals:
Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
The above answers may help you but you may also want to know how to use array of function pointers.
void fun1()
{
}
void fun2()
{
}
void fun3()
{
}
void (*func_ptr[3])() = {fun1, fun2, fun3};
main()
{
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;
}
You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.
You can also pass arguments like below if all the above functions are having the same number of arguments of same type.
(*func_ptr[option])(argu1);
Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1
can be called if option=0, fun2
can be called if option=1 and fun3
can be called if option=2.
len(self.table)
checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):
Python 2:
if len(self.table) > 0:
#Do code here
Python 3:
if(len(self.table) > 0):
#Do code here
It's also possible to use
if self.table:
#Execute if self.table is not empty
else:
#Execute if self.table is empty
to see if the list is not empty.
I think this one will also work:
SELECT * FROM ORDER BY id DESC LIMIT 0 , 1
The solution is to add height:100%;
to all the parent elements of your .wrapper-div
as well. So:
html{
height: 100%;
}
body{
margin:0;
padding:0;
overflow:hidden;
height:100%;
}
#container{
width:1000px;
margin:0 auto;
height:100%;
}
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
With Termsql you can do it in one line:
termsql -i mycsvfile.CSV -d ',' -c 'a,b' -t 'foo' -o mynewdatabase.db
You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:
Private Sub writeDebug(ByVal x As String)
Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim FILE_NAME As String = path & "\mydebug.txt"
MsgBox(FILE_NAME)
If System.IO.File.Exists(FILE_NAME) = False Then
System.IO.File.Create(FILE_NAME).Dispose()
End If
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine(x)
objWriter.Close()
End Sub
There are more standard folders you can access through the "SpecialFolder" object.
You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:
Am I using proper dependency injection? Do I possibly needs to move the private methods into a separate class and rather test that? Must these methods be private? ...can't they be default or protected rather?
In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.
Another way is to use the subplots
function and pass the width ratio with gridspec_kw
:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)
f.tight_layout()
f.savefig('grid_figure.pdf')
You get the error because order[1]
is undefined
.
That error message means that somewhere in your code, an attempt is being made to access a property with some name (here it's "push"), but instead of an object, the base for the reference is actually undefined
. Thus, to find the problem, you'd look for code that refers to that property name ("push"), and see what's to the left of it. In this case, the code is
if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }
which means that the code expects order[1]
to be an array. It is, however, not an array; it's undefined
, so you get the error. Why is it undefined
? Well, your code doesn't do anything to make it anything else, based on what's in your question.
Now, if you just want to place a[i]
in a particular property of the object, then there's no need to call .push()
at all:
var order = [], stack = [];
for(var i=0;i<a.length;i++){
if(parseInt(a[i].daysleft) == 0){ order[0] = a[i]; }
if(parseInt(a[i].daysleft) > 0){ order[1] = a[i]; }
if(parseInt(a[i].daysleft) < 0){ order[2] = a[i]; }
}
Create a class inherited from JavaScriptConverter. You must then implement three things:
Methods-
Property-
You can use the JavaScriptConverter class when you need more control over the serialization and deserialization process.
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyCustomConverter() });
DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);
Information from Microsoft about this (see Remarks on MSDN):
- System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
- System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
- System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
- System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
It is interesting to mention that System.Timers.Timer
was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0).
The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.
When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer
instead.
Looks like that Microsoft favors System.Threading.Timer
before System.Timers.Timer
.
EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.
I was surprised that no other answers on this page mentioned git stash push
.
This article helped me understand:
The command
git stash
is shorthand forgit stash push
. In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. There are also another alias for this commandgit stash save
which is deprecated in favour ofgit stash push
.By default git ignores untracked files when doing stash. If those files need to be added to stash you can use
-u
options which tells git to include untracked files. Ignored files can be added as well if-a
option is specified.-a
will include both untracked and ignored files.
I care about naming my stashes, and I want them to include untracked files, so the command I most commonly run is: git stash push -u -m "whatIWantToNameThisStash"
let array = [5,5,4,4,2,3,4]
let newArray = array.join(',').replace('5','').split(',')
This example works if you want to remove one current item.
echo date('D', strtotime($date));
echo date('l', strtotime($date));
Result
Tue
Tuesday
You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):
1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.
2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.
Right now, I'm working in the second option but with iPhone.
Try this:
$('div.btn-group ul.dropdown-menu li a').click(function (e) {
var $div = $(this).parent().parent().parent();
var $btn = $div.find('button');
$btn.html($(this).text() + ' <span class="caret"></span>');
$div.removeClass('open');
e.preventDefault();
return false;
});
Make a set out of the larger one:
_auxset = set(a)
Then,
c = [x for x in b if x in _auxset]
will do what you want (preserving b
's ordering, not a
's -- can't necessarily preserve both) and do it fast. (Using if x in a
as the condition in the list comprehension would also work, and avoid the need to build _auxset
, but unfortunately for lists of substantial length it would be a lot slower).
If you want the result to be sorted, rather than preserve either list's ordering, an even neater way might be:
c = sorted(set(a).intersection(b))
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
Problem with the above answer comes with files input with "./" like "./my-file.txt"
Workaround (of many):
myfile="./somefile.txt"
FOLDER="$(dirname $(readlink -f "${ARG}"))"
echo ${FOLDER}
One liner:
total_line_count = sum(1 for line in open("filename.txt"))
print(total_line_count)
Use ripgrep, aka rg: https://github.com/BurntSushi/ripgrep
rg --passthru...
Color is the default:
rg -t tf -e 'key.*tfstate' -e dynamodb_table
--passthru
Print both matching and non-matching lines.
Another way to achieve a similar effect is by modifying your pattern to
match the empty string.
For example, if you are searching using rg foo then using
rg "^|foo" instead will emit every line in every file searched, but only
occurrences of foo will be highlighted.
This flag enables the same behavior without needing to modify the pattern.
Sacrilege, granted, but grep has gotten complacent.
brew/apt/rpm/whatever install ripgrep
You'll never go back.
Official Python .msi installers are designed to replace:
A snapshot installer is designed to replace any snapshot with a lower micro version.
(See responsible code for 2.x, for 3.x)
Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:
bdist_wininst
packages (Windows .exe
s), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logicsetuptools
/pip
that reside in Lib\site-packages
can just be deleted afterwards%APPDATA%/Python/PythonXY/site-packages
and can likewise be deletedAnother approach:
union IP {
unsigned int ip;
struct {
unsigned char d;
unsigned char c;
unsigned char b;
unsigned char a;
} ip2;
};
...
char ips[20];
IP ip;
ip.ip = 0xAABBCCDD;
sprintf(ips, "%x.%x.%x.%x", ip.ip2.a, ip.ip2.b, ip.ip2.c, ip.ip2.d);
printf("%s\n", ips);
There are few named constructors in GridView
for different scenarios,
Constructors
GridView
GridView.builder
GridView.count
GridView.custom
GridView.extent
Below is a example of GridView
constructor:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
List<String> images = [
"https://uae.microless.com/cdn/no_image.jpg",
"https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
"https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
"https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
"https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
"https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
"https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
"https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
"https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView(
physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
children: images.map((url) {
return Card(child: Image.network(url));
}).toList(),
),
);
}
}
If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView
package. I have provided an answer with example here.
Below is an example for a GridView.count
:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
crossAxisCount: 4,
children: List.generate(40, (index) {
return Card(
child: Image.network("https://robohash.org/$index"),
); //robohash.org api provide you different images for any number you are giving
}),
),
);
}
}
Screenshot for above snippet:
Example for a SliverGridView
:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
primary: false,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(20.0),
sliver: SliverGrid.count(
crossAxisSpacing: 10.0,
crossAxisCount: 2,
children: List.generate(20, (index) {
return Card(child: Image.network("https://robohash.org/$index"));
}),
),
),
],
)
);
}
}
I was using
SELECT * from TABLE1 WHERE Col1 NOT IN (SELECT Col1 FROM TABLE2)
and found that it was giving wrong results (By wrong I mean no results). As there was a NULL in TABLE2.Col1.
While changing the query to
SELECT * from TABLE1 T1 WHERE NOT EXISTS (SELECT Col1 FROM TABLE2 T2 WHERE T1.Col1 = T2.Col2)
gave me the correct results.
Since then I have started using NOT EXISTS every where.
This is java answer.
df.select("id").collectAsList();
Unfortunately it seems to be a issue with MySql usage of "NOT IN" clause, the screen-shoot below shows the sub-query option returning wrong results:
mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------+
| innodb_version | 1.1.8 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.21 |
| version_comment | MySQL Community Server (GPL) |
| version_compile_machine | x86_64 |
| version_compile_os | Linux |
+-------------------------+------------------------------+
7 rows in set (0.07 sec)
mysql> select count(*) from TABLE_A where TABLE_A.Pkey not in (select distinct TABLE_B.Fkey from TABLE_B );
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.07 sec)
mysql> select count(*) from TABLE_A left join TABLE_B on TABLE_A.Pkey = TABLE_B.Fkey where TABLE_B.Pkey is null;
+----------+
| count(*) |
+----------+
| 139 |
+----------+
1 row in set (0.06 sec)
mysql> select count(*) from TABLE_A where NOT EXISTS (select * FROM TABLE_B WHERE TABLE_B.Fkey = TABLE_A.Pkey );
+----------+
| count(*) |
+----------+
| 139 |
+----------+
1 row in set (0.06 sec)
mysql>
If you're using Semantic UI React, data
is passed as the second parameter to the onChange
event.
You can therefore access the checked
property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
I like to be super lazy by using tables to align images with the vertical pipe (|
) syntax. This is supported by some Markdown flavours (and is also supported by Textile if that floats your boat):
| I am text to the left | ![Flowers](/flowers.jpeg) |
or
| ![Flowers](/flowers.jpeg) | I am text to the right |
It is not the most flexible solution, but it is good for most of my simple needs, is easy to read in markdown format, and you don't need to remember any CSS or raw HTML.
After some trial and tribulation, I was able to find all .msi files in a given directory and install them.
foreach($_msiFiles in
($_msiFiles = Get-ChildItem $_Source -Recurse | Where{$_.Extension -eq ".msi"} |
Where-Object {!($_.psiscontainter)} | Select-Object -ExpandProperty FullName))
{
msiexec /i $_msiFiles /passive
}
To get the first day of the month, simply get a Date
and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.
private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
First day of the week is the same thing, but using Calendar.DAY_OF_WEEK
instead
private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
It also gives the same error if you just stop your PostgreSQL app. You just need to start it again. (PostgreSQL 11)
jeb's edited answer comes close to solving all the issues. But it has problems with the following strings:
"a\b\"
"a/b/"
"\"
"/"
"."
".."
"c:"
I've modified his technique to something that I think can truly handle any string of printable characters, except for length limitations.
Other improvements:
Uses the %TEMP% location for the temp file, so no longer need write access to the current directory.
Created 2 variants, one takes a string literal, the other the name of a variable containing the string. The variable version is generally less convenient, but it eliminates some special character escape issues.
Added the /n option as an optional 3rd parameter to append a newline at the end of the output.
Backspace does not work across a line break, so the technique can have problems if the line wraps. For example, printing a string with length between 74 - 79 will not work properly if the console has a line width of 80.
@echo off
setlocal
call :initColorPrint
call :colorPrint 0a "a"
call :colorPrint 0b "b"
set "txt=^" & call :colorPrintVar 0c txt
call :colorPrint 0d "<"
call :colorPrint 0e ">"
call :colorPrint 0f "&"
call :colorPrint 1a "|"
call :colorPrint 1b " "
call :colorPrint 1c "%%%%"
call :colorPrint 1d ^"""
call :colorPrint 1e "*"
call :colorPrint 1f "?"
call :colorPrint 2a "!"
call :colorPrint 2b "."
call :colorPrint 2c ".."
call :colorPrint 2d "/"
call :colorPrint 2e "\"
call :colorPrint 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :colorPrintVar 74 complex /n
call :cleanupColorPrint
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color Str [/n]
setlocal
set "str=%~2"
call :colorPrintVar %1 str %3
exit /b
:colorPrintVar Color StrVar [/n]
if not defined %~2 exit /b
setlocal enableDelayedExpansion
set "str=a%DEL%!%~2:\=a%DEL%\..\%DEL%%DEL%%DEL%!"
set "str=!str:/=a%DEL%/..\%DEL%%DEL%%DEL%!"
set "str=!str:"=\"!"
pushd "%temp%"
findstr /p /A:%1 "." "!str!\..\x" nul
if /i "%~3"=="/n" echo(
exit /b
:initColorPrint
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do set "DEL=%%a"
<nul >"%temp%\x" set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%.%DEL%"
exit /b
:cleanupColorPrint
del "%temp%\x"
exit /b
UPDATE 2012-11-27
This method fails on XP because FINDSTR displays backspace as a period on the screen. jeb's original answer works on XP, albeit with the limitations already noted
UPDATE 2012-12-14
There has been a lot of development activity at DosTips and SS64. It turns out that FINDSTR also corrupts file names containing extended ASCII if supplied on the command line. I've updated my FINDSTR Q&A.
Below is a version that works on XP and supports ALL single byte characters except 0x00 (nul), 0x0A (linefeed), and 0x0D (carriage return). However, when running on XP, most control characters will display as dots. This is an inherent feature of FINDSTR on XP that cannot be avoided.
Unfortunately, adding support for XP and for extended ASCII characters slows the routine down :-(
Just for fun, I grabbed some color ASCII art from joan stark's ASCII Art Gallery and adapted it for use with ColorPrint. I added a :c entry point just for shorthand, and to handle an issue with quote literals.
@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E " , .-;" /n
call :c 0E " , |\ / / __," /n
call :c 0E " |\ '.`-.| |.'.-'" /n
call :c 0E " \`'-: `; : /" /n
call :c 0E " `-._'. \'|" /n
call :c 0E " ,_.-=` ` ` ~,_" /n
call :c 0E " '--,. "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E " / "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E " | "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E " / "&call :c 06 "\_,\|" /n
call :c 0E " | (" /n
call :c 0E " "&call :c 0c "__ "&call :c 0E "/ ' \" /n
call :c 02 " /\_ "&call :c 0c "/,'`"&call :c 0E "| ' "&call :c 0c ".-~!q!~~-." /n
call :c 02 " |`.\_ "&call :c 0c "| "&call :c 0E "/ ' , "&call :c 0c "/ \" /n
call :c 02 " _/ `, \"&call :c 0c "| "&call :c 0E "; , . "&call :c 0c "| , ' . |" /n
call :c 02 " \ `, "&call :c 0c "| "&call :c 0E "| , , "&call :c 0c "| : ; : |" /n
call :c 02 " _\ `, "&call :c 0c "\ "&call :c 0E "|. , "&call :c 0c "| | | | |" /n
call :c 02 " \` `. "&call :c 0c "\ "&call :c 0E "| ' "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 " _\ `, "&call :c 0A "`"&call :c 0E "\ ' . ' "&call :c 0A "| | | | | "&call :c 02 "__" /n
call :c 02 " \ `, "&call :c 0E "| , ' "&call :c 0A "|_/'-|_\_/ "&call :c 02 "__ ,-;` /" /n
call :c 02 " \ `, "&call :c 0E "\ . , ' .| | | | | "&call :c 02 "_/' ` _=`|" /n
call :c 02 " `\ `, "&call :c 0E "\ , | | | | |"&call :c 02 "_/' .=!q! /" /n
call :c 02 " \` `, "&call :c 0E "`\ \/|,| ;"&call :c 02 "/' .=!q! |" /n
call :c 02 " \ `, "&call :c 0E "`\' , | ; "&call :c 02 "/' =!q! _/" /n
call :c 02 " `\ `, "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/' =!q! /" /n
call :c 02 " jgs _`\ ;"&call :c 05 "_{ ' ; "&call :c 02 "/' =!q! /" /n
call :c 02 " _\`-/__"&call :c 05 ".~ `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q! _,/" /n
call :c 02 " __\ "&call :c 05 "{ '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 " _/" /n
call :c 02 " \ .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..' "&call :c 02 "__/" /n
call :c 02 " _/ .!q! "&call :c 05 "{ -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 " / .!q! _/'"&call :c 05 "`--; ; `. ;" /n
call :c 02 " .=!q! _/' "&call :c 05 "`-..__,-'" /n
call :c 02 " __/'" /n
echo(
exit /b
:c
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color Str [/n]
setlocal
set "s=%~2"
call :colorPrintVar %1 s %3
exit /b
:colorPrintVar Color StrVar [/n]
if not defined DEL call :initColorPrint
setlocal enableDelayedExpansion
pushd .
':
cd \
set "s=!%~2!"
:: The single blank line within the following IN() clause is critical - DO NOT REMOVE
for %%n in (^"^
^") do (
set "s=!s:\=%%~n\%%~n!"
set "s=!s:/=%%~n/%%~n!"
set "s=!s::=%%~n:%%~n!"
)
for /f delims^=^ eol^= %%s in ("!s!") do (
if "!" equ "" setlocal disableDelayedExpansion
if %%s==\ (
findstr /a:%~1 "." "\'" nul
<nul set /p "=%DEL%%DEL%%DEL%"
) else if %%s==/ (
findstr /a:%~1 "." "/.\'" nul
<nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%"
) else (
>colorPrint.txt (echo %%s\..\')
findstr /a:%~1 /f:colorPrint.txt "."
<nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
)
)
if /i "%~3"=="/n" echo(
popd
exit /b
:initColorPrint
for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "DEL=%%A %%A"
<nul >"%temp%\'" set /p "=."
subst ': "%temp%" >nul
exit /b
:cleanupColorPrint
2>nul del "%temp%\'"
2>nul del "%temp%\colorPrint.txt"
>nul subst ': /d
exit /b
the issue of too long content @beenotung can be resolved by this css class :
.col{
max-width :20% !important;
}
example fork from @jpoveda
Seems there is some demand to be able to access this statically.
How can I get such thing in static methods in non-spring-managed classes? – Aetherus
It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment()
before all beans have been created, since there is no guarantee when this component will be instantiated.
@Component
public class SpringContext
{
private static Environment environment;
public SpringContext(Environment environment) {
SpringContext.environment = environment;
}
public static Environment getEnvironment() {
if (environment == null) {
throw new RuntimeException("Environment has not been set yet");
}
return environment;
}
}
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
I had this problem when trying to resize a CMYK jpeg using the Intervention / gd library. I had to increase the memory_limit.
I'm going to hell for this :
=keyframes($name)
@-webkit-keyframes #{$name}
@content
@-moz-keyframes #{$name}
@content
@-ms-keyframes #{$name}
@content
@keyframes #{$name}
@content
+keyframes(blink)
25%
zoom: 1
opacity: 1
65%
opacity: 1
66%
opacity: 0
100%
opacity: 0
body
font-family: sans-serif
font-size: 4em
background: #222
text-align: center
.blink
color: rgba(#fff, 0.9)
+animation(blink 1s 0s reverse infinite)
+transform(translateZ(0))
.table
display: table
height: 5em
width: 100%
vertical-align: middle
.cell
display: table-cell
width: 100%
height: 100%
vertical-align: middle
http://codepen.io/anon/pen/kaGxC (sass with bourbon)
I kind of like this method which I think covers all the bases:
const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;
Thanks to @the-tin-man for putting together the benchmarks!
Alas, I don't really like any of those solutions. Either they require an extra step to get the result ([0] = ''
, .strip!
) or they aren't very semantic/clear about what's happening ([1..-1]
: "Um, a range from 1 to negative 1? Yearg?"), or they are slow or lengthy to write out (.gsub
, .length
).
What we are attempting is a 'shift' (in Array parlance), but returning the remaining characters, rather than what was shifted off. Let's use our Ruby to make this possible with strings! We can use the speedy bracket operation, but give it a good name, and take an arg to specify how much we want to chomp off the front:
class String
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
end
But there is more we can do with that speedy-but-unwieldy bracket operation. While we are at it, for completeness, let's write a #shift
and #first
for String (why should Array have all the fun??), taking an arg to specify how many characters we want to remove from the beginning:
class String
def first(how_many = 1)
self[0...how_many]
end
def shift(how_many = 1)
shifted = first(how_many)
self.replace self[how_many..-1]
shifted
end
alias_method :shift!, :shift
end
Ok, now we have a good clear way of pulling characters off the front of a string, with a method that is consistent with Array#first
and Array#shift
(which really should be a bang method??). And we can easily get the modified string as well with #eat!
. Hm, should we share our new eat!
ing power with Array? Why not!
class Array
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
end
Now we can:
> str = "[12,23,987,43" #=> "[12,23,987,43"
> str.eat! #=> "12,23,987,43"
> str #=> "12,23,987,43"
> str.eat!(3) #=> "23,987,43"
> str #=> "23,987,43"
> str.first(2) #=> "23"
> str #=> "23,987,43"
> str.shift!(3) #=> "23,"
> str #=> "987,43"
> arr = [1,2,3,4,5] #=> [1, 2, 3, 4, 5]
> arr.eat! #=> [2, 3, 4, 5]
> arr #=> [2, 3, 4, 5]
That's better!
Assuming the name of the dataframe after reading the excel sheet is df
, take an empty list (e.g. dataList
), iterate through the dataframe row by row and append to your empty list like-
dataList = [] #empty list
for index, row in df.iterrows():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
Or,
dataList = [] #empty list
for row in df.itertuples():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
No, if you print the dataList
, you will get each rows as a list in the dataList
.
This works for me:
var table = new DataTable();
table.Rows.Add();
It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?
I just read in the MySQL documentation that SHOW FULL PROCESSLIST
by default only lists the threads from your current user connection.
Quote from the MySQL SHOW FULL PROCESSLIST documentation:
If you have the PROCESS privilege, you can see all threads.
So you can enable the Process_priv
column in your mysql.user
table. Remember to execute FLUSH PRIVILEGES
afterwards :)
Alternatively if adding extra library such as hamcrest
is not desirable, the logic can be implemented as utility method using junit
dependency only:
public static void assertGreaterThan(int greater, int lesser) {
assertGreaterThan(greater, lesser, null);
}
public static void assertGreaterThan(int greater, int lesser, String message) {
if (greater <= lesser) {
fail((StringUtils.isNotBlank(message) ? message + " ==> " : "") +
"Expected: a value greater than <" + lesser + ">\n" +
"But <" + greater + "> was " + (greater == lesser ? "equal to" : "less than") + " <" + lesser + ">");
}
}
inputs[5].addEventListener('keydown', enterNumbers);
function enterNumbers(event) {
if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
(event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
(event.code == 'Delete') || (event.code == 'Backspace')) {
return;
} else if (event.key.search(/\d/) == -1) {
event.preventDefault();
}
}
in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.
Maybe not what you were looking for, but perhaps nice for someone to know:
If you are using .net Web Api 2 you could just do the following:
if (!ModelState.IsValid)
return BadRequest(ModelState);
Depending on the model errors, you get this result:
{
Message: "The request is invalid."
ModelState: {
model.PropertyA: [
"The PropertyA field is required."
],
model.PropertyB: [
"The PropertyB field is required."
]
}
}
>>> a=[]
>>> a.append([1,2])
>>> a
[[1, 2]]
>>> a=[]
>>> a+=[1,2]
>>> a
[1, 2]
See that append adds a single element to the list, which may be anything. +=[]
joins the lists.
Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched
robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
If you still want to group only by one column (as I wanted) you can nest the query:
select c1, count(*) from (select distinct c1, c2 from t) group by c1
a = [2 3 5];
b = [1 1 0];
c = a+b;
starts = zeros(3,3);
ends = [a;b;c];
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal
I just made a simple batch script that takes a file name as an argument compiles and runs the java file with one command. Here is the code:
@echo off
set arg1=%1
shift
javac -cp . %arg1%.java
java %arg1%
pause
I just saved that as run-java.bat and put it in the System32 directory so I can use the script from wherever I wish.
To use the command I would do:
run-java filename
and it will compile and run the file. Just make sure to leave out the .java extension when you type the filename (you could make it work even when you type the file name but I am new to batch and don't know how to do that yet).
SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)
Never returns any records unless eotm_dyn
is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn
like
SELECT * from employees
WHERE NOT EXISTS (
SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)
assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.
Select google map activity
you need a Google Maps API key.
To get one, follow this link, follow the directions and press "Create" at the end: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication
Paste this Code in MapsActivity.java
import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.widget.Toast; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implement OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
@private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
That's exactly what cursor: pointer;
is supposed to do.
If you want the cursor to remain normal, you should be using cursor: default
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:
overflow: hidden;
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
I needed this, the posts helped, this gets it down to one line, and if the path isn't a path at all, it just returns and exits the method. It addresses all of the above concerns, doesn't need the trailing slash either.
if (!Directory.Exists(@"C:\folderName")) return;
You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:
class D : public A
{
public:
D(const string &val) : A(0) {}
D( int val ) : A( val ) {}
};
D variable1( "Hello" );
D variable2( 10 );
C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
This doesn't have the regex overhead
double myNum = 0;
String testVar = "Not A Number";
if (Double.TryParse(testVar, out myNum)) {
// it is a number
} else {
// it is not a number
}
Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.
update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.
example 1:
public Boolean IsNumber(String s) {
Boolean value = true;
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
return value;
}
or if you want to be a little more fancy
public Boolean IsNumber(String value) {
return value.All(Char.IsDigit);
}
update 2 ( from @stackonfire to deal with null or empty strings)
public Boolean IsNumber(String s) {
Boolean value = true;
if (s == String.Empty || s == null) {
value=false;
} else {
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
} return value;
}
if you do not have an access to the commons apache library, the following probably will work ok
if(null != foo && foo.bar()) {
//do something
}
You could do this
Assembly asm = Assembly.GetExecutingAssembly();
string path = System.IO.Path.GetDirectoryName(asm.Location);
You can use a for each loop and count the number of integer values that are significant. You could also use an ArrayList which will keep track of the couny for you. Everytime you add or remove objects from the list it will automatically update the count. Calling the size() method will give you the current number of elements.
You can't use a foreach statement for that. The foreach is using internally an iterator:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
(From ArrayList javadoc)
In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:
int listSize = list.size();
for(int i = 0; i < listSize; ++i)
list.add("whatever");
Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.
its working
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textviewconclusion.frame.size.width
textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textviewconclusion.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textviewconclusion.frame = newFrame
}
Adding another solution for this issue.
in my Global.asax.cs file I had disabled attempted php files from being consumed by the MVC pipeline using the following:
routes.IgnoreRoute( "{*php}" );
I had done these previously in a MVC2 project and it worked fine, but doing this in my MVC 3 app caused the issue reported above.
This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.
This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.
In this example, clicking on the button changes the background color for a row and then calls repaint.
public class TableTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Color[] rowColors = new Color[] {
randomColor(), randomColor(), randomColor()
};
final JTable table = new JTable(3, 3);
table.setDefaultRenderer(Object.class, new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JPanel pane = new JPanel();
pane.setBackground(rowColors[row]);
return pane;
}
});
frame.setLayout(new BorderLayout());
JButton btn = new JButton("Change row2's color");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rowColors[1] = randomColor();
table.repaint();
}
});
frame.add(table, BorderLayout.NORTH);
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private static Color randomColor() {
Random rnd = new Random();
return new Color(rnd.nextInt(256),
rnd.nextInt(256), rnd.nextInt(256));
}
}
To use the Like Button and have the Open Graph inspect your website, you need an application.
So you need to associate the Like Button with a fb:app_id
If you want other users to see the administration page for your website on Facebook you add fb:admins
. So if you are the developer of the application and the website owner there is no need to add fb:admins
A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.
Set the CSS for the #footer
to:
position: absolute;
bottom: 0;
You will then need to add a padding
or margin
to the bottom of your #sidebar
and #content
to match the height of #footer
or when they overlap, the #footer
will cover them.
Also, if I remember correctly, IE6 has a problem with the bottom: 0
CSS. You might have to use a JS solution for IE6 (if you care about IE6 that is).
You can try the following solution to change the size of custom checkbox
by setting the following properties to Checkbox
in your layout file. Worked for me
android:scaleX="0.8" android:scaleY="0.8"
android:button="@null"
android:scaleX="0.8"
android:scaleY="0.8"
android:background="@drawable/custom_checkbox"
add following lines to drawable file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false"
android:drawable="@drawable/unchecked_img" />
<item android:state_checked="true"
android:drawable="@drawable/checked_img" />
</selector>
I know the topic is a bit old and seems stale, but anyway I was able to use these options:
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
when using 3.7 version of docker-compose
What helped in my case, was using this command:
docker-compose --compatibility up
--compatibility
flag stands for (taken from the documentation):
If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent
Think it's great, that I don't have to revert my docker-compose file back to v2.
Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:
export function forceCast<T>(input: any): T {
// ... do runtime checks here
// @ts-ignore <-- forces TS compiler to compile this as-is
return input;
}
Then you can use it to force cast objects to a certain type:
import { forceCast } from './forceCast';
const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);
Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts
interface files into JSON schemas and using ajv
to validate in runtime.
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}
The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive
was not longer working after navigation.
My solution was to use lotation.go:
import { Component } from "@angular/core";
import { Location } from "@angular/common";
import { HttpParams } from "@angular/common/http";
export class whateverComponent {
constructor(private readonly location: Location, private readonly router: Router) {}
addQueryString() {
const params = new HttpParams();
params.append("param1", "value1");
params.append("param2", "value2");
this.location.go(this.router.url.split("?")[0], params.toString());
}
}
I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.
and the this._router.url.split("?")[0]
, is to remove all previous query string from current url.
I have the same issue; I use gradle and IDEA;
It turns out that, it's caused by the wrong version of gradle.
In gradle\wrapper\gradle-wrapper.properties, it is:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-bin.zip
However, I specified the version in IDEA to be
D:\Library\gradle-5.2.1
After lower the gradle version to be 4.10.x, the issue is gone.
df[df['ID'].duplicated() == True]
This worked for me
$("#select_all").live("click", function(){
$("input").prop("checked", $(this).prop("checked"));
}
});
I found a good Blog post about the behaviour of Hibernate in this kind of object mappings: http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html
Arrays have a property .length
that returns the number of elements.
var st =
{
"itema":{},
"itemb":
[
{"id":"s01","cd":"c01","dd":"d01"},
{"id":"s02","cd":"c02","dd":"d02"}
]
};
st.itemb.length // 2
Java jar files are the same format as zip files - so if you have a zip file utility that would let you modify an archive, you have your foot in the door. Second problem is, if you want to recompile a class or something, you probably will just have to re-build the jar; but a text file or something (xml, for instance) should be easily enough modified.
SQL Server requires a transaction log in order to function.
That said there are two modes of operation for the transaction log:
In Full mode the transaction log keeps growing until you back up the database. In Simple mode: space in the transaction log is 'recycled' every Checkpoint.
Very few people have a need to run their databases in the Full recovery model. The only point in using the Full model is if you want to backup the database multiple times per day, and backing up the whole database takes too long - so you just backup the transaction log.
The transaction log keeps growing all day, and you keep backing just it up. That night you do your full backup, and SQL Server then truncates the transaction log, begins to reuse the space allocated in the transaction log file.
If you only ever do full database backups, you don't want the Full recovery mode.
You just need to update the AngularCli
npm install --save-dev @angular/cli@latest
Interesting question!
capitalize
transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter
pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.
So as far as I can see, this is indeed impossible to do with CSS.
@Harmen shows good-looking PHP and jQuery workarounds in his answer.
(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)
In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:
MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
// Database returned
});
According to the changelog for 3.0 you now get a client object containing the database object instead:
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
// Client returned
var db = client.db('mytestingdb');
});
The close()
method has also been moved to the client. The code in the question can therefore be translated to:
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
db.collection('customers').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
pkill is the easiest command line utility
pkill -f node
or
pkill -f nodejs
whatever name the process runs as for your os
Add .idea/*
to your exclusion list to prevent tracking of all .idea files, directories, and sub-resources.
Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.
For arrays:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
For objects:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
Note that only properties passing the hasOwnProperty
test will be enumerated.
If you want to open Form2
modally (meaning you can't click on Form1 while Form2 is open), you can do this:
using (Form2 f2 = new Form2())
{
f2.ShowDialog(this);
}
If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:
private Form2 _f2;
public void openForm2()
{
_f2 = new Form2();
_f2.Show(this); // the "this" is important, as this will keep Form2 open above
// Form1.
}
public void closeForm2()
{
_f2.Close();
_f2.Dispose();
}
I have resolved this problem in my way. Try connection string in this way:
<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).
You can use the toggle-event
(docs) method to assign 2 (or more) handlers that toggle with each click.
Example: http://jsfiddle.net/SQHQ2/1/
$("#topbar").toggle(function(){
$(this).animate({height:40},200);
},function(){
$(this).animate({height:10},200);
});
or you could create your own toggle behavior:
Example: http://jsfiddle.net/SQHQ2/
$("#topbar").click((function() {
var i = 0;
return function(){
$(this).animate({height:(++i % 2) ? 40 : 10},200);
}
})());
To find out what ports rabbitmq uses:
$ epmd -names
Outputs:
epmd: up and running on port 4369 with data:
name rabbit at port 25672
Run these as root:
lsof -i :4369
lsof -i :25672
Found: object with keys
Which means you passing something is a key-value. So you need to modify your handler:
fromonItemClick(e, item) {
this.setState({
lang: item,
});
}
to
onItemClick({e, item}) {
this.setState({
lang: item,
});
}
You missed out the braces ({}
).
In matplotlib 2.0 there is a parameter called fillstyle
which allows better control on the way markers are filled.
In my case I have used it with errorbars but it works for markers in general
http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html
fillstyle
accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
There are two important things to keep in mind when using fillstyle
,
1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle
2) You might want to control the marker edge width (using markeredgewidth
or mew
) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.
Following is an example using errorbars:
myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue', mec='blue')
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
It happened to me when I combined the bundle.crt and main cert. The reason was I copied the main cert below the bundle.crt. It should be the other way around
1/ main cert 2/ bundle.crt
Here is the example directly from PEP 8 on limiting line length:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
Have you tried this?
Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Edited per the apt comment from @J.F.Sebastian
$users = get-childitem \\ServerName\c$\users\ | select -ExpandProperty name
foreach ($user in $users)
{
remove-item -path "\\Servername\c$\Users\$user\AppData\Local\Microsoft\Office365\PowerShell\*" -Force -Recurse
Write-Warning "$user Cleaned"
}
Wrote the above to clean some logfiles without deleting the parent directory and this works perfectly!
The same error occurs also when doing SELECT DISTINCT ..., <CLOB_column>, ...
.
If this CLOB column contains values shorter than limit for VARCHAR2 in all the applicable rows you may use to_char(<CLOB_column>)
or concatenate results of multiple calls to DBMS_LOB.SUBSTR(<CLOB_column>, ...)
.
You could use --where option on mysqldump to produce an output that you are waiting for:
mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql
At most 100 rows from test.t1 will be dumped from database table.
Cheers, WB
Basic rules:
^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$
Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules.
Complete rules:
If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go:
^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$
Tested against our customers database and seems perfectly accurate.
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
If efficiency of looping the keys is a priority for your app, then choose a Map
implementation that maintains the keys in your desired order.
Will the ordering of elements depend on the specific map implementation that I have for the interface?
Yes, absolutely.
Map
implementations promise a certain iteration order, others do not.Map
maintain different ordering of the key-value pairs. See this table I created summarizing the various Map
implementations bundled with Java 11. Specifically, notice the iteration order column. Click/tap to zoom.
You can see there are four Map
implementations maintaining an order:
TreeMap
ConcurrentSkipListMap
LinkedHashMap
EnumMap
NavigableMap
interfaceTwo of those implement the NavigableMap
interface: TreeMap
& ConcurrentSkipListMap
.
The older SortedMap
interface is effectively supplanted by the newer NavigableMap
interface. But you may find 3rd-party implementations implementing the older interface only.
If you want a Map
that keeps its pairs arranged by the “natural order” of the key, use TreeMap
or ConcurrentSkipListMap
. The term “natural order” means the class of the keys implements Comparable
. The value returned by the compareTo
method is used for comparison in sorting.
If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a Comparator
implementation appropriate to the class of your keys. Use either TreeMap
or ConcurrentSkipListMap
, passing your Comparator
.
If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use LinkedHashMap
.
If you are using an enum such as DayOfWeek
or Month
as your keys, use the EnumMap
class. Not only is this class highly optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For DayOfWeek
, for example, the key of DayOfWeek.MONDAY
will be first found when iterated, and the key of DayOfWeek.SUNDAY
will be last.
In choosing a Map
implementation, also consider:
Collections::synchronizedMap
(less preferable). Both of these considerations are covered in the graphic table above.
I recompiled the package specification, even though the change was only in the package body. This resolved my issue
task :build => [:some_other_tasks] do
build
end
task :build_all do
[:debug, :release].each { |t| build t }
end
def build(type = :debug)
# ...
end
rake
's idioms, here are your possibilities, compiled from past answers:This always executes the task, but it doesn't execute its dependencies:
Rake::Task["build"].execute
This one executes the dependencies, but it only executes the task if it has not already been invoked:
Rake::Task["build"].invoke
This first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all:
Rake::Task["build"].reenable
Rake::Task["build"].invoke
Note that dependencies already invoked are not automatically re-executed unless they are re-enabled. In Rake >= 10.3.2, you can use the following to re-enable those as well:
Rake::Task["build"].all_prerequisite_tasks.each(&:reenable)
Food for thought: what would a text-to-speech synthesizer do with <center>
?
There is restriction on using --jars
: if you want to specify a directory for location of jar/xml
file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.
If you specify --driver-class-path
and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.
Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf
option. It's better to pass driver and executor class paths as --conf
, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.
spark-submit \
--master yarn \
--queue spark_queue \
--deploy-mode cluster \
--num-executors 12 \
--executor-memory 4g \
--driver-memory 8g \
--executor-cores 4 \
--conf spark.ui.enabled=False \
--conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapred.output.dir=/tmp \
--conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp
@selectField1 AS bit
@selectField2 AS bit
SELECT
CASE
WHEN @selectField1 THEN Field1
WHEN @selectField2 THEN Field2
ELSE someDefaultField
END
FROM Table
Is this what you're looking for?
Add display: grid
to the parent
Events can be initialized with an empty default delegate which is never removed:
public event EventHandler MyEvent = delegate { };
No null-checking necessary.
[Update, thanks to Bevan for pointing this out]
Be aware of the possible performance impact, though. A quick micro benchmark I did indicates that handling an event with no subscribers is 2-3 times slower when using the the "default delegate" pattern. (On my dual core 2.5GHz laptop that means 279ms : 785ms for raising 50 million not-subscribed events.). For application hot spots, that might be an issue to consider.
I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".
for me below worked:
chown -R ftpusername /var/app/current
I just had a similar situation and was looking for a solution that allows me to return an alternative default value without taking care of it at the caller side every time I need it. What we usually do in case Linq does not support what we want, is to write a new extension that takes care of it. That´s what I did. Here is what I came up with (not tested though):
public static class EnumerableExtensions
{
public static T FirstOrDefault<T>(this IEnumerable<T> items, T defaultValue)
{
foreach (var item in items)
{
return item;
}
return defaultValue;
}
public static T FirstOrDefault<T>(this IEnumerable<T> items, Func<T, bool> predicate, T defaultValue)
{
return items.Where(predicate).FirstOrDefault(defaultValue);
}
public static T LastOrDefault<T>(this IEnumerable<T> items, T defaultValue)
{
return items.Reverse().FirstOrDefault(defaultValue);
}
public static T LastOrDefault<T>(this IEnumerable<T> items, Func<T, bool> predicate, T defaultValue)
{
return items.Where(predicate).LastOrDefault(defaultValue);
}
}
String formatting, using the new-style .format()
method (with the defaults .format() provides):
'{}{}'.format(s, i)
Or the older, but "still sticking around", %
-formatting:
'%s%d' %(s, i)
In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.
These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.
How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.
<div class="container">
<div class="row">
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col1
</div>
<div class="col-xs-4 col-sm-2" align="center">
Col2
</div>
<div class="hidden-xs col-sm-6 col-md-5" align="center">
Col3
</div>
<div class="visible-md col-md-3 " align="center">
Col4
</div>
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col5
</div>
</div>
</div>
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;
Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)
var TextFit = function(){_x000D_
var container = $('.container');_x000D_
container.each(function(){_x000D_
var container_width = $(this).width(),_x000D_
width_offset = parseInt($(this).data('width-offset')),_x000D_
font_container = $(this).find('.font-container');_x000D_
_x000D_
if ( width_offset > 0 ) {_x000D_
container_width -= width_offset;_x000D_
}_x000D_
_x000D_
font_container.each(function(){_x000D_
var font_container_width = $(this).width(),_x000D_
font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
_x000D_
var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
_x000D_
if (diff_percentage !== 0){_x000D_
if ( container_width > font_container_width ) {_x000D_
new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
} else if ( container_width < font_container_width ) {_x000D_
new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
}_x000D_
}_x000D_
$(this).css('font-size', new_font_size + 'px');_x000D_
});_x000D_
});_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
TextFit();_x000D_
$(window).resize(function(){_x000D_
TextFit();_x000D_
});_x000D_
});
_x000D_
.container {_x000D_
width:341px;_x000D_
height:341px;_x000D_
background-color:#000;_x000D_
padding:20px;_x000D_
}_x000D_
.font-container {_x000D_
font-size:131px;_x000D_
text-align:center;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
<span class="font-container">£5000</span>_x000D_
</div>
_x000D_
A list comprehension is a simple approach:
j2 = [x for x in j if x >= 5]
Alternately, you can use filter
for the exact same result:
j2 = filter(lambda x: x >= 5, j)
Note that the original list j
is unmodified.
you cant do this. Use a custom popup. Something like with the help of jQuery UI or jQuery BOXY.
for jQuery UI http://jqueryui.com/demos/dialog/
for jQuery BOXY http://onehackoranother.com/projects/jquery/boxy/
This one also works
Remove the "php.executablePath" line from the VS code settings.
Then add the xampp php path to the System variables
After that restart the Visual Studio Code
You can return multiple value inside a xml data type in "case" expression, then extract them, also "else" block is available
SELECT
xmlcol.value('(value1)[1]', 'NVARCHAR(MAX)') AS value1,
xmlcol.value('(value2)[1]', 'NVARCHAR(MAX)') AS value2
FROM
(SELECT CASE
WHEN <condition 1> THEN
CAST((SELECT a1 AS value1, b1 AS value2 FOR XML PATH('')) AS XML)
WHEN <condition 2> THEN
CAST((SELECT a2 AS value1, b2 AS value2 FOR XML PATH('')) AS XML)
ELSE
CAST((SELECT a3 AS value1, b3 AS value2 FOR XML PATH('')) AS XML)
END AS xmlcol
FROM <table>) AS tmp
Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)
If you want more than one style this is the correct full answer. This is div with class and style:
<div className="class-example" style={{width: '300px', height: '150px'}}></div>
Well... sure... just access the parent and then the children.
node.parentNode.childNodes[]
or... using jQuery:
$('#innerId').siblings()
Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:
function getChildren(n, skipMe){
var r = [];
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 && n != skipMe)
r.push( n );
return r;
};
function getSiblings(n) {
return getChildren(n.parentNode.firstChild, n);
}
I found out that the naming of my css files was in conflict with the proxy filters
www.dating.com (which is not my site) was blocked and my css and js files were called dating.css and dating.js. The filter was blocking this. Maybe that is the case with some of you, working on corporates systems.
XAMPP Apache + MariaDB + PHP + Perl (X -any OS)
Open browser and in url type localhost
or 127.0.0.1
By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).
For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'
Building on this question, I use the following code to indent my messages:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
This is the output:
short text: indented looooooooooooooong text: indented
This is documented in section "Flag characters" in man 3 printf
.
Setting the photo as a background image will give us more control over size and placement, leaving the img tag to serve a different purpose...
Below, if we want the div to be the same aspect ratio as the photo, then placeholder.png is a small transparent image with the same aspect ratio as photo.jpg. If the photo is a square, it's a 1px x 1px placeholder, if the photo is a video thumbnail, it's a 16x9 placeholder, etc.
Specific to the question, use a 1x1 placeholder to maintain the div's square ratio, with a background image using background-size
to maintain the photo's aspect ratio.
I used background-position: center center;
so the photo will be centered in the div. (Aligning the photo in the vertical center or bottom would get ugly with the photo in the img tag.)
div {
background: url(photo.jpg) center center no-repeat;
background-size: contain;
width: 48px; // or a % in responsive layout
}
img {
width: 100%;
}
<div><img src="placeholder.png"/></div>
To avoid an extra http request, convert the placeholder image to a data: URL.
<img src="data:image/png;base64,..."/>
Select the cell you want to be like this, Go To Cell Properties (or CTRL 1) under Number tab in custom enter "X"#
Using text-indent on li works best.
text-indent: -x px; will move the bullet closer to li and vice-versa.
Using relative on span the negative left might not work properly with older versions for IE. P.S- avoid giving positions as much as you can.
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).
I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.
There are lots of great great answers here, and here is my take. PowerShell is ready if you are... Examples:
grep = "Select-String -Pattern"
sort = "Sort-Object"
uniq = "Get-Unique"
file = "Get-Item"
cat = "Get-Content"
Perl/AWK/Sed are not commands, but utilities hence hard to compare, but you can do almost everything in PowerShell.
For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.
\config\backup.php on line 123
'mail' => [
'to' => '',
],
This is old thread, but I have find new answer on https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
The problem with previous solution is that you need to have special div around video code, which is not suitable for most uses. So here is JavaScript solution without special div.
// Find all YouTube videos - RESIZE YOUTUBE VIDEOS!!!
var $allVideos = $("iframe[src^='https://www.youtube.com']"),
// The element that is fluid width
$fluidEl = $("body");
// Figure out and save aspect ratio for each video
$allVideos.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
$(window).resize(function() {
var newWidth = $fluidEl.width();
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all videos on page load
}).resize();
// END RESIZE VIDEOS
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
A (somewhat) different way:
reduce(lambda acc, x: acc + (1 if x > 5 else 0), j, 0)
Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.
Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.
In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
This is a little function that prints colored text using bash scripting. You may add as many styles as you want, and even print tabs and new lines:
#!/bin/bash
# prints colored text
print_style () {
if [ "$2" == "info" ] ; then
COLOR="96m";
elif [ "$2" == "success" ] ; then
COLOR="92m";
elif [ "$2" == "warning" ] ; then
COLOR="93m";
elif [ "$2" == "danger" ] ; then
COLOR="91m";
else #default color
COLOR="0m";
fi
STARTCOLOR="\e[$COLOR";
ENDCOLOR="\e[0m";
printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}
print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";
Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).
if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)
Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.
The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.
I always did it in this way:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
where this
is the JFrame involved.
I believe you are trying to do exactly what I just tried to do: I want two stacked canvases... the bottom one has a static image and the top one contains animated sprites. Because of the animation, you need to clear the background of the top layer to transparent at the start of rendering every new frame. I finally found the answer: it's not using globalAlpha, and it's not using a rgba() color. The simple, effective answer is:
context.clearRect(0,0,width,height);
As per Jenkins Documentation,
BUILD_NUMBER
is used. This number is identify how many times jenkins run this build process
$BUILD_NUMBER
is general syntax for it.
It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.
Example:
0x6400
translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600.
When compiler reads 0x6400
, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..
For binary it would be:
0b00000001
Hope I have helped in some way.
Good day!
There are no post/pre increment/decrement operators in python like in languages like C.
We can see ++
or --
as multiple signs getting multiplied, like we do in maths (-1) * (-1) = (+1).
E.g.
---count
Parses as
-(-(-count)))
Which translates to
-(+count)
Because, multiplication of -
sign with -
sign is +
And finally,
-count
Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim()
on a not existing object would throw an exception:
function isEmpty(value) {
return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}
Usage:
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
Although the answers above seems correct, just a simple explanation to give you an idea of how it works.
Suppose that your column is set to be DECIMAL(13,4)
. This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.
So, in summary, for that column you would have a max value of: 999999999.9999
Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.
There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:
$("#clickable").click(function(e) {
var senderElement = e.target;
// Check if sender is the <div> element e.g.
// if($(e.target).is("div")) {
window.location = url;
return true;
});
You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:
$("#clickable a").click(function(e) {
// Do something
e.stopPropagation();
});
Code:
library(microbenchmark)
dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
c=rep(LETTERS,10),d=rep(LETTERS,10))
}
mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
times=1000)
ggplot2::autoplot(mb)
Session:
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.5.0’
> packageVersion("data.table")
[1] ‘1.9.6’
UPDATE: Rerun 31-Jan-2018. Ran on the same computer. New versions of packages. Added seed for seed lovers.
set.seed(21)
library(microbenchmark)
dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
c=rep(LETTERS,10),d=rep(LETTERS,10))
}
mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
times=1000)
ggplot2::autoplot(mb)+theme_bw()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.7.2’
> packageVersion("data.table")
[1] ‘1.10.4’
UPDATE: Rerun 06-Aug-2019.
set.seed(21)
library(microbenchmark)
dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
c=rep(LETTERS,10),d=rep(LETTERS,10))
}
mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
purrr::map_df(dflist,dplyr::bind_rows),
times=1000)
ggplot2::autoplot(mb)+theme_bw()
R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so
packageVersion("plyr")
packageVersion("dplyr")
packageVersion("data.table")
packageVersion("purrr")
>> packageVersion("plyr")
[1] ‘1.8.4’
>> packageVersion("dplyr")
[1] ‘0.8.3’
>> packageVersion("data.table")
[1] ‘1.12.2’
>> packageVersion("purrr")
[1] ‘0.3.2’
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s
on a Unix terminal.
Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.
Example:
$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type
Your $xml
array contains an object or array at $xml->entry[$i]->source
for some value of $i
, and when you try to use that as an index key for $s
, you get that warning. You'll have to make sure $xml
contains what you want it to and that you're accessing it correctly.
In Workbook events:
Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub
In a module:
Sub RunEveryTwoMinutes()
//Add code here for whatever you want to happen
Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub
If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the Workbook_Open
event