There is an (somewhat) official option: jQuery.validator.format.
Comes with jQuery Validation Plugin 1.6 (at least).
Quite similar to the String.Format
found in .NET.
Edit Fixed broken link.
Yet another solution with another algorithm, by using bitwise operators.
def int2bin(val):
res=''
while val>0:
res += str(val&1)
val=val>>1 # val=val/2
return res[::-1] # reverse the string
A faster version without reversing the string.
def int2bin(val):
res=''
while val>0:
res = chr((val&1) + 0x30) + res
val=val>>1
return res
This one works with {0}, {1} and {}.
String.prototype.format = function format()
{
var msg = this;
for(var i in arguments)
msg = msg.replace(/\{\}/,arguments[i]).replace(new RegExp('\\{'+i+'\\}','g'),arguments[i]);
return msg;
}
You could encapsulate the string in a struct that implements IFormattable
public struct PaddedString : IFormattable
{
private string value;
public PaddedString(string value) { this.value = value; }
public string ToString(string format, IFormatProvider formatProvider)
{
//... use the format to pad value
}
public static explicit operator PaddedString(string value)
{
return new PaddedString(value);
}
}
Then use this like that :
string.Format("->{0:x20}<-", (PaddedString)"Hello");
result:
"->xxxxxxxxxxxxxxxHello<-"
I can see a number of reasons:
Readability
string s = string.Format("Hey, {0} it is the {1}st day of {2}. I feel {3}!", _name, _day, _month, _feeling);
vs:
string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ". I feel " + feeling + "!";
Format Specifiers (and this includes the fact you can write custom formatters)
string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
vs:
string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
String Template Persistence
What if I want to store string templates in the database? With string formatting:
_id _translation
1 Welcome {0} to {1}. Today is {2}.
2 You have {0} products in your basket.
3 Thank-you for your order. Your {0} will arrive in {1} working days.
vs:
_id _translation
1 Welcome
2 to
3 . Today is
4 .
5 You have
6 products in your basket.
7 Someone
8 just shoot
9 the developer.
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
About performance:
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = "Hi " + i + "; Hi to you " + i*2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = String.format("Hi %s; Hi to you %s",i, + i*2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
}
The timing results are as follows:
Therefore, concatenation is much faster than String.format.
did you try a clean? cmd + shift + k
First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.
Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.
Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.
So, to sum it all up:
ptr++; // Pointer moves to the next int position (as if it was an array)
++ptr; // Pointer moves to the next int position (as if it was an array)
++*ptr; // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++; // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr; // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault
As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.
EDIT:
So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
To add Tomer and Charles answers,
Syntax to run nginx in forground in Docker container using Entrypoint:
ENTRYPOINT nginx -g 'daemon off;'
Not directly related but to run multiple commands with Entrypoint:
ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;'
.panel.with-nav-tabs .panel-heading {_x000D_
padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
color: #777;_x000D_
background-color: #ddd;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
color: #555;_x000D_
background-color: #fff;_x000D_
border-color: #ddd;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #f5f5f5;_x000D_
border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
color: #fff;_x000D_
background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
color: #fff;_x000D_
background-color: #3071a9;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
color: #428bca;_x000D_
background-color: #fff;_x000D_
border-color: #428bca;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #428bca;_x000D_
border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
color: #3c763d;_x000D_
background-color: #d6e9c6;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
color: #3c763d;_x000D_
background-color: #fff;_x000D_
border-color: #d6e9c6;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #dff0d8;_x000D_
border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
color: #fff;_x000D_
background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
color: #31708f;_x000D_
background-color: #bce8f1;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
color: #31708f;_x000D_
background-color: #fff;_x000D_
border-color: #bce8f1;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #d9edf7;_x000D_
border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
color: #fff;_x000D_
background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
color: #8a6d3b;_x000D_
background-color: #faebcc;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
color: #8a6d3b;_x000D_
background-color: #fff;_x000D_
border-color: #faebcc;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #fcf8e3;_x000D_
border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
color: #fff;_x000D_
background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
color: #a94442;_x000D_
background-color: #ebccd1;_x000D_
border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
color: #a94442;_x000D_
background-color: #fff;_x000D_
border-color: #ebccd1;_x000D_
border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
background-color: #f2dede;_x000D_
/* bg color */_x000D_
border-color: #ebccd1;_x000D_
/* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
color: #a94442;_x000D_
/* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
background-color: #ebccd1;_x000D_
/* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
color: #fff;_x000D_
/* active text color */_x000D_
background-color: #a94442;_x000D_
/* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
<div class="page-header">_x000D_
<h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-default">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
<li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
<li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
<li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
<div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
<div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
<div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
<div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-primary">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
<li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
<li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
<li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
<div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
<div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
<div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
<div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-success">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
<li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
<li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
<li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
<div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
<div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
<div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
<div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-info">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
<li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
<li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
<li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
<div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
<div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
<div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
<div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-warning">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
<li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
<li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
<li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
<div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
<div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
<div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
<div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<div class="panel with-nav-tabs panel-danger">_x000D_
<div class="panel-heading">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
<li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
<li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
<li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
<div class="tab-content">_x000D_
<div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
<div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
<div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
<div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
<div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<br/>
_x000D_
If startDate and endDate are instance of java.util.Date
We can use the between( ) method from ChronoUnit enum:
public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}
ChronoUnit.DAYS count days which completed 24 hours.
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
//OR
ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
Save, then redefine the variable $_FILES to whatever you need. maybe not the best solution, but this worked for me.
function do_upload()
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$quantFiles = count($_FILES['userfile']['name']);
for($i = 0; $i < $quantFiles ; $i++)
{
$arquivo[$i] = array
(
'userfile' => array
(
'name' => $_FILES['userfile']['name'][$i],
'type' => $_FILES['userfile']['type'][$i],
'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
'error' => $_FILES['userfile']['error'][$i],
'size' => $_FILES['userfile']['size'][$i]
)
);
}
for($i = 0; $i < $quantFiles ; $i++)
{
$_FILES = '';
$_FILES = $arquivo[$i];
if ( ! $this->upload->do_upload())
{
$error[$i] = array('error' => $this->upload->display_errors());
return FALSE;
}
else
{
$data[$i] = array('upload_data' => $this->upload->data());
var_dump($this->upload->data());
}
}
if(isset($error))
{
$this->index($error);
}
else
{
$this->index($data);
}
}
the separate function to establish the config..
private function set_upload_options()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'xml|pdf';
$config['max_size'] = '10000';
return $config;
}
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
I just modified hhafez's test to include StringBuilder. StringBuilder is 33 times faster than String.format using jdk 1.6.0_10 client on XP. Using the -server switch lowers the factor to 20.
public class StringTest {
public static void main( String[] args ) {
test();
test();
}
private static void test() {
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for ( i = 0; i < 1000000; i++ ) {
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
new StringBuilder("Blah").append(i).append("Blah");
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
While this might sound drastic, I consider it to be relevant only in rare cases, because the absolute numbers are pretty low: 4 s for 1 million simple String.format calls is sort of ok - as long as I use them for logging or the like.
Update: As pointed out by sjbotha in the comments, the StringBuilder test is invalid, since it is missing a final .toString()
.
The correct speed-up factor from String.format(.)
to StringBuilder
is 23 on my machine (16 with the -server
switch).
A simple approach would be to use the /MIR option, to mirror the two directories. Basically it will copy only the new files to destination. In next comand replace source and destination with the paths to your folders, the script will search for any file with any extensions.
robocopy <source directory> <destination directory> *.* /MIR
I like to use a TreeWalker if the set of elements are children of a root node.
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
I needed to enable the JUnit plugin, after I linked my project with the jar files.
To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.
vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to
C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\
and add these jar files:
hamcrest-core-1.3.jar
junit-4.11.jar
junit.jar
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
You can remove the reference using null
.
Let's say You have class A
:
A a = new A();
a=null;
last statement will remove the reference of the object a
and that object will be "garbage collected" by JVM.
It is one of the easiest ways to do this.
You could also try this:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
This answer mentions Json.NET but stops short of telling you how you can use Json.NET to serialize a dictionary:
return JsonConvert.SerializeObject( myDictionary );
As opposed to JavaScriptSerializer, myDictionary
does not have to be a dictionary of type <string, string>
for JsonConvert to work.
Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.
The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.
Try this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://domain1.com',
'http://domain2.com',
);
if (in_array($http_origin, $allowed_domains))
{
header("Access-Control-Allow-Origin: $http_origin");
}
There are 2 problems we are looking at:
Rounding conversions mean rounding ± float/double to nearest floor/ceil float/double. May be your problem ends here. But if you are expected to return Int/Long, you need to perform type conversion, and thus "Overflow" problem might hit your solution. SO, do a check for error in your function
long round(double x) {
assert(x >= LONG_MIN-0.5);
assert(x <= LONG_MAX+0.5);
if (x >= 0)
return (long) (x+0.5);
return (long) (x-0.5);
}
#define round(x) ((x) < LONG_MIN-0.5 || (x) > LONG_MAX+0.5 ?\
error() : ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
import java.util.LinkedList;
import java.util.Queue;
public class StackQueue {
static Queue<Integer> Q1 = new LinkedList<Integer>();
static Queue<Integer> Q2 = new LinkedList<Integer>();
public static void main(String args[]) {
push(24);
push(34);
push(4);
push(10);
push(1);
push(43);
push(21);
System.out.println("Popped element is "+pop());
System.out.println("Popped element is "+pop());
System.out.println("Popped element is "+pop());
}
public static void push(int data) {
Q1.add(data);
}
public static int pop() {
if(Q1.isEmpty()) {
System.out.println("Cannot pop elements , Stack is Empty !!");
return -1;
}
else
{
while(Q1.size() > 1) {
Q2.add(Q1.remove());
}
int element = Q1.remove();
Queue<Integer> temp = new LinkedList<Integer>();
temp = Q1;
Q1 = Q2;
Q2 = temp;
return element;
}
}
}
Perhaps what you are looking for is the Singleton pattern?
public class Singleton
{
private Singleton() {}
public void DoWork()
{
// do something
}
// You can call this static method which calls the singleton instance method.
public static void DoSomeWork()
{
Instance.DoWork();
}
public static Singleton Instance
{
get { return instance; }
}
private static Singleton instance = new Singleton();
}
You still have to create an instance of the class but you ensure there is only one instance.
Encode your data string into JSON.
dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
In your PHP
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
Note
When you send data via POST, it needs to be as a keyvalue pair.
Thus
data: dataString
is wrong. Instead do:
data: {data:dataString}
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
Since innerHeight
doesn't work in some old IE versions, clientHeight
can be used:
$(window).scroll(function (e){
var body = document.body;
//alert (body.clientHeight);
var scrollTop = this.pageYOffset || body.scrollTop;
if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
loadMoreNews();
}
});
Now with xCode 8 you can do:
? + ? + /
to auto-generate a doc comment.
Source: https://twitter.com/felix_schwarz/status/774166330161233920
I like to use the recursive pattern for this scenario. For example, something like this:
// If config is an array of queries
var config = JSON.parse(queries.querrryArray);
// Array of results
var results;
processQueries(config);
function processQueries(queries) {
var searchQuery;
if (queries.length == 0) {
// All queries complete
res.writeHead(200, {'content-type': 'application/json'});
res.end(JSON.stringify({results: results}));
return;
}
searchQuery = queries.pop();
search(searchQuery, function(result) {
results.push(JSON.stringify({result: result});
processQueries();
});
}
processQueries
is a recursive function that will pull a query element out of an array of queries to process. Then the callback function calls processQueries
again when the query is complete. The processQueries
knows to end when there are no queries left.
It is easiest to do this using arrays, but it could be modified to work with object key/values I imagine.
You've basically answered anything and everything already, so I'm no sure what the point is here?
FWIW I would use an httphandler - there seems no point in invoking a page lifecycle and having to deal with clipping off the bits of viewstate and session and what have you which don't make sense for an XML doc. It's like buying a car and stripping it for parts to make your motorbike.
And content-type is all important, it's how the requester knows what to do with the response.
Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.
Most of my points are related to Invariant's answer, so I would suggest to go through it first.
UPDATE
JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.
Old answer with JavaFXPorts
Some bad news first:
Now, some good news:
If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.
Most of the documentation on how to get started can be found here and some of the samples can be found here.
Make it work, in values-v21 styles or theme xml needs to use this attribute:
<item name="android:windowTranslucentStatus">true</item>
That make the magic!
To get the path of file in application package;
ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();
Make sure you have commented out any commentaries. Sometimes when copying and pasting you will leave out the "/*!"
Also when you go into the console they will list your errors and you should take it one at a time. If you see "Uncaught SyntaxError: Unexpected token * " That might mean it is reading your js file and it isn't getting past the first line.
/*! * jquery.tools 1.1.2 - The missing UI library for the Web * * [tools.tabs-1.0.4, tools.tooltip-1.1.2, tools.scrollable-1.1.2, tools.overlay-1.1.2, tools.expose-1.0.5] * * Copyright (c) 2009 Tero Piirainen * http://flowplayer.org/tools/ * File generated: Wed Oct 07 09:40:16 GMT 2009 */
Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's
SELECT distinct 1 products.id FROM products WHERE products.id = ?;
You can use peseudo elements like this:
input[type=checkbox] {_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
margin-right: 8px;_x000D_
cursor: pointer;_x000D_
font-size: 27px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
content: " ";_x000D_
background-color: #9FFF9D;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "\2714";_x000D_
}
_x000D_
<label>Checkbox label_x000D_
<input type="checkbox">_x000D_
</label>
_x000D_
The support for stored procedure in EF Core is similar to the earlier versions of EF Code first.
You need to create your DbContext class by inherting the DbContext class from EF. The stored procedures are executing using the DbContext.
First step is to write a method that create a DbCommand from the DbContext.
public static DbCommand LoadStoredProc(
this DbContext context, string storedProcName)
{
var cmd = context.Database.GetDbConnection().CreateCommand();
cmd.CommandText = storedProcName;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
return cmd;
}
To pass parameters to the stored procedure use the following method.
public static DbCommand WithSqlParam(
this DbCommand cmd, string paramName, object paramValue)
{
if (string.IsNullOrEmpty(cmd.CommandText))
throw new InvalidOperationException(
"Call LoadStoredProc before using this method");
var param = cmd.CreateParameter();
param.ParameterName = paramName;
param.Value = paramValue;
cmd.Parameters.Add(param);
return cmd;
}
Finally for mapping the result into a list of custom objects use the MapToList method.
private static List<T> MapToList<T>(this DbDataReader dr)
{
var objList = new List<T>();
var props = typeof(T).GetRuntimeProperties();
var colMapping = dr.GetColumnSchema()
.Where(x => props.Any(y => y.Name.ToLower() == x.ColumnName.ToLower()))
.ToDictionary(key => key.ColumnName.ToLower());
if (dr.HasRows)
{
while (dr.Read())
{
T obj = Activator.CreateInstance<T>();
foreach (var prop in props)
{
var val =
dr.GetValue(colMapping[prop.Name.ToLower()].ColumnOrdinal.Value);
prop.SetValue(obj, val == DBNull.Value ? null : val);
}
objList.Add(obj);
}
}
return objList;
}
Now we’re ready for execute the stored procedute with the ExecuteStoredProc method and maps it to the a List whose type that’s passed in as T.
public static async Task<List<T>> ExecuteStoredProc<T>(this DbCommand command)
{
using (command)
{
if (command.Connection.State == System.Data.ConnectionState.Closed)
command.Connection.Open();
try
{
using (var reader = await command.ExecuteReaderAsync())
{
return reader.MapToList<T>();
}
}
catch(Exception e)
{
throw (e);
}
finally
{
command.Connection.Close();
}
}
}
For example, to execute a stored procedure called “StoredProcedureName” with two parameters called “firstparamname” and “secondparamname” this is the implementation.
List<MyType> myTypeList = new List<MyType>();
using(var context = new MyDbContext())
{
myTypeList = context.LoadStoredProc("StoredProcedureName")
.WithSqlParam("firstparamname", firstParamValue)
.WithSqlParam("secondparamname", secondParamValue).
.ExecureStoredProc<MyType>();
}
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
Optional Constraint Name:
If you leave out CONSTRAINT D_SomeTable_SomeCol
then SQL Server will autogenerate
a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6
Optional With-Values Statement:
The WITH VALUES
is only needed when your Column is Nullable
and you want the Default Value used for Existing Records.
If your Column is NOT NULL
, then it will automatically use the Default Value
for all Existing Records, whether you specify WITH VALUES
or not.
How Inserts work with a Default-Constraint:
If you insert a Record into SomeTable
and do not Specify SomeCol
's value, then it will Default to 0
.
If you insert a Record and Specify SomeCol
's value as NULL
(and your column allows nulls),
then the Default-Constraint will not be used and NULL
will be inserted as the Value.
Notes were based on everyone's great feedback below.
Special Thanks to:
@Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
Note for the answer-seekers (who I also was) - if using arc is not obligatory, a far simpler solution to draw a part-circle is to use stroke-dasharray
of SVG <circle>
.
Divide dash array into two elements, and scale their range to the desired angle. Starting angle can be adjusted using stroke-dashoffset
.
Not a single cosine in sight.
Full example with explanations: https://codepen.io/mjurczyk/pen/wvBKOvP
Set the property RetainSameConnection
on the Connection Manager
to True
so that temporary table created in one Control Flow task can be retained in another task.
Here is a sample SSIS package written in SSIS 2008 R2
that illustrates using temporary tables.
Create a stored procedure that will create a temporary table named ##tmpStateProvince
and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora
Use the below create stored procedure script.
USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
Create a table named dbo.StateProvince
that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.
USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
Create an SSIS package using Business Intelligence Development Studio (BIDS)
. Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection...
to create a new connection to access SQL Server 2008 R2 database.
Click New...
on Configure OLE DB Connection Manager.
Perform the following actions on the Connection Manager dialog.
Native OLE DB\SQL Server Native Client 10.0
from Provider since the package will connect to SQL Server 2008 R2 databaseMACHINENAME\INSTANCE
Use Windows Authentication
from Log on to the server section or whichever you prefer.Select or enter a database name
, the sample uses the database name Sora
.Test Connection
OK
on the Test connection succeeded message.OK
on Connection ManagerThe newly created data connection will appear on Configure OLE DB Connection Manager. Click OK
.
OLE DB connection manager KIWI\SQLSERVER2008R2.Sora
will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties
Set the property RetainSameConnection
on the connection KIWI\SQLSERVER2008R2.Sora
to the value True
.
Right-click anywhere inside the package and then click Variables
to view the variables pane. Create the following variables.
A new variable named PopulateTempTable
of data type String
in the package scope SO_5631010
and set the variable with the value EXEC dbo.PopulateTempTable
.
A new variable named FetchTempData
of data type String
in the package scope SO_5631010
and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince
Drag and drop an Execute SQL Task
on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.
On the General
page of the Execute SQL Task Editor, perform the following actions.
Create and populate temp table
OLE DB
KIWI\SQLSERVER2008R2.Sora
Variable
from SQLSourceTypeUser::PopulateTempTable
from SourceVariableOK
Drag and drop a Data Flow Task
onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table
. Connect the green arrow from the Execute SQL Task to the Data Flow Task.
Double-click the Data Flow Task
to switch to Data Flow tab. Drag and drop an OLE DB Source
onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.
On the Connection Manager
page of the OLE DB Source Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerSQL command from variable
from Data access modeUser::FetchTempData
from Variable nameColumns
pageClicking Columns
page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince
specified in the source command variable does not exist and SSIS is unable to read the column definition.
To fix the error, execute the statement EXEC dbo.PopulateTempTable
using SQL Server Management Studio (SSMS) on the database Sora
so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns
page on OLE DB Source Editor, you will see the column information. Click OK
.
Drag and drop OLE DB Destination
onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination
to open OLE DB Destination Editor.
On the Connection Manager
page of the OLE DB Destination Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerTable or view - fast load
from Data access mode[dbo].[StateProvince]
from Name of the table or the viewMappings
pageClick Mappings
page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK
. Column StateProvinceID
does not have a matching input column and it is defined as an IDENTITY
column in database. Hence, no mapping is required.
Data Flow tab should look something like this after configuring all the components.
Click the OLE DB Source
on Data Flow tab and press F4 to view Properties
. Set the property ValidateExternalMetadata
to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.
Execute the package. Control Flow shows successful execution.
In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.
The above example illustrated how to create and use temporary table within a package.
There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:
http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp
You can also use the setProperty method like below
document.getElementById('divName').style.setProperty("top", "100px");
Use
"$filepath"_newstap.sh
or
${filepath}_newstap.sh
or
$filepath\_newstap.sh
_
is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap
.
You can use set -u
to make the shell exit with an error when you reference an undefined variable.
These need to go as different commands e.g.:
NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"
The expansion $NAME
to empty string is done by the shell earlier, before running echo
, so at the time the NAME
variable is passed to the echo
command's environment, the expansion is already done (to null string).
To get the same result in one command:
NAME=sam printenv NAME
In Weblogic 9.2 the configuration via console is as follows:
I believe the default value was 60
.
Remember to use Release Configuration
button after you edit the field.
I know this is three years old, but thought it might be helpful to someone.
The concept is to use the :after (or :before) selector to position a border within the parent element.
.container{
position:relative; /*Position must be set to something*/
}
.container:after{
position:relative;
top: 0;
content:"";
left:0;
height: 100%; /*Set pixel height and width if not defined in parent element*/
width: 100%;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
border:1px solid #000; /*set your border style*/
}
For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).
The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.
Great question - I solved my issue today as follows using Ecilpse:
Put your template in the same folder hierarchy as your source code (not in a separate folder hierarchy even if you include it in the build path) as below:
In your code simply use the following lines of code (assuming you just want the date to be passed as data):
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext context = new VelocityContext();
context.put("date", getMyTimestampFunction());
Template t = ve.getTemplate( "templates/email_html_new.vm" );
StringWriter writer = new StringWriter();
t.merge( context, writer );
See how first we tell VelocityEngine to look in the classpath. Without this it wouldn't know where to look.
In order to answer you questions;
"?v=1" this is written only beacuse to download a fresh copy of the css and js files instead of using from the cache of the browser.
If you mention this query string parameter at the end of your stylesheet or the js file then it forces the browser to download a new file, Due to which the recent changes in the .css and .js files are made effetive in your browser.
If you dont use this versioning then you may need to clear the cache of refresh the page in order to view the recent changes in those files.
Here is an article that explains this thing How and Why to make versioning of CSS and JS files
Regarding whether the stack is implemented in the hardware, this Wikipedia article might help.
Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's Application Binary Interface (ABI).
That article and the others it links to might be useful to get a feel for stack usage in processors.
Using the principle of the idea user2620505 got result with implementation of addClass:
...
open: function(){
$('.ui-dialog-titlebar-close').addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only');
$('.ui-dialog-titlebar-close').append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
},
...
If English is bad forgive me, I am using Google Translate.
or Just %~F will give you the full path and full file name.
For example, if you want to register all *.ax files in the current directory....
FOR /R C:. %F in (*.ax) do regsvr32 "%~F"
This works quite nicely in Win7 (64bit) :-)
$computer,$Speed,$Regcheck
will create an array, and run out-file
ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:
"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
You can also read lines w/o loop. Works in python3.6.
import os
import subprocess
process = subprocess.Popen(command, stdout=subprocess.PIPE)
list_of_byte_strings = process.stdout.readlines()
I clone libgdx
demo, can't import project. it also reminds like this.
Env:
Eclipse(Android-ADT)
window 7
so I create local.properties file at the project root, like following
sdk.dir = D:/adt-bundle-windows-x86/sdk
I hope this can help others!
Instant.ofEpochMilli( myMillisSinceEpoch ) // Convert count-of-milliseconds-since-epoch into a date-time in UTC (`Instant`).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust into the wall-clock time used by the people of a particular region (a time zone). Produces a `ZonedDateTime` object.
.toLocalDate() // Extract the date-only value (a `LocalDate` object) from the `ZonedDateTime` object, without time-of-day and without time zone.
.format( // Generate a string to textually represent the date value.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Specify a formatting pattern. Tip: Consider using `DateTimeFormatter.ofLocalized…` instead to soft-code the formatting pattern.
) // Returns a `String` object.
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes used by all the other Answers.
Assuming you have a long
number of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z…
Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;
To get a date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
Extract a date-only value.
LocalDate ld = zdt.toLocalDate() ;
Generate a String representing that value using standard ISO 8601 format.
String output = ld.toString() ;
Generate a String in custom format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;
Tip: Consider letting java.time automatically localize for you rather than hard-code a formatting pattern. Use the DateTimeFormatter.ofLocalized…
methods.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Seems like the a
tag is hidden. Remember Selenium is not able to interact with hidden element. Javascript
is the only option in that case.
By css = By.cssSelector("a[href='/docs/configuration']");
WebElement element = driver.findElement(css);
((JavascriptExecutor)driver).executeScript("arguments[0].click();" , element);
For anyone that stumbles upon this page, none of the solutions here worked for me. I found this is the way to do it (in a batch file):
@for /f "skip=1" %%p in ('wmic cpu get loadpercentage /VALUE') do (
for /F "tokens=2 delims==" %%J in ("%%p") do echo %%J
)
What database are you using? normally you don't save files to a database but i think sql 2008 has support for it...
A file is binary data hence UTF 8 does not matter here..
UTF 8 matters when you try to convert a string to a byte array... not a file to byte array.
push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below
var lastIndex = Object.keys(element)[Object.keys(element).length-1];
then add object to the new index of element
element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
They say it right there in the documentation for the FPDF constructor:
FPDF([string orientation [, string unit [, mixed size]]])
This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...
size
The size used for pages. It can be either one of the following values (case insensitive):
A3 A4 A5 Letter Legal
or an array containing the width and the height (expressed in the unit given by unit).
They even give an example with custom size:
Example with a custom 100x150 mm page size:
$pdf = new FPDF('P','mm',array(100,150));
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")
The beauty of this formula is you can add more data to columns A and B and it will just recalculate.
You might need to use the ".live" option in jQuery since the behavior will be evaluated in real-time based on the condition you've set.
$('#my_select').live('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
You can create abstract classes by using object prototypes, a simple example can be as follows :
var SampleInterface = {
addItem : function(item){}
}
You can change above method or not, it is up to you when you implement it. For a detailed observation, you may want to visit here.
Waht about: http://www.mattkruse.com/javascript/calendarpopup/
Select the month-select example
When Xcode asks you to reset certs, you reset it. And the app can be run on actual device without crash with that error messages. Once this problem is fixed in one swift project. Other swift projects with this problem are fixed also.
I have struggled for these about half a day and I found that reset certs again and again in provisioning portal doesn't help.
Android Studio
> Preferences
> Appearance & Behaviour
> System Settings
> Android SDK
> Android SDK Location
.bash_profile
file for your environment variablescd ~
touch .bash_profile
.bash_profile
open .bash_profile
Add export PATH=$PATH:
[your SDK location]
/platform-tools
to the file and hit ?s
to save it. By default it's:
export PATH=$PATH:/Users/yourUserName/Library/Android/sdk/platform-tools
Go back to your Terminal App and load the variable with source ~/.bash_profile
It is better to use API Key in header, not in URL.
URLs are saved in browser's history if it is tried from browser. It is very rare scenario. But problem comes when the backend server logs all URLs. It might expose the API key.
In two ways, you can use API Key in header
Basic Authorization:
Example from stripe:
curl https://api.stripe.com/v1/charges -u sk_test_BQokikJOvBiI2HlWgH4olfQ2:
curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password).
Custom Header
curl -H "X-API-KEY: 6fa741de1bdd1d91830ba" https://api.mydomain.com/v1/users
'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.
When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.
I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.
Typing SET /?
explains the thing reasonably well:
Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "%VAR%" == "after" @echo If you see this, it worked )
would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:
set LIST= for %i in (*) do set LIST=%LIST% %i echo %LIST%
in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:
for %i in (*) do set LIST= %i
which just keeps setting LIST to the last file found.
Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "!VAR!" == "after" @echo If you see this, it worked ) set LIST= for %i in (*) do set LIST=!LIST! %i echo %LIST%
Another example is this batch file:
@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
set b=%%a
echo !b:1=2!
)
This prints x2
and y2
: every 1 gets replaced by a 2.
Without setlocal enabledelayedexpansion
, exclamation marks are just that, so it will echo !b:1=2!
twice.
Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2%
uses the value b
has before the loop: z2
(but y2
when not set).
XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to DBG debugger Its php benchmarking provides timing for functions, methods, modules and even lines.
Unfortunately this answer is probably of little or no help whatsoever, but I did a forensics analysis of the Java Lambda Mailing list to see if I could find the cause of this design. This is what I found out.
In the beginning there was an instance method for Stream.concat(Stream)
In the mailing list I can clearly see the method was originally implemented as an instance method, as you can read in this thread by Paul Sandoz, about the concat operation.
In it they discuss the issues that could arise from those cases in which the stream could be infinite and what concatenation would mean in those cases, but I do not think that was the reason for the modification.
You see in this other thread that some early users of the JDK 8 questioned about the behavior of the concat instance method when used with null arguments.
This other thread reveals, though, that the design of the concat method was under discussion.
Refactored to Streams.concat(Stream,Stream)
But without any explanation, suddenly, the methods were changed to static methods, as you can see in this thread about combining streams. This is perhaps the only mail thread that sheds a bit of light about this change, but it was not clear enough for me to determine the reason for the refactoring. But we can see they did a commit in which they suggested to move the concat
method out of Stream
and into the helper class Streams
.
Refactored to Stream.concat(Stream,Stream)
Later, it was moved again from Streams
to Stream
, but yet again, no explanation for that.
So, bottom line, the reason for the design is not entirely clear for me and I could not find a good explanation. I guess you could still ask the question in the mailing list.
Some Alternatives for Stream Concatenation
This other thread by Michael Hixson discusses/asks about other ways to combine/concat streams
To combine two streams, I should do this:
Stream.concat(s1, s2)
not this:
Stream.of(s1, s2).flatMap(x -> x)
... right?
To combine more than two streams, I should do this:
Stream.of(s1, s2, s3, ...).flatMap(x -> x)
not this:
Stream.of(s1, s2, s3, ...).reduce(Stream.empty(), Stream::concat)
... right?
The code you are talking about sounds like ServiceLoader
, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.
There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.
A much easier and resource friendly approach would be.
import UIKit
@IBDesignable
class CircleDrawView: UIView {
@IBInspectable var borderColor: UIColor = UIColor.red;
@IBInspectable var borderSize: CGFloat = 4
override func draw(_ rect: CGRect)
{
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderSize
layer.cornerRadius = self.frame.height/2
}
}
With Border Color
and Border Size
and the default Background
property you can define the appearance of the circle.
Please note, to draw a circle the view's height and width have to be equal in size.
The code is working for Swift >= 4
and Xcode >= 9
.
I found this on another post, which did not get many upvotes, but it was super helpful for me. So will add it here.
Android Studio will bring a keytool with it.
C:\Program Files\Android\Android Studio\jre\bin
You can see his post below by Richar Heap, with a helpful reference. I did see this before but forgot about it. https://stackoverflow.com/a/51524526/4446406
By default use ALT+p for previous command, you can change to Up-Arrow instead in IDLE GUi >> OPtions >> Configure IDLE >>Key >>Custom Key Binding It is not necesary to run a custom script, besides readlines module doesnt run in Windows. Hope That Help. :)
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
We can use the 'type' command to see file contents in cmd.
Example -
type abc.txt
More information can be found HERE.
To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.
Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.
Example:
/* Utils.js */
/* This file contains functions you can use anywhere in your application */
function formatName(label) {
// your logic
}
function formatDate(date) {
// your logic
}
// Now you have to export each function you want
export {
formatName,
formatDate,
};
Let's create another file which has functions to help you with tables:
/* Table.js */
/* Table file contains functions to help you when working with tables */
function getColumnsFromData(data) {
// your logic
}
function formatCell(data) {
// your logic
}
// Export each function
export {
getColumnsFromData,
formatCell,
};
Now the trick is to have a index.js inside the helpers folder:
/* Index.js */
/* Inside this file you will import your other helper files */
// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';
// Export again
export {
Utils,
Table,
};
Now you can import then separately to use each function:
import { Table, Utils } from 'helpers';
const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);
const myName = Utils.formatName(someNameVariable);
Hope it can help to organise your files in a better way.
I had this issue when running older XP SP3 boxes against both IIS and glassfish on Amazon AWS. Amazon changed their default load balancer settings to NOT enable the DES-CBC3-SHA cipher. You have to enable that on amazon ELB if you want to allow older XP TLS 1.0 to work against ELB for HTTPS otherwise you get this error. Ciphers can be changed on ELB by going to the listener tab in the console and clicking on cipher next to the particular listener you are trying to make work.
Try something like this:
Sub ClearDataFilters()
'Clears filters on the activesheet. Will not clear filters if the sheet is protected.
On Error GoTo Protection
If ActiveWorkbook.ActiveSheet.FilterMode Or _
ActiveWorkbook.ActiveSheet.AutoFilterMode Then _
ActiveWorkbook.ActiveSheet.ShowAllData
Exit Sub
Protection:
If Err.Number = 1004 And Err.Description = _
"ShowAllData method of Worksheet class failed" Then
MsgBox "Unable to Clear Filters. This could be due to protection on the sheet.", _
vbInformation
End If
End Sub
.FilterMode
returns true if the worksheet is in filter mode. (See this for more information.)
See this for more information on .AutoFilter
.
And finally, this will provide more information about the .ShowAllData
method.
This will not work:
wget -q -S -O - google.com 1>wget.txt 2>&1
since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:
wget -q -S -O - google.com 2>&1 1>wget.txt
Plain html cannot allow you to do this. But with javascript you can be able to do that. If you are using javascript/jquery you could classify your form elements with a class and then use serialize() to serialize only those form elements for the subset of the items you want to submit.
<form id="formid">
<input type="text" class="class1" />
<input type="text" class="class2">
</form>
Then in your javascript you could do this to serialize class1 elements
$(".class1").serialize();
For class2 you could do
$(".class2").serialize();
For the whole form
$("#formid").serialize();
or simply
$("#formid").submit();
Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'
It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.
as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir
It's also possible by using rsync
, for example:
rsync -va --delete-after src/ dst/
where:
-v
, --verbose
: increase verbosity-a
, --archive
: archive mode; equals -rlptgoD
(no -H,-A,-X
)--delete-after
: delete files on the receiving side be done after the transfer has completedIf you've root privileges, prefix with sudo
to override potential permission issues.
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/
This method is also included with json2.js, for supporting older browsers.
If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.
I also got this error, but for a .h
file. The fix was to go into the file Properties
(via Solution Explorer's file popup menu) and set the file type correctly. It was set to C/C++ Compiler
instead of the correct C/C++ header
.
Note that you could as well plot directly from ce
(after the comma removing) using the column name :
hist(ce$Weight)
(As opposed to using hist(ce[1])
, which would lead to the same "must be numeric" error.)
This also works for a database query result.
In your case it should be:
Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb
I found a nice solution on the blog of Lisa Wray. With the new data binding it is possible to set the font in your XML files.
@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}
In XML:
<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
It can be done much easier:
\S
which equals [^ \t\r\n\v\f]
It helps me:
pg_hba.conf
sudo nano /etc/postgresql/9.x/main/pg_hba.conf
and change this line:
Database administrative login by Unix domain socket
local all postgres md5
to
Database administrative login by Unix domain socket
local all postgres trust
Restart the server
sudo service postgresql restart
Login into psql and set password
psql -U postgres
ALTER USER postgres with password 'new password';
pg_hba.conf
and change this line: Database administrative login by Unix domain socket local all postgres trust
to
Database administrative login by Unix domain socket local all postgres md5
sudo service postgresql restart
You can use this configuration:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
In windows you should use %WORKSPACE%
.
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
It depends on what format you put on the datepicker So first we gave it the format.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want
Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )
//Datetimepicker
$(function () {
$('#datetimepicker1').datetimepicker({
minDate: today, //pass today's date
daysOfWeekDisabled: [0],
locale: 'es',
inline: true,
format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)
sideBySide: true
});
});
I'm not sure about your first code sample where you use WebClient.UploadValues, it's not really enough to go on, could you paste more of your surrounding code? Regarding your WebRequest code, there are two things at play here:
You're only requesting the headers of the response**, you never read the body of the response by opening and reading (to its end) the ResponseStream. Because of this, the WebRequest client helpfully leaves the connection open, expecting you to request the body at any moment. Until you either read the response body to completion (which will automatically close the stream for you), clean up and close the stream (or the WebRequest instance) or wait for the GC to do its thing, your connection will remain open.
You have a default maximum amount of active connections to the same host of 2. This means you use up your first two connections and then never dispose of them so your client isn't given the chance to complete the next request before it reaches its timeout (which is milliseconds, btw, so you've set it to 0.2 seconds - the default should be fine).
If you don't want the body of the response (or you've just uploaded or POSTed something and aren't expecting a response), simply close the stream, or the client, which will close the stream for you.
The easiest way to fix this is to make sure you use using blocks on disposable objects:
for (int i = 0; i < ops1; i++)
{
Uri myUri = new Uri(site);
WebRequest myWebRequest = WebRequest.Create(myUri);
//myWebRequest.Timeout = 200;
using (WebResponse myWebResponse = myWebRequest.GetResponse())
{
// Do what you want with myWebResponse.Headers.
} // Your response will be disposed of here
}
Another solution is to allow 200 concurrent connections to the same host. However, unless you're planning to multi-thread this operation so you'd need multiple, concurrent connections, this won't really help you:
ServicePointManager.DefaultConnectionLimit = 200;
When you're getting timeouts within code, the best thing to do is try to recreate that timeout outside of your code. If you can't, the problem probably lies with your code. I usually use cURL for that, or just a web browser if it's a simple GET request.
** In reality, you're actually requesting the first chunk of data from the response, which contains the HTTP headers, and also the start of the body. This is why it's possible to read HTTP header info (such as Content-Encoding, Set-Cookie etc) before reading from the output stream. As you read the stream, further data is retrieved from the server. WebRequest's connection to the server is kept open until you reach the end of this stream (effectively closing it as it's not seekable), manually close it yourself or it is disposed of. There's more about this here.
The Firefox developer tools now does this. Events are shown by clicking the "ev" button on the right of each element's display, including jQuery and DOM events.
New approach to old question. A solution that works from java 9+
ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));
is more readable and maintainable for complex objects. Ej
Map<String, Object> agencyMap = Map.of(
"name", "Agencia Prueba",
"phone1", "1198788373",
"address", "Larrea 45 e/ calligaris y paris",
"number", 267,
"enable", true,
"location", Map.of("id", 54),
"responsible", Set.of(Map.of("id", 405)),
"sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);
Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();
So, you want to treat your .properties
file on the same folder as the main/runnable jar as a file rather than as a resource of the main/runnable jar. In that case, my own solution is as follows:
First thing first: your program file architecture shall be like this (assuming your main program is main.jar and its main properties file is main.properties):
./ - the root of your program
|__ main.jar
|__ main.properties
With this architecture, you can modify any property in the main.properties file using any text editor before or while your main.jar is running (depending on the current state of the program) since it is just a text-based file. For example, your main.properties file may contain:
app.version=1.0.0.0
app.name=Hello
So, when you run your main program from its root/base folder, normally you will run it like this:
java -jar ./main.jar
or, straight away:
java -jar main.jar
In your main.jar, you need to create a few utility methods for every property found in your main.properties file; let say the app.version
property will have getAppVersion()
method as follows:
/**
* Gets the app.version property value from
* the ./main.properties file of the base folder
*
* @return app.version string
* @throws IOException
*/
import java.util.Properties;
public static String getAppVersion() throws IOException{
String versionString = null;
//to load application's properties, we use this class
Properties mainProperties = new Properties();
FileInputStream file;
//the base folder is ./, the root of the main.properties file
String path = "./main.properties";
//load the file handle for main.properties
file = new FileInputStream(path);
//load all the properties from this file
mainProperties.load(file);
//we have loaded the properties, so close the file handle
file.close();
//retrieve the property we are intrested, the app.version
versionString = mainProperties.getProperty("app.version");
return versionString;
}
In any part of the main program that needs the app.version
value, we call its method as follows:
String version = null;
try{
version = getAppVersion();
}
catch (IOException ioe){
ioe.printStackTrace();
}
When using GetAsync with the HttpClient you can add the authorization headers like so:
httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "Your Oauth token");
This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.
Here is an detailed SO answer
<md-input placeholder="Item name..." [(ngModel)]="name" (keyup)="filterResults()"></md-input>
<div *ngFor="let item of filteredValue">
{{item.name}}
</div>
filterResults() {
if (!this.name) {
this.filteredValue = [...this.items];
} else {
this.filteredValue = [];
this.filteredValue = this.items.filter((item) => {
return item.name.toUpperCase().indexOf(this.name.toUpperCase()) > -1;
});
}
}
Don't do any modification on 'items' array(list of items from which results are filtered). When searched item 'name' is empty return the complete list of 'items', if not compare the 'name' with every 'name' in the 'items ' array and filter out only the name that is present in 'items' array and store it in the 'filteredValue'.
A little bit of decorator treatment (very loosely inspired by the Maybe monad and lifting). You can safely remove Python 3.6 type annotations and use an older message formatting style.
fallible.py
from functools import wraps
from typing import Callable, TypeVar, Optional
import logging
A = TypeVar('A')
def fallible(*exceptions, logger=None) \
-> Callable[[Callable[..., A]], Callable[..., Optional[A]]]:
"""
:param exceptions: a list of exceptions to catch
:param logger: pass a custom logger; None means the default logger,
False disables logging altogether.
"""
def fwrap(f: Callable[..., A]) -> Callable[..., Optional[A]]:
@wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except exceptions:
message = f'called {f} with *args={args} and **kwargs={kwargs}'
if logger:
logger.exception(message)
if logger is None:
logging.exception(message)
return None
return wrapped
return fwrap
Demo:
In [1] from fallible import fallible
In [2]: @fallible(ArithmeticError)
...: def div(a, b):
...: return a / b
...:
...:
In [3]: div(1, 2)
Out[3]: 0.5
In [4]: res = div(1, 0)
ERROR:root:called <function div at 0x10d3c6ae8> with *args=(1, 0) and **kwargs={}
Traceback (most recent call last):
File "/Users/user/fallible.py", line 17, in wrapped
return f(*args, **kwargs)
File "<ipython-input-17-e056bd886b5c>", line 3, in div
return a / b
In [5]: repr(res)
'None'
You can also modify this solution to return something a bit more meaningful than None
from the except
part (or even make the solution generic, by specifying this return value in fallible
's arguments).
Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the width
of the image appears before the height
.
<html>
<head>
<style>
.container {
background: blue;
padding: 10px;
height: 100%;
max-height: 200px;
max-width: 300px;
}
.container img {
width: 100%;
height: 100%
}
</style>
</head>
<body>
<div class="container">
<img src="http://placekitten.com/400/500" />
</div>
</body>
</html>
If the label
immediately follows a specified input
element:
input#example + label { ... }
input:checked + label { ... }
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
if you are using angularjs you can write your own directive. I had the same problem whith bootstrapSwitch. I have to call
$("[name='my-checkbox']").bootstrapSwitch();
in javascript but my html input object was not created at that time. So I write an own directive and create the input element with
<input type="checkbox" checkbox-switch>
In the directive I compile the element to get access via javascript an execute the jquery command (like your .combobox()
command). Very important is to remove the attribute. Otherwise this directive will call itself and you have build a loop
app.directive("checkboxSwitch", function($compile) {
return {
link: function($scope, element) {
var input = element[0];
input.removeAttribute("checkbox-switch");
var inputCompiled = $compile(input)($scope.$parent);
inputCompiled.bootstrapSwitch();
}
}
});
You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.
Here is a rather ugly hack that adds to the SystemClassLoader at runtime:
import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
The reflection is necessary to access the protected method addURL
. This could fail if there is a SecurityManager.
Although git pull origin yourbranch
works, it's not really a good idea
You can alternatively do the following:
git fetch origin
git merge origin/yourbranch
The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.
The second line merges your current branch with that of yourbranch
that you fetched from origin
(which is one of your remotes
).
This is assuming origin
points to the repository at address ssh://11.21.3.12:23211/dir1/dir2
Take a look at this post on Java Ranch:
http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could
"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."
From Wikipedia:
Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).
So as others mentioned, it's a convention.
for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items
to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems
.
In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems'
error. Use items()
instead of iteritems()
here.
Refer to this post.
How about BOM, the magical character Microsoft adds to start of files (at least XML)?
This codifies @Sérgio and @unutbu's answers. It will "just work" with either a pytz.timezone
object or an IANA Time Zone string.
def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive."""
tz = dt.tzinfo or tz
try:
tz = pytz.timezone(tz)
except AttributeError:
pass
return tz.localize(dt, is_dst=is_dst)
This seems like what datetime.localize()
(or .inform()
or .awarify()
) should do, accept both strings and timezone objects for the tz argument and default to UTC if no time zone is specified.
Anaconda with Windows
After conda commands it's required to accept process - Proceed ([y]/n)?
It must be overridden. You could use:
<!-- Add a class name to override -->
<select name="funTimes" class="funTimes" size="5">
#elementId select.funTimes {
/* Override styles here */
}
Make sure you use !important
flag in css style e.g. margin-top: 0px !important
What does !important mean in CSS?
You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name
I am a git newbie as well. I had the same problem with 'your branch is ahead of origin/master by N commits' messages. Doing the suggested 'git diff origin/master' did show some diffs that I did not care to keep. So ...
Since my git clone was for hosting, and I wanted an exact copy of the master repo, and did not care to keep any local changes, I decided to save off my entire repo, and create a new one:
(on the hosting machine)
mv myrepo myrepo
git clone USER@MASTER_HOST:/REPO_DIR myrepo
For expediency, I used to make changes to the clone on my hosting machine. No more. I will make those changes to the master, git commit there, and do a git pull. Hopefully, this should keep my git clone on the hosting machine in complete sync.
/Nara
Use File.ReadAllText passing file location as an argument.
However, if your real goal is to parse html then I would recommend using Html Agility Pack.
Pythonic way to do this is ...
np.divide(data.T,vector).T
This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.
#NOTE: No of columns in both data and vector should match
You can achieve this using css flex properties. Please see the code below
.img-container {_x000D_
border: 2px solid red;_x000D_
justify-content: center;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
overflow: hidden;_x000D_
_x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
flex: 1;_x000D_
height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
<img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
Or in restSharp:
var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This can be done in three simple steps:
1) Add item id with url
tag:
{% for item in post %}
<tr>
<th>{{ item.id }}</th>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>
<a href={% url 'edit' id=item.id %}>Edit</a>
<a href={% url 'delete' id=item.id %}>Delete</a>
</td>
</tr>
{% endfor %}
2) Add path to urls.py:
path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')
3) Use the id on views.py:
def delete(request, id):
obj = post.objects.get(id=id)
obj.delete()
return redirect('dashboard')
If you are looking to serialize the inputs on an event. Here's a pure JavaScript approach I use.
// serialize form
var data = {};
var inputs = [].slice.call(e.target.getElementsByTagName('input'));
inputs.forEach(input => {
data[input.name] = input.value;
});
Data will be a JavaScript object of the inputs.
Came here for the solution, but could not understand much, posting my version;
const getLongestStr = (longestStr, str) => {
return longestStr.length > str.length ? longestStr : str;
}
var input = ['ali', 'Shahenshah', 'naqvi', 'hm'];
var longest = input.reduce(getLongestStr, "")
Cross apply can be used to replace subquery's where you need a column of the subquery
subquery
select * from person p where
p.companyId in(select c.companyId from company c where c.companyname like '%yyy%')
here i won't be able to select the columns of company table so, using cross apply
select P.*,T.CompanyName
from Person p
cross apply (
select *
from Company C
where p.companyid = c.companyId and c.CompanyName like '%yyy%'
) T
More simple way with es6 style.
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
//Examples:
var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
indexOfAll(cars, "Nano"); //[0, 3, 5]
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []
when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
For the Record:
Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
var objectA = {}
is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.
If you just want to check the value is in Range, use this:
MIN_VALUE = 1;
MAX_VALUE = 100;
$customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
@echo off
ver | find "6.1." > nul
if %ERRORLEVEL% == 0 (
echo Win7
for /f "delims=" %%a in ('DIR "C:\Program Files\Microsoft Office\*Outlook.EXE" /B /P /S') do call set findoutlook=%%a
%findoutlook%
)
ver | find "5.1." > nul
if %ERRORLEVEL% == 0 (
echo WinXP
for /f "delims=" %%a in ('DIR "C:\Program Files\Microsoft Office\*Outlook.EXE" /B /P /S') do call set findoutlook=%%a
%findoutlook%
)
echo Outlook dir: %findoutlook%
"%findoutlook%"
You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.
You can use a dynamic array when you don't know the number of values it will contain until run-time:
Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)
Or you could do everything with one statement if you're creating an array that's local to a procedure:
ReDim Zombies(NumberOfZombies) As Integer
Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.
You could use a constant if you knew the value of the variable was not going to change:
Const NumberOfZombies = 2000
but there's no way to cast between constants and variables. They have distinctly different meanings.
For fields where NULL
is acceptable, you could use var_export($var, true)
to output the string
, integer
, or NULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
If Ubuntu Docker image isn't recognizing 'ifconfig' inside of GNS3, you'll need to open Ubuntu docker image on your host.
Assuming you already have docker on your host pc and ubuntu pull'd from docker images. Enter these commands in your host OS (Linux, CentOS, etc.) CLI.
$docker images
$docker run -it ubuntu
$apt-get update
$apt-get install net-tools
(side note: you can add whatever other tools and services that you would like to add now, but for now this is just to get ifconfig to work.)
$exit
Now you will commit these changes to Docker. This link for committing changes is the best summary and works (skip to Step 4):
https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image#htoc-step-3-modify-the-container
When you re-open the docker image in GNS3 you should now have the ifconfig command usable and whatever other tools or services you added to the container.
Enjoy!
If you are like me, who has no formal computer science education, and is interested in building/want to know how a compiler works:
I am recommend "Programming Language Processors in Java: Compilers and Interpreters", an amazing book for a self-taught computer programmer.
From my point of view, understanding those basic language theory, automate machine, and set theory is not a big problem. The problem is how to turn those things into code. The above book tells you how to write a parser, analysis context, and generate code. If you can not understand this book, then I have to say, give up building a compiler. The book is best programming book I have ever read.
There is an other book, also good, Compiler Design in C. There is a lot of code, and it tells you everything about how to build a compiler and lexer tools.
Building a compiler is a fun programming practice and can teach you heaps of programming skills.
Do not buy the Dragon book. It was a waste of money and time and is not for a practitioner.
PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.
You can just loop though the items:
$("input[name^='card']").each(function() {
console.log($(this).val());
});
To ignore all subdirectories you can simply use:
**/
This works as of version 1.8.2 of git.
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
This is not an appropriate use of regular expressions. You'd be better off using
[0-9]{2}/[0-9]{2}/[0-9]{4}
and then checking ranges in a higher-level language.
Repeat for Multiple aggregations like:
SELECT sum(AMOUNT) AS TOTAL_AMOUNT FROM (
SELECT AMOUNT FROM table_1
UNION ALL
SELECT AMOUNT FROM table_2
UNION ALL
SELECT ASSURED_SUM FROM table_3
)
This is working for me:
this.listCopy = Object.assign([], this.list);
The correct answer to this question has been provided by user frm.adiputra, as currently this seems to be the only way to explicitly control the value attribute of the option elements.
However, I just wanted to emphasize that "select" is not a keyword in this context, but it is just a placeholder for an expression. Please refer to the following list, for the definition of the "select" expression as well as other expressions that can be used in ng-options directive.
The use of select as it is depicted in the question:
ng-options='select p.text for p in resultOptions'
is essentially wrong.
Based on the list of expressions, it seems that trackexpr may be used to specify the value, when options are given in an array of objects, but it has been used with grouping only.
From AngularJS' documentation for ng-options:
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
let's say you want a pointer to point at the address 0x28ff4402, the usual way is
uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want
So the short way is to use a MACRO,
#define ptr *(uint32_t *) (0x28ff4402)
for(int i=1;i<=5;i++)
{
for(int j=5;j>=i;j--)
{
System.out.print(" ");
}
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
for(int j=1;j<=i-1;j++)
{
System.out.print("*");
}
System.out.println("");
}
*
***
Focusing on the label didn't work for me, doing something like label1.Focus()
right?
the textbox still has focus when loading the form, however trying Velociraptors
answer, worked for me, setting the Form's Active control to the label like this:
private void Form1_Load(object sender, EventArgs e)
{
this.ActiveControl = label1;
}
Another option is to use jq
:
$ seq 10|jq -s add
55
-s
(--slurp
) reads the input lines into an array.
Two approaches:
When you login: you can to create a copy_my_files.bat
file into your All Programs > Startup
folder with this content (its a plain text document):
xcopy c:\folder\*.* d:\another_folder\.
Use xcopy c:\folder\*.* d:\another_folder\. /Y
to overwrite the file without any prompt.
Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher
Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:
<button onclick="myFunction()">Click me</button>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
function myFunction() {
localStorage.setItem('scrollpos', window.scrollY);
location.reload();
}
</script>
Personally I think it should be a failable initialiser:
extension Date {
init?(dateString: String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
if let d = dateStringFormatter.date(from: dateString) {
self.init(timeInterval: 0, since: d)
} else {
return nil
}
}
}
Otherwise a string with an invalid format will raise an exception.
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
A primary key is a column (or columns) in a table that uniquely identifies the rows in that table.
CUSTOMERS
CustomerNo FirstName LastName
1 Sally Thompson
2 Sally Henderson
3 Harry Henderson
4 Sandra Wellington
For example, in the table above, CustomerNo is the primary key.
The values placed in primary key columns must be unique for each row: no duplicates can be tolerated. In addition, nulls are not allowed in primary key columns.
So, having told you that it is possible to use one or more columns as a primary key, how do you decide which columns (and how many) to choose?
Well there are times when it is advisable or essential to use multiple columns. However, if you cannot see an immediate reason to use multiple columns, then use one. This isn't an absolute rule, it is simply advice. However, primary keys made up of single columns are generally easier to maintain and faster in operation. This means that if you query the database, you will usually get the answer back faster if the tables have single column primary keys.
Next question — which column should you pick? The easiest way to choose a column as a primary key (and a method that is reasonably commonly employed) is to get the database itself to automatically allocate a unique number to each row.
In a table of employees, clearly any column like FirstName is a poor choice since you cannot control employee's first names. Often there is only one choice for the primary key, as in the case above. However, if there is more than one, these can be described as 'candidate keys' — the name reflects that they are candidates for the responsible job of primary key.
Swift has a very clear, specific sequence of operations that are done in initializers. Let's start with some basic examples and work our way up to a general case.
Let's take an object A. We'll define it as follows.
class A {
var x: Int
init(x: Int) {
self.x = x
}
}
Notice that A does not have a superclass, so it cannot call a super.init() function as it does not exist.
OK, so now let's subclass A with a new class named B.
class B: A {
var y: Int
init(x: Int, y: Int) {
self.y = y
super.init(x: x)
}
}
This is a departure from Objective-C where [super init]
would typically be called first before anything else. Not so in Swift. You are responsible for ensuring that your instance variables are in a consistent state before you do anything else, including calling methods (which includes your superclass' initializer).
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
You can read the Name
from WindowsIdentity
:
var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return Ok(user);
In a multi-select option box, you can use $('#input1 :selected').length;
to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.
function refreshButtons () {
if ($('#input :selected').length == 0)
{
$('#submit').attr ('disabled', 'disabled');
}
else
{
$('#submit').removeAttr ('disabled');
}
}
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
As what has already mentioned by others, the save()
itself contains both create and update operation.
I just want to add supplement about what behind the save()
method.
Firstly, let's see the extend/implement hierarchy of the CrudRepository<T,ID>
,
Ok, let's check the save()
implementation at SimpleJpaRepository<T, ID>
,
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
As you can see, it will check whether the ID is existed or not firstly, if the entity is already there, only update will happen by merge(entity)
method and if else, a new record is inserted by persist(entity)
method.
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
As an extension to Andomar's answer, above, I had a scenario where the first 700,000,000 records (of ~1.2 billion) processed very quickly, with chunks of 25,000 records processing per second (roughly). But, then it starting taking 15 minutes to do a batch of 25,000. I reduced the chunk size down to 5,000 records and it went back to its previous speed. I'm not certain what internal threshold I hit, but the fix was to reduce the number of records, further, to regain the speed.
The solution is to do exactly what the exception message tells you:
Caused by: org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)
Remove the deleted object from an associations (sets, lists, or maps) that it is in. In particular, i suspect, from PlayList.PlaylistadMaps
. It's not enough to just delete the object, you have to remove it from any cascading collections which refer to it.
In fact, since your collection has orphanRemoval = true
, you don't need to delete it explicitly. You just need to remove it from the set.
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
I'm using
$("input:radio[name='html_radio']").is(":checked")
And will return FALSE if all the items in the radiogroup are unchecked and TRUE if an item is checked.
Actually composer nowadays seems to work without the zip
command line command, so installing php-zip
should be enough --- BUT it would display a warning:
As there is no 'unzip' command installed zip files are being unpacked using the PHP zip extension. This may cause invalid reports of corrupted archives. Installing 'unzip' may remediate them.
See also Is there a problem with using php-zip (composer warns about it)
updated 05/09/2014
OK. We have official document now. It talked all I have mentioned, in a better way.
Read more detailed here.
Yes, the main difference is surfaceView can be updated on the background thread. However, there are more you might care.
surfaceView has dedicate surface buffer while all the view shares one surface buffer that is allocated by ViewRoot. In another word, surfaceView cost more resources.
surfaceView cannot be hardware accelerated (as of JB4.2) while 95% operations on normal View are HW accelerated using openGL ES.
More work should be done to create your customized surfaceView. You need to listener to the surfaceCreated/Destroy Event, create an render thread, more importantly, synchronized the render thread and main thread. However, to customize the View, all you need to do is override onDraw
method.
view.invalidate
in the UI thread or view.postInvalid
in other thread to indicate to the framework that the view should be updated. However, the view won't be updated immediately but wait until next VSYNC event arrived. The easy approach to understand VSYNC is to consider it is as a timer that fire up every 16ms for a 60fps screen. In Android, all the normal view update (and display actually but I won't talk it today), is synchronized with VSYNC to achieve better smoothness. Now,back to the surfaceView, you can render it anytime as you wish. However, I can hardly tell if it is an advantage, since the display is also synchronized with VSYNC, as stated previously.There's no such thing as "local package". The organization of packages on a disk is orthogonal to any parent/child relations of packages. The only real hierarchy formed by packages is the dependency tree, which in the general case does not reflect the directory tree.
Just use
import "myproject/packageN"
and don't fight the build system for no good reason. Saving a dozen of characters per import in any non trivial program is not a good reason, because, for example, projects with relative import paths are not go-gettable.
The concept of import paths have some important properties:
All of the above is ruined by using relative import paths. Do not do it.
PS: There are few places in the legacy code in Go compiler tests which use relative imports. ATM, this is the only reason why relative imports are supported at all.
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
Just use CSS transitions:
$(element).css( { transition: "transform 0.5s",
transform: "rotate(" + amount + "deg)" } );
setTimeout( function() { $(element).css( { transition: "none" } ) }, 500 );
As example I set the duration of the animation to 0.5 seconds.
Note the setTimeout
to remove the transition
css property after the animation is over (500 ms)
For readability I omitted vendor prefixes.
This solution requires browser's transition support off course.
Actually, if you don't know if the subfolders have a git repo or not, the best would be to let find
get the repos for you:
find . -type d -name .git -exec git --git-dir={} --work-tree=$PWD/{}/.. pull origin master \;
The PowerShell equivalent would be:
Get-ChildItem -Recurse -Directory -Hidden -Filter .git | ForEach-Object { & git --git-dir="$($_.FullName)" --work-tree="$(Split-Path $_.FullName -Parent)" pull origin master }
I created a simple Objective C wrapper around the good old C array to be used more conveniently: https://gist.github.com/4705733
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));
outputs:
1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875
Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).
More about double precision:
You can get window from injected document.
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
export class MyClass {
constructor(@Inject(DOCUMENT) private document: Document) {
this.window = this.document.defaultView;
}
check() {
console.log(this.document);
console.log(this.window);
}
}
The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).
The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.
So what was missing was:
Response.End();
See also: Trying to stream a PDF file with asp.net is producing a "damaged file"
The wb
indicates that the file is opened for writing in binary mode.
When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b
is excluded as in just w
or when you specify text mode with wt
), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n
) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe
or png
file.
Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.
References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open
You can use python, to simplify things (works on all Windows versions and all other platforms):
import platform
print(platform.system()) # returns 'Windows', 'Linux' etc.
print(platform.release()) # returns for Windows 10 or Server 2019 '10'
if platform.system() = 'Windows':
print(platform.win32_ver()) # returns (10, 10.0.17744, SP0, Multiprocessor Free) on windows server 2019
First of all, two things that we need to understand,
bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
here mServiceConn
is instance of ServiceConnection
class(inbuilt) it is actually interface
that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.
IBinder
Object. So, IBinder
object is our handler which accesses all the methods of Service
by using (.) operator. .
MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d("ServiceConnection","connected");
myService = binder;
}
//binder comes from server to communicate with method's of
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
}
myservice.serviceMethod();
Here myService
is object and serviceMethod is method in service.
and by this way communication is established between client and server.
This code work for me:
BufferedImage image = null;
try {
URL file = getClass().getResource("water.bmp");
image = ImageIO.read(file);
} catch (IOException ioex) {
System.err.println("load error: " + ioex.getMessage());
}
ImageIcon icon = new ImageIcon(image);
JButton quitButton = new JButton(icon);
Private Function GetIPv4Address() As String
GetIPv4Address = String.Empty
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
For Each ipheal As System.Net.IPAddress In iphe.AddressList
If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
GetIPv4Address = ipheal.ToString()
End If
Next
End Function
Huffman coding generally works okay for this.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
Or Using promises:
const AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: 'accessKeyId',
secretAccessKey: 'secretAccessKey',
region: 'region'
});
let params = {
Bucket: "yourBucketName",
Key: 'someUniqueKey',
Body: 'someFile'
};
try {
let uploadPromise = await new AWS.S3().putObject(params).promise();
console.log("Successfully uploaded data to bucket");
} catch (e) {
console.log("Error uploading data: ", e);
}
I believe that was already answered here.
String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
OR
int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
Of course! Just use the ALTER TABLE...
syntax.
Example
ALTER TABLE YourTable
ADD Foo INT NULL /*Adds a new int column existing rows will be
given a NULL value for the new column*/
Or
ALTER TABLE YourTable
ADD Bar INT NOT NULL DEFAULT(0) /*Adds a new int column existing rows will
be given the value zero*/
In SQL Server 2008 the first one is a metadata only change. The second will update all rows.
In SQL Server 2012+ Enterprise edition the second one is a metadata only change too.
If we are creating too many projects using Android Studio sometime Rendering issue comes. Even creating a blank activity we receive such rendering error. Please shut down and restart Android studio. In case the issue persists you can
Hope this helps. It works similar fashion as rule of thumb, in case all looks good and still error persists a restart of application usually resolves the issue.
The reason, is, because you did not specify the width of the table, and your whole bunch of td's are overflowing.
This for example, i've given the table a width of 5000px, which I thought would fit your requirements.
table{
width:5000px;
}
It is the exact same code you provided, which I merely added in the table width.
I believe what is happening, is because your TD's are way past the default table width. Which you could see, if you pull out about 45 of your td's in each tr, (i.e. the code you provided in your question, not jsfiddle) it works exactly fine
Java 8 introduced default implementation of forEach() inside the Iterable interface , you can easily do it by declarative approach .
List<String> values = Arrays.asList("Yasir","Shabbir","Choudhary");
values.forEach( value -> System.out.println(value));
Here is the code of Iterable interface
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
In Java 8 you can skip server name checking with the following code:
HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);
However this should be used only in development!
Link to the PyYAML documentation showing the difference for the default_flow_style
parameter.
To write it to a file in block mode (often more readable):
d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
yaml.dump(d, yaml_file, default_flow_style=False)
produces:
A: a
B:
C: c
D: d
E: e
For years, I have used JExcel for this, an excellent open-source Java project. It was also .NET-able by using J# to compile it, and I have also had great success with it in this incarnation. However, recently I needed to migrate the code to native .NET to support a 64-bit IIS application in which I create Excel output. The 32-bit J# version would not load.
The code for CSharpJExcel is LGPL and is available currently at this page, while we prepare to deploy it on the JExcel SourceForge site. It will compile with VS2005 or VS2008. The examples in the original JExcel documentation will pretty well move over intact to the .NET version.
Hope it is helpful to someone out here.
Just my two cents, Silas Ray is on the right track, however I felt like adding an example. ;-)
Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person.
Per PEP 8:
Use one leading underscore only for non-public methods and instance variables.
To have a 'read-only' property in a class you can make use of the @property
decoration, you'll need to inherit from object
when you do so to make use of the new-style classes.
Example:
>>> class A(object):
... def __init__(self, a):
... self._a = a
...
... @property
... def a(self):
... return self._a
...
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
SELECT * FROM table WHERE arr && '{s}'::text[];
Compare two arrays for containment.