// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
/**
* Sanitize HTML
*/
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
/**
* Pipe Constructor
*
* @param _sanitizer: DomSanitezer
*/
// tslint:disable-next-line
constructor(protected _sanitizer: DomSanitizer) {
}
/**
* Transform
*
* @param value: string
* @param type: string
*/
transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
}
{{ data.url | safe:'url' }}
// Public properties
itsSafe: SafeHtml;
// Private properties
private safePipe: SafePipe = new SafePipe(this.domSanitizer);
/**
* Component constructor
*
* @param safePipe: SafeHtml
* @param domSanitizer: DomSanitizer
*/
constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
}
/**
* On init
*/
ngOnInit(): void {
this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
}
The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.
These may be a bit heavy, but they're flexible enough to sanitize whatever string into a "safe" en
style filename or folder name (or heck, even scrubbed slugs and things if you bend it).
1) Building a full filename (with fallback name in case input is totally truncated):
str_file($raw_string, $word_separator, $file_extension, $fallback_name, $length);
2) Or using just the filter util without building a full filename (strict mode true
will not allow [] or () in filename):
str_file_filter($string, $separator, $strict, $length);
3) And here are those functions:
// Returns filesystem-safe string after cleaning, filtering, and trimming input
function str_file_filter(
$str,
$sep = '_',
$strict = false,
$trim = 248) {
$str = strip_tags(htmlspecialchars_decode(strtolower($str))); // lowercase -> decode -> strip tags
$str = str_replace("%20", ' ', $str); // convert rogue %20s into spaces
$str = preg_replace("/%[a-z0-9]{1,2}/i", '', $str); // remove hexy things
$str = str_replace(" ", ' ', $str); // convert all nbsp into space
$str = preg_replace("/&#?[a-z0-9]{2,8};/i", '', $str); // remove the other non-tag things
$str = preg_replace("/\s+/", $sep, $str); // filter multiple spaces
$str = preg_replace("/\.+/", '.', $str); // filter multiple periods
$str = preg_replace("/^\.+/", '', $str); // trim leading period
if ($strict) {
$str = preg_replace("/([^\w\d\\" . $sep . ".])/", '', $str); // only allow words and digits
} else {
$str = preg_replace("/([^\w\d\\" . $sep . "\[\]\(\).])/", '', $str); // allow words, digits, [], and ()
}
$str = preg_replace("/\\" . $sep . "+/", $sep, $str); // filter multiple separators
$str = substr($str, 0, $trim); // trim filename to desired length, note 255 char limit on windows
return $str;
}
// Returns full file name including fallback and extension
function str_file(
$str,
$sep = '_',
$ext = '',
$default = '',
$trim = 248) {
// Run $str and/or $ext through filters to clean up strings
$str = str_file_filter($str, $sep);
$ext = '.' . str_file_filter($ext, '', true);
// Default file name in case all chars are trimmed from $str, then ensure there is an id at tail
if (empty($str) && empty($default)) {
$str = 'no_name__' . date('Y-m-d_H-m_A') . '__' . uniqid();
} elseif (empty($str)) {
$str = $default;
}
// Return completed string
if (!empty($ext)) {
return $str . $ext;
} else {
return $str;
}
}
So let's say some user input is: .....<div></div><script></script>& Weiß Göbel ?????File name %20 %20 %21 %2C Décor \/. /. . z \... y \...... x ./ “This name” is & 462^^ not = that grrrreat -][09]()1234747) ???????-??-????????????
And we wanna convert it to something friendlier to make a tar.gz with a file name length of 255 chars. Here is an example use. Note: this example includes a malformed tar.gz extension as a proof of concept, you should still filter the ext after string is built against your whitelist(s).
$raw_str = '.....<div></div><script></script>& Weiß Göbel ?????File name %20 %20 %21 %2C Décor \/. /. . z \... y \...... x ./ “This name” is & 462^^ not = that grrrreat -][09]()1234747) ???????-??-????????????';
$fallback_str = 'generated_' . date('Y-m-d_H-m_A');
$bad_extension = '....t&+++a()r.gz[]';
echo str_file($raw_str, '_', $bad_extension, $fallback_str);
The output would be: _wei_gbel_file_name_dcor_._._._z_._y_._x_._this_name_is_462_not_that_grrrreat_][09]()1234747)_.tar.gz
You can play with it here: https://3v4l.org/iSgi8
Or a Gist: https://gist.github.com/dhaupin/b109d3a8464239b7754a
EDIT: updated script filter for
instead of space, updated 3v4l link
To access helpers from your own controllers, just use:
OrdersController.helpers.order_number(@order)
I just had this problem too. Apparently I had set the JRE to 1.5 instead of 1.6 in my build path.
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).
The reason I wanted that version in particular is because that's what ships with MVC currently.
Here's the code:
$(document).ready(function() {
$("#topBar").css("position", "absolute");
});
$(window).scroll(function() {
$("#topBar").css("top", $(window).scrollTop() + "px");
});
DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
// code
}
If it is a typed DataSet:
MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
// code
}
Go to the folder platform-tools
in cmd
folder platform tools available in the Android folder where you have Android backup files.
Type the following
adb kill-server
and
adb start-server
then type
adb devices
adb kill-server
You can now see your device.
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.
With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
whenever you facing this type of error simply change the Release version just like In my case it is showing Error in 2.2.7 I changed to 2.2.6
Problem:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
Solution:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
var x;
if (x === undefined) {
alert ("I am declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("I am not even declared.")
};
/* One more thing to understand: typeof ==='undefined' also checks
for if a variable is declared, but no value is assigned. In other
words, the variable is declared, but not defined. */
// Will repeat above logic of x for typeof === 'undefined'
if (x === undefined) {
alert ("I am declared, but not defined.")
};
/* So typeof === 'undefined' works for both, but x === undefined
only works for a variable which is at least declared. */
/* Say if I try using typeof === undefined (not in quotes) for
a variable which is not even declared, we will get run a
time error. */
if (z === undefined) {
alert ("I am neither declared nor defined.")
};
// I got this error for z ReferenceError: z is not defined
You can get your heap memory size through below programe.
public class GetHeapSize {
public static void main(String[] args) {
long heapsize = Runtime.getRuntime().totalMemory();
System.out.println("heapsize is :: " + heapsize);
}
}
then accordingly you can increase heap size also by using: java -Xmx2g http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html
A simple solution is – just to ignore user interactions :-)
video {
pointer-events: none;
}
Let's illustrate what's happening here:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults
.
As other posters have pointed out, you probably want to use None
as a sentinel value and give each instance it's own list.
<div class="example" align="center">
<div class="menuholder">
<ul class="menu slide">
<li><a href="index.php?id=1" class="blue">Home</a></li>
<li><a href="index.php?id=14" class="blue">About Us</a></li>
<li><a href="index.php?id=4" class="blue">Mens</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=15">Coats & Jackets</a></dd>
<dd><a href="index.php?id=22">Chinos</a></dd>
<dd><a href="index.php?id=23">Jeans</a></dd>
<dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=25">Linen</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=26">Polo Shirts</a></dd>
<dd><a href="index.php?id=16">Shirts Casual</a></dd>
<dd><a href="index.php?id=27">Shirts Formal</a></dd>
<dd><a href="index.php?id=28">Shorts</a></dd>
<dd><a href="index.php?id=18">Sportswear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=20">Trousers Casual</a></dd>
<dd><a href="index.php?id=29">Trousers Formal</a></dd>
<dd><a href="index.php?id=30">Nightwear</a></dd>
<dd><a href="index.php?id=17">Socks</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=21">Underwear</a></dd>
<dd><a href="index.php?id=31">Swimwear</a></dd>
</dl>
</div>
</li>
<!--menu-->
<li><a href="index.php?id=5" class="blue">Ladie's</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=32">Coats & Jackets</a></dd>
<dd><a href="index.php?id=33">Dresses</a></dd>
<dd><a href="index.php?id=34">Jeans</a></dd>
<dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=36">Jumpsuits</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
<dd><a href="index.php?id=38">Linen</a></dd>
<dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
<dd><a href="index.php?id=40">Maternity Wear</a></dd>
<dd><a href="index.php?id=41">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=42">Shorts</a></dd>
<dd><a href="index.php?id=43">Skirts</a></dd>
<dd><a href="index.php?id=44">Sportswear</a></dd>
<dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
<dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=47">Thermals</a></dd>
<dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
<dd><a href="index.php?id=50">Socks</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=7" class="blue">Girls</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=51">Coats & Jackets</a></dd>
<dd><a href="index.php?id=52">Dresses</a></dd>
<dd><a href="index.php?id=53">Jeans</a></dd>
<dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
<dd><a href="index.php?id=57">Leggings</a></dd>
<dd><a href="index.php?id=58">Nightwear</a></dd>
<dd><a href="index.php?id=59">Shorts</a></dd>
<dd><a href="index.php?id=60">Skirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=61">Swimwear</a></dd>
<dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=64">Socks</a></dd>
<dd><a href="index.php?id=65">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=8" class="blue">Boys</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=66">Coats & Jackets</a></dd>
<dd><a href="index.php?id=67">Jeans</a></dd>
<dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=70">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=71">Shirts</a></dd>
<dd><a href="index.php?id=72">Shorts</a></dd>
<dd><a href="index.php?id=73">Sportswear</a></dd>
<dd><a href="index.php?id=74">Swimwear</a></dd>
<dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=77">Socks</a></dd>
<dd><a href="index.php?id=78">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=9" class="blue">Toddlers</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=79">Newborn</a></dd>
<dd><a href="index.php?id=80">0-2 Years</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=10" class="blue">Accessories</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=81">Shoes</a></dd>
<dd><a href="index.php?id=82">Ties</a></dd>
<dd><a href="index.php?id=83">Caps</a></dd>
<dd><a href="index.php?id=84">Belts</a></dd>
</dl>
</div>
</li><!--menu end-->
<li><a href="index.php?id=13" class="blue">Contact Us</a></li>
</ul>
<div class="back"></div>
<div class="shadow"></div>
</div>
<div style="clear:both"></div>
</div>
CSS 3 Coding- Copy and Paste
<style>
body{margin:0px;}
.example {
width:980px;
height:40px;
margin:0px auto;
position:absolute;
margin-bottom:60px;
top:95px;
}
.menuholder {
float:left;
font:normal bold 11px/35px verdana, sans-serif;
overflow:hidden;
position:relative;
}
.menuholder .shadow {
-moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
background:#888;
box-shadow:0 0 20px rgba(0, 0, 0, 1);
height:10px;
left:5%;
position:absolute;
top:-9px;
width:100%;
z-index:100;
}
.menuholder .back {
-moz-transition-duration:.4s;
-o-transition-duration:.4s;
-webkit-transition-duration:.4s;
background-color:rgba(0, 0, 0, 0.88);
height:0;
width:980px; /*100%*/
}
.menuholder:hover div.back {
height:280px;
}
ul.menu {
display:block;
float:left;
list-style:none;
margin:0;
padding:0 125px;
position:relative;
}
ul.menu li {
float:left;
margin:0 10px 0 0;
}
ul.menu li > a {
-moz-border-radius:0 0 10px 10px;
-moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-moz-transition:all 0.3s ease-in-out;
-o-border-radius:0 0 10px 10px;
-o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-o-transition:all 0.3s ease-in-out;
-webkit-border-bottom-left-radius:10px;
-webkit-border-bottom-right-radius:10px;
-webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-webkit-transition:all 0.3s ease-in-out;
border-radius:0 0 10px 10px;
box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
color:#eee;
display:block;
padding:0 10px;
text-decoration:none;
transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
background:#a00;
}
ul.menu li a.orange {
background:#da0;
}
ul.menu li a.yellow {
background:#aa0;
}
ul.menu li a.green {
background:#060;
}
ul.menu li a.blue {
background:#073263;
}
ul.menu li a.violet {
background:#682bc2;
}
.menu li div.subs {
left:0;
overflow:hidden;
position:absolute;
top:35px;
width:0;
}
.menu li div.subs dl {
-moz-transition-duration:.2s;
-o-transition-duration:.2s;
-webkit-transition-duration:.2s;
float:left;
margin:0 130px 0 0;
overflow:hidden;
padding:40px 0 5% 2%;
width:0;
}
.menu dt {
color:#fc0;
font-family:arial, sans-serif;
font-size:12px;
font-weight:700;
height:20px;
line-height:20px;
margin:0;
padding:0 0 0 10px;
white-space:nowrap;
}
.menu dd {
margin:0;
padding:0;
text-align:left;
}
.menu dd a {
background:transparent;
color:#fff;
font-size:12px;
height:20px;
line-height:20px;
padding:0 0 0 10px;
text-align:left;
white-space:nowrap;
width:80px;
}
.menu dd a:hover {
color:#fc0;
}
.menu li:hover div.subs dl {
-moz-transition-delay:0.2s;
-o-transition-delay:0.2s;
-webkit-transition-delay:0.2s;
margin-right:2%;
width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
background:#aaa;
color:#fff;
padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
width:100%;
}
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
use [\\W+]
or "[^a-zA-Z0-9]"
as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.
String c= "hjdg$h&jk8^i0ssh6";
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find())
{
String s= match.group();
c=c.replaceAll("\\"+s, "");
}
System.out.println(c);
Beautiful soup does convert html entities. It's probably your best bet considering HTML is often buggy and filled with unicode and html encoding issues. This is the code I use to convert html to raw text:
import BeautifulSoup
def getsoup(data, to_unicode=False):
data = data.replace(" ", " ")
# Fixes for bad markup I've seen in the wild. Remove if not applicable.
masssage_bad_comments = [
(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1)),
(re.compile('<!WWWAnswer T[=\w\d\s]*>'), lambda match: '<!--' + match.group(0) + '-->'),
]
myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(masssage_bad_comments)
return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage,
convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES
if to_unicode else None)
remove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else ""
Best way is
Add permission manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then you can get GPS location or if GPS location is not available then this function return NETWORK location
public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
assert lm != null;
isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location networkLoacation = null, gpsLocation = null, finalLoc = null;
if (isGpsEnabled)
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkLocationEnabled)
networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null && networkLoacation != null) {
//smaller the number more accurate result will
if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
return finalLoc = networkLoacation;
else
return finalLoc = gpsLocation;
} else {
if (gpsLocation != null) {
return finalLoc = gpsLocation;
} else if (networkLoacation != null) {
return finalLoc = networkLoacation;
}
}
return finalLoc;
}
Don't forget TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
or
{Binding RelativeSource={RelativeSource TemplatedParent}}
You may also use all() method to get array of selected attributes.
$test=test::select('id')->where('id' ,'>' ,0)->all();
Regards
Yes, your device can simultaneously connect to 7 other Bluetooth devices at the same time, in theory. Such a connection is called a piconet. A more complex connection pattern is the scatternet.
The reason it is limited to 7 other devices is because the assigned bit field for LT_ADDR in L2CAP protocol is only 3.
Also, don't forget to escape variables if you want to pick them up from the destination host.
This has caught me out in the past.
For example:
user@host> ssh user2@host2 "echo \$HOME"
prints out /home/user2
while
user@host> ssh user2@host2 "echo $HOME"
prints out /home/user
Another example:
user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"
prints out "hello" correctly.
You may attach the dialog to the form, so all those inputs are in a form. The other thing is make the password text field right after the username text field.
Indeed, there is no defined standard. To support that information, have a look at wikipedia, in the Query String chapter. There is the following comment:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field.[3][4]
Furthermore, when you take a look at the RFC 3986, in section 3.4 Query, there is no definition for parameters with multiple values.
Most applications use the first option you have shown: http://server/action?id=a&id=b
. To support that information, take a look at this Stackoverflow link, and this MSDN link regarding ASP.NET applications, which use the same standard for parameters with multiple values.
However, since you are developing the APIs, I suggest you to do what is the easiest for you, since the caller of the API will not have much trouble creating the query string.
A slight modification to derekerdmann's post to meet the original request using regex's alternation operator "|"(pipe).
It's also slightly easier for regex newbies to understand and read.
Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").
Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.
switch -regex ($someString) #many have noted ToLower() here is redundant
{
#processing user input
"^(y|yes|indubitably)$" { "You entered Yes." }
# not processing user input
"y|yes|indubitably" { "Yes was the selected string" }
default { "You entered No." }
}
The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).
You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.
There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField
.
You should read up on how to ensure that you've implemented equals and hashCode properly. This is a good starting point: What issues should be considered when overriding equals and hashCode in Java?
If the individual child items have an explicit width (eg. 32%), you can solve this by adding an :after element to the parent and giving this the same explicit width.
As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.
There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).
However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo();
you must have an int foo;
field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.
please have look at compressImage method i have used for compressing image.
public static String compressImage(String imageUri, Activity activity) {
String filename = "";
try {
String filePath = getRealPathFromURI(imageUri, activity);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas;
if (scaledBitmap != null) {
canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
}
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
if (scaledBitmap != null) {
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
}
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out;
filename = getFilename(activity);
try {
out = new FileOutputStream(filename);
if (scaledBitmap != null) {
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
private static String getRealPathFromURI(String contentURI, Activity activity) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = activity.getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
Just run your console and type:
db.version()
https://docs.mongodb.com/manual/reference/method/db.version/
When it comes to implement a search functionality there are two suggested approach by official Android Developer Documentation.
You can either use a SearchDialog or a SearchWidget.
I am going to explain the implementation of Search functionality using SearchWidget.
I will explain search functionality in a RecyclerView using SearchWidget. It's pretty straightforward.
Just follow these 5 Simple steps
You can add SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
You should initialize SearchView in the onCreateOptionsMenu(Menu menu)
method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
OnQueryTextListener
has two abstract methods
onQueryTextSubmit(String query)
onQueryTextChange(String newText
So your Activity skeleton would look like this
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
You can provide the implementation for the abstract methods like this
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
Most important part. You can write your own logic to perform search.
Here is mine. This snippet shows the list of Name which contains the text typed in the SearchView
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code on SearchView with an SQLite database in this Music App
I'm guessing your using mod_proxy_http (or proxy balancer).
Look in your tomcat logs (localhost.log, or catalina.log) I suspect your seeing an exception in your web stack bubbling up and closing the socket that the tomcat worker is connected to.
you can use following code for re-enable mouse right click.
document.oncontextmenu = function(){}
and you can use shortcut key (Ctrl+Shift+i) to open inspect elements in chrome in windows OS.
JonH has covered very well the part on how to write the query. There is another significant issue that must be mentioned too, however, which is the performance characteristics of such a query. Let's repeat it here (adapted to Oracle):
SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(EmployeeName) > 4;
This query is restricting the result of a function applied to a column value (the result of applying the LENGTH
function to the EmployeeName
column). In Oracle, and probably in all other RDBMSs, this means that a regular index on EmployeeName will be useless to answer this query; the database will do a full table scan, which can be really costly.
However, various databases offer a function indexes feature that is designed to speed up queries like this. For example, in Oracle, you can create an index like this:
CREATE INDEX EmployeeTable_EmployeeName_Length ON EmployeeTable(LENGTH(EmployeeName));
This might still not help in your case, however, because the index might not be very selective for your condition. By this I mean the following: you're asking for rows where the name's length is more than 4. Let's assume that 80% of the employee names in that table are longer than 4. Well, then the database is likely going to conclude (correctly) that it's not worth using the index, because it's probably going to have to read most of the blocks in the table anyway.
However, if you changed the query to say LENGTH(EmployeeName) <= 4
, or LENGTH(EmployeeName) > 35
, assuming that very few employees have names with fewer than 5 character or more than 35, then the index would get picked and improve performance.
Anyway, in short: beware of the performance characteristics of queries like the one you're trying to write.
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
Check if in the app store under xcode it says GET instead of installed, delete your current version and get the new one
Assume that the source file you want to compile is main.cpp and your example_dll.dll and example_dll.lib . now run cl.exe main.cpp /EHsc /link example_dll.lib
now you may get main.exe
There are a lot of ways to do this. Below is a few simple steps:
Suppose you have one Map like:
Map<String, Integer> m = new HashMap<String, Integer>();
Then you can do something like the below to iterate over map elements.
// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
Entry<String, Integer> pair = me.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}
// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
System.out.println(me.getKey() + " : " + me.getValue());
}
// *********** Using keySet *****************************
for(String s : m.keySet()){
System.out.println(s + " : " + m.get(s));
}
// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
String key = me.next();
System.out.println(key + " : " + m.get(key));
}
If you have the authority to edit the pages to be opened, you can href to 'A' page and in the A page you can put link to B page in onpageload attribute of body tag.
Replace the vendor id of 0bb4
with 18d1
in /etc/udev/rules.d/51-android.rules
Or add another line that reads:
SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"
As reported by Aziz Alto filter(None, lstr)
does not remove empty strings with a space ' '
but if you are sure lstr contains only string you can use filter(str.strip, lstr)
>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']
>>> ' '.join(lstr).split()
['hello', 'world']
>>> filter(str.strip, lstr)
['hello', 'world']
Compare time on my pc
>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.356455087661743
>>> timeit('filter(str.strip, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
5.276503801345825
The fastest solution to remove ''
and empty strings with a space ' '
remains ' '.join(lstr).split()
.
As reported in a comment the situation is different if your strings contain spaces.
>>> lstr = ['hello', '', ' ', 'world', ' ', 'see you']
>>> lstr
['hello', '', ' ', 'world', ' ', 'see you']
>>> ' '.join(lstr).split()
['hello', 'world', 'see', 'you']
>>> filter(str.strip, lstr)
['hello', 'world', 'see you']
You can see that filter(str.strip, lstr)
preserve strings with spaces on it but ' '.join(lstr).split()
will split this strings.
You would never want to run that, but you may want to source it.
. ~/.bash_profile
source ~/.bash_profile
both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
in html:
<div [ngClass]="{'disabled-field': !show}" *ngFor="let thing of stuff">
{{thing.name}}
</div>
in css:
.disabled-field {
pointer-events: none;
display: none;
}
A good alternative which is easy to use is DBPool.
"A Java-based database connection pooling utility, supporting time-based expiry, statement caching, connection validation, and easy configuration using a pool manager."
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
Like this
DECLARE @date DATETIME
SET @date = '2011-09-28 18:01:00'
select convert(varchar, @date,105) + ' ' + convert(varchar, @date,108)
Lose the contentType: "application/json; charset=utf-8",
. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).
That should make what you have work.
Thing is, you don't need to use JSON.stringify
or json_decode
here at all. Just do:
data: {myData:postData},
Then in PHP:
$obj = $_POST['myData'];
I created an online tool to do this. Simply paste any dependency in pom file format, and the dependency tree for that artifact is generated, based on the central maven repository.
Use this code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open !");
conn.Close();
import requests and try this simple python code.
def check_internet():
url = 'http://www.google.com/'
timeout = 5
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError:
return False
Here is how its done in Angular 6
<li *ngFor="let user of userObservable ; first as isFirst">
<span *ngIf="isFirst">default</span>
</li>
Note the change from let first = first
to first as isFirst
Pure string operations :):
>>> url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "stackoverflow.com/questions/9626535/get-domain-name-from-url"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'stackoverflow.com'
>>> url = "http://foo.bar?haha/whatever"
>>> url.split("//")[-1].split("/")[0].split('?')[0]
'foo.bar'
That's all, folks.
I've recently found a very succinct update to this which automatically raises meaningful error messages and prevents access via __dict__
:
class CONST(object):
__slots__ = ()
FOO = 1234
CONST = CONST()
# ----------
print(CONST.FOO) # 1234
CONST.FOO = 4321 # AttributeError: 'CONST' object attribute 'FOO' is read-only
CONST.__dict__['FOO'] = 4321 # AttributeError: 'CONST' object has no attribute '__dict__'
CONST.BAR = 5678 # AttributeError: 'CONST' object has no attribute 'BAR'
We define over ourselves as to make ourselves an instance and then use slots to ensure that no additional attributes can be added. This also removes the __dict__
access route. Of course, the whole object can still be redefined.
Edit - Original solution
I'm probably missing a trick here, but this seems to work for me:
class CONST(object):
FOO = 1234
def __setattr__(self, *_):
pass
CONST = CONST()
#----------
print CONST.FOO # 1234
CONST.FOO = 4321
CONST.BAR = 5678
print CONST.FOO # Still 1234!
print CONST.BAR # Oops AttributeError
Creating the instance allows the magic __setattr__
method to kick in and intercept attempts to set the FOO
variable. You could throw an exception here if you wanted to. Instantiating the instance over the class name prevents access directly via the class.
It's a total pain for one value, but you could attach lots to your CONST
object. Having an upper class, class name also seems a bit grotty, but I think it's quite succinct overall.
Just a hint: zip codes are not worldwide unique so this is worth to provide country ISO code in the request (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).
e.g looking for coordinates of polish (iso code PL
) zipcode 01-210
:
https://maps.googleapis.com/maps/api/geocode/json?address=01210,PL
how to obtain user country code?
if you would like to get your user country info based on IP address there are services for it, e.g you can do GET request on: http://ip-api.com/json
This is not possible. If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ).
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
<g>_x000D_
<rect x="0" y="0" width="100" height="100" fill="red"></rect>_x000D_
<text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>_x000D_
</g>_x000D_
</svg>
_x000D_
Office 2007
Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.
It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];
Filtered in this case contains the dictionary.
(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)
On windows 7 I used the general 'Uninstall Node.js' (just started typing in the search bottom left ,main menu field) followed by clicking the link to the older version which complies with the project, for instance: Windows 64-bit Installer: https://nodejs.org/dist/v4.4.6/node-v4.4.6-x64.msi
Just use --repo
option for git push command. Like this:
$ git push --repo https://name:[email protected]/name/repo.git
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}
The short answer: the setting needs to be setup when the connection to the MySQL server is established. For example, if using MYSQLi / PHP, it will look something like this:
$ myConn = mysqli_init();
$ myConn->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
Therefore, if you are using a home-brewed framework, well, you need to look for the place in the code when the connection is establish and provide a sensible value.
I am still using Codeigniter 3 on 2020, so in this framework, the code to add is in the application/system/database/drivers/mysqli/mysqli_driver.php, the function is named db_connect();
public function db_connect($persistent = FALSE)
{
// Do we have a socket path?
if ($this->hostname[0] === '/')
{
$hostname = NULL;
$port = NULL;
$socket = $this->hostname;
}
else
{
$hostname = ($persistent === TRUE)
? 'p:'.$this->hostname : $this->hostname;
$port = empty($this->port) ? NULL : $this->port;
$socket = NULL;
}
$client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
$this->_mysqli = mysqli_init();
$this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
$this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
...
}
The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.
As you need to see the result for testing purpose. The simple and elegant solution is the below code.
echo "<pre>";
print_r($_POST);
echo "</pre>";
I want to be clear that the following code is not good practice. You can use GOTO Label:
For Each I As Item In Items
If I = x Then
'Move to next item
GOTO Label1
End If
' Do something
Label1:
Next
An angular-only solution that works alongside ng-click
is possible by using compile to wrap the ng-click
expression.
Directive:
.directive('confirmClick', function ($window) {
var i = 0;
return {
restrict: 'A',
priority: 1,
compile: function (tElem, tAttrs) {
var fn = '$$confirmClick' + i++,
_ngClick = tAttrs.ngClick;
tAttrs.ngClick = fn + '($event)';
return function (scope, elem, attrs) {
var confirmMsg = attrs.confirmClick || 'Are you sure?';
scope[fn] = function (event) {
if($window.confirm(confirmMsg)) {
scope.$eval(_ngClick, {$event: event});
}
};
};
}
};
});
HTML:
<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>
The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.
For mysql 5.7 downloaded from binary file onto MacOS:
sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
root@hostname:~# time [command]
It also distinguishes between real time used and system time used.
public void DeleteUserIMP(UserIMP useriamp) {
synchronized (ListUserIMP) {
if (ListUserIMP.isEmpty()) {
System.out.println("user is empty");
} else {
Iterator<UserIMP> it = ListUserIMP.iterator();
while (it.hasNext()) {
UserIMP user = it.next();
if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
it.remove();
System.out.println("remove it");
}
}
// ListUserIMP.remove(useriamp);
System.out.println(" this user removed");
}
Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
// System.out.println("This user Deleted " + Constants.MESSAGE_OK);
}
}
It is correct that we need to look into the path ~/Library/Developer/CoreSimulator/Devices/.
But the issue I am seeing is that the path keeps changing every time I run the app. The path contains another set of long IDs after the Application string and that keeps changing every time I run the app. This basically means that my app will not have any cached data when it runs the next time.
Here are a few things you cant do with email:
- Include a section with styles. Apple Mail.app supports it, but Gmail and Hotmail do not, so it's a no-no. Hotmail will support a style section in the body but Gmail still doesn't.
- Link to an external stylesheet. Not many email clients support this, best to just forget it.
- Background-image / Background-position. Gmail is also the culprit on this one.
- Clear your floats. Gmail again.
- Margin. Yep, seriously, Hotmail ignores margins. Basically any CSS positioning at all doesn't work.
- Font-anything. Chances are Eudora will ignore anything you try to declare with fonts.
Source: http://css-tricks.com/using-css-in-html-emails-the-real-story/
Mailchimp has email templates you can use - here
A few more resources that should help you
Right-click My Computer and go to Properties->Advanced->Environmental Variables...
What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.
If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment
(assuming your current control set is not ControlSet002
). Then find the Path
value and copy the data into the Path
value of HKLM\CurrentControlSet\Control\Session Manager\Environment
. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)
Please try the following:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
It will be fixed 64 chars, so use char(64)
Provided your class extends a class with a generic parameter, you can also get this at runtime via reflection, and then use that for comparison, i.e.
class YourClass extends SomeOtherClass<String>
{
private Class<?> clazz;
public Class<?> getParameterizedClass()
{
if(clazz == null)
{
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
clazz = (Class<?>)pt.getActualTypeArguments()[0];
}
return clazz;
}
}
In the case above, at runtime you will get String.class from getParameterizedClass(), and it caches so you don't get any reflection overhead upon multiple checks. Note that you can get the other parameterized types by index from the ParameterizedType.getActualTypeArguments() method.
If this (https://stackoverflow.com/a/11764922/3045875) does not help: Check if another SVN tool is interfering and close the tool. We just struggled a couple of hours at merging using TortoiseSVN and had dozens of such lock errors. Eventually we figured that Matlabs SVN integration is interfering and after closing it all worked out.
You can use the below method:
# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
if file not in ephFiles:
noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.
Thank you.
In my case, it was a sloppy application issue. An AJAX call is being made to a PHP which had sloppy includes (there was trailing white space after the PHP closing delimiter in two of the includes). This meant that spaces were being output to the response ahead of the expected JSON output. I only discovered this when I put a Header for JSON output just ahead of the response, and the chunking error was replaced by the error that "headers could not be sent because output had occurred". In other words, the AJAX was expecting a JSON response, and it got that - sort of - but the response wasn't clean because a JSON response shouldn't have white ahead of it. This was apparent when looking at the Response from the PHP in Firebug Network - the response looked right justified in the panel because of the leading spaces. Strangely, not all white space triggered the error - the chunking error only occurred when the entire length of the response exceeded some certain length.
Changing com.android.tools.build:gradle:2.2.0-beta1
to com.android.tools.build:gradle:2.1.2
fixed it for me.
My Android Studio version is 2.1.2, perhaps that's why
I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:
* commit I want to cherry-pick (x)
|\
| * branch I want to cherry-pick to (y)
* |
|/
* common parent (x)
I understand now that I want to do
git cherry-pick -m 2 mycommitsha
This is because -m 1
would merge based on the common parent where as -m 2
merges based on branch y, that is the one I want to cherry-pick to.
**June 2012 **
Google Recommends Eclipse Helios, Eclipse Classic or Eclipse RCP. For details, read the below post.
URL: http://developer.android.com/sdk/eclipse-adt.html
Look under ADT 18.0.0 (April 2012).
Eclipse Helios (Version 3.6.2) or higher is required for ADT 18.0.0.
Look under Installing the ADT Plugin.
If you need to install or update Eclipse, you can download it from http://www.eclipse.org/downloads/. The "Eclipse Classic" version is recommended. Otherwise, a Java or RCP version of Eclipse is recommended.
April 2014 Updated
Eclipse Indigo (Version 3.7.2) or higher is required. I'll suggest you to use Eclipse Kepler.
ADT 22.6.0 (March 2014)
The most efficient way could possibly be to use a fast logarithm based approach, similar to those used to determine the highest bit set in an integer.
size_t printed_length ( int32_t x )
{
size_t count = x < 0 ? 2 : 1;
if ( x < 0 ) x = -x;
if ( x >= 100000000 ) {
count += 8;
x /= 100000000;
}
if ( x >= 10000 ) {
count += 4;
x /= 10000;
}
if ( x >= 100 ) {
count += 2;
x /= 100;
}
if ( x >= 10 )
++count;
return count;
}
This (possibly premature) optimisation takes 0.65s for 20 million calls on my netbook; iterative division like zed_0xff has takes 1.6s, recursive division like Kangkan takes 1.8s, and using floating point functions (Jordan Lewis' code) takes a whopping 6.6s. Using snprintf takes 11.5s, but will give you the size that snprintf requires for any format, not just integers. Jordan reports that the ordering of the timings are not maintained on his processor, which does floating point faster than mine.
The easiest is probably to ask snprintf for the printed length:
#include <stdio.h>
size_t printed_length ( int x )
{
return snprintf ( NULL, 0, "%d", x );
}
int main ()
{
int x[] = { 1, 25, 12512, 0, -15 };
for ( int i = 0; i < sizeof ( x ) / sizeof ( x[0] ); ++i )
printf ( "%d -> %d\n", x[i], printed_length ( x[i] ) );
return 0;
}
To add okhttp as a dependency do as follows
now you have okhttp as a dependency
Now design a interface as below so we can have the callback to our activity once the network response received.
public interface NetworkCallback {
public void getResponse(String res);
}
I create a class named NetworkTask so i can use this class to handle all the network requests
public class NetworkTask extends AsyncTask<String , String, String>{
public NetworkCallback instance;
public String url ;
public String json;
public int task ;
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public NetworkTask(){
}
public NetworkTask(NetworkCallback ins, String url, String json, int task){
this.instance = ins;
this.url = url;
this.json = json;
this.task = task;
}
public String doGetRequest() throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String doPostRequest() throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
@Override
protected String doInBackground(String[] params) {
try {
String response = "";
switch(task){
case 1 :
response = doGetRequest();
break;
case 2:
response = doPostRequest();
break;
}
return response;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
instance.getResponse(s);
}
}
now let me show how to get the callback to an activity
public class MainActivity extends AppCompatActivity implements NetworkCallback{
String postUrl = "http://your-post-url-goes-here";
String getUrl = "http://your-get-url-goes-here";
Button doGetRq;
Button doPostRq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
doGetRq = findViewById(R.id.button2);
doPostRq = findViewById(R.id.button1);
doPostRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendPostRq();
}
});
doGetRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendGetRq();
}
});
}
public void sendPostRq(){
JSONObject jo = new JSONObject();
try {
jo.put("email", "yourmail");
jo.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
// 2 because post rq is for the case 2
NetworkTask t = new NetworkTask(this, postUrl, jo.toString(), 2);
t.execute(postUrl);
}
public void sendGetRq(){
// 1 because get rq is for the case 1
NetworkTask t = new NetworkTask(this, getUrl, jo.toString(), 1);
t.execute(getUrl);
}
@Override
public void getResponse(String res) {
// here is the response from NetworkTask class
System.out.println(res)
}
}
In Python3, csv.reader
expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs
module:
import csv
import codecs
ifile = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
print (row)
If you want the default colors of Android ICS, you just have to go to your Android SDK and look for this path: platforms\android-15\data\res\values\colors.xml
.
Here you go:
<!-- For holo theme -->
<drawable name="screen_background_holo_light">#fff3f3f3</drawable>
<drawable name="screen_background_holo_dark">#ff000000</drawable>
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
<color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
<color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
<color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
<color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
<color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
<color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
<color name="dim_foreground_holo_dark">#bebebe</color>
<color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
<color name="dim_foreground_inverse_holo_dark">#323232</color>
<color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
<color name="hint_foreground_holo_dark">#808080</color>
<color name="dim_foreground_holo_light">#323232</color>
<color name="dim_foreground_disabled_holo_light">#80323232</color>
<color name="dim_foreground_inverse_holo_light">#bebebe</color>
<color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
<color name="hint_foreground_holo_light">#808080</color>
<color name="highlighted_text_holo_dark">#6633b5e5</color>
<color name="highlighted_text_holo_light">#6633b5e5</color>
<color name="link_text_holo_dark">#5c5cff</color>
<color name="link_text_holo_light">#0000ee</color>
This for the Background:
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
You won't get the same colors if you look this up in Photoshop etc. because they are set up with Alpha values.
Update for API Level 19:
<resources>
<drawable name="screen_background_light">#ffffffff</drawable>
<drawable name="screen_background_dark">#ff000000</drawable>
<drawable name="status_bar_closed_default_background">#ff000000</drawable>
<drawable name="status_bar_opened_default_background">#ff000000</drawable>
<drawable name="notification_item_background_color">#ff111111</drawable>
<drawable name="notification_item_background_color_pressed">#ff454545</drawable>
<drawable name="search_bar_default_color">#ff000000</drawable>
<drawable name="safe_mode_background">#60000000</drawable>
<!-- Background drawable that can be used for a transparent activity to
be able to display a dark UI: this darkens its background to make
a dark (default theme) UI more visible. -->
<drawable name="screen_background_dark_transparent">#80000000</drawable>
<!-- Background drawable that can be used for a transparent activity to
be able to display a light UI: this lightens its background to make
a light UI more visible. -->
<drawable name="screen_background_light_transparent">#80ffffff</drawable>
<color name="safe_mode_text">#80ffffff</color>
<color name="white">#ffffffff</color>
<color name="black">#ff000000</color>
<color name="transparent">#00000000</color>
<color name="background_dark">#ff000000</color>
<color name="background_light">#ffffffff</color>
<color name="bright_foreground_dark">@android:color/background_light</color>
<color name="bright_foreground_light">@android:color/background_dark</color>
<color name="bright_foreground_dark_disabled">#80ffffff</color>
<color name="bright_foreground_light_disabled">#80000000</color>
<color name="bright_foreground_dark_inverse">@android:color/bright_foreground_light</color>
<color name="bright_foreground_light_inverse">@android:color/bright_foreground_dark</color>
<color name="dim_foreground_dark">#bebebe</color>
<color name="dim_foreground_dark_disabled">#80bebebe</color>
<color name="dim_foreground_dark_inverse">#323232</color>
<color name="dim_foreground_dark_inverse_disabled">#80323232</color>
<color name="hint_foreground_dark">#808080</color>
<color name="dim_foreground_light">#323232</color>
<color name="dim_foreground_light_disabled">#80323232</color>
<color name="dim_foreground_light_inverse">#bebebe</color>
<color name="dim_foreground_light_inverse_disabled">#80bebebe</color>
<color name="hint_foreground_light">#808080</color>
<color name="highlighted_text_dark">#9983CC39</color>
<color name="highlighted_text_light">#9983CC39</color>
<color name="link_text_dark">#5c5cff</color>
<color name="link_text_light">#0000ee</color>
<color name="suggestion_highlight_text">#177bbd</color>
<drawable name="stat_notify_sync_noanim">@drawable/stat_notify_sync_anim0</drawable>
<drawable name="stat_sys_download_done">@drawable/stat_sys_download_done_static</drawable>
<drawable name="stat_sys_upload_done">@drawable/stat_sys_upload_anim0</drawable>
<drawable name="dialog_frame">@drawable/panel_background</drawable>
<drawable name="alert_dark_frame">@drawable/popup_full_dark</drawable>
<drawable name="alert_light_frame">@drawable/popup_full_bright</drawable>
<drawable name="menu_frame">@drawable/menu_background</drawable>
<drawable name="menu_full_frame">@drawable/menu_background_fill_parent_width</drawable>
<drawable name="editbox_dropdown_dark_frame">@drawable/editbox_dropdown_background_dark</drawable>
<drawable name="editbox_dropdown_light_frame">@drawable/editbox_dropdown_background</drawable>
<drawable name="dialog_holo_dark_frame">@drawable/dialog_full_holo_dark</drawable>
<drawable name="dialog_holo_light_frame">@drawable/dialog_full_holo_light</drawable>
<drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
<drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
<color name="input_method_navigation_guard">#ff000000</color>
<!-- For date picker widget -->
<drawable name="selected_day_background">#ff0092f4</drawable>
<!-- For settings framework -->
<color name="lighter_gray">#ddd</color>
<color name="darker_gray">#aaa</color>
<!-- For security permissions -->
<color name="perms_dangerous_grp_color">#33b5e5</color>
<color name="perms_dangerous_perm_color">#33b5e5</color>
<color name="shadow">#cc222222</color>
<color name="perms_costs_money">#ffffbb33</color>
<!-- For search-related UIs -->
<color name="search_url_text_normal">#7fa87f</color>
<color name="search_url_text_selected">@android:color/black</color>
<color name="search_url_text_pressed">@android:color/black</color>
<color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>
<!-- SlidingTab -->
<color name="sliding_tab_text_color_active">@android:color/black</color>
<color name="sliding_tab_text_color_shadow">@android:color/black</color>
<!-- keyguard tab -->
<color name="keyguard_text_color_normal">#ffffff</color>
<color name="keyguard_text_color_unlock">#a7d84c</color>
<color name="keyguard_text_color_soundoff">#ffffff</color>
<color name="keyguard_text_color_soundon">#e69310</color>
<color name="keyguard_text_color_decline">#fe0a5a</color>
<!-- keyguard clock -->
<color name="lockscreen_clock_background">#ffffffff</color>
<color name="lockscreen_clock_foreground">#ffffffff</color>
<color name="lockscreen_clock_am_pm">#ffffffff</color>
<color name="lockscreen_owner_info">#ff9a9a9a</color>
<!-- keyguard overscroll widget pager -->
<color name="kg_multi_user_text_active">#ffffffff</color>
<color name="kg_multi_user_text_inactive">#ff808080</color>
<color name="kg_widget_pager_gradient">#ffffffff</color>
<!-- FaceLock -->
<color name="facelock_spotlight_mask">#CC000000</color>
<!-- For holo theme -->
<drawable name="screen_background_holo_light">#fff3f3f3</drawable>
<drawable name="screen_background_holo_dark">#ff000000</drawable>
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
<color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
<color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
<color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
<color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
<color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
<color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
<color name="dim_foreground_holo_dark">#bebebe</color>
<color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
<color name="dim_foreground_inverse_holo_dark">#323232</color>
<color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
<color name="hint_foreground_holo_dark">#808080</color>
<color name="dim_foreground_holo_light">#323232</color>
<color name="dim_foreground_disabled_holo_light">#80323232</color>
<color name="dim_foreground_inverse_holo_light">#bebebe</color>
<color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
<color name="hint_foreground_holo_light">#808080</color>
<color name="highlighted_text_holo_dark">#6633b5e5</color>
<color name="highlighted_text_holo_light">#6633b5e5</color>
<color name="link_text_holo_dark">#5c5cff</color>
<color name="link_text_holo_light">#0000ee</color>
<!-- Group buttons -->
<eat-comment />
<color name="group_button_dialog_pressed_holo_dark">#46c5c1ff</color>
<color name="group_button_dialog_focused_holo_dark">#2699cc00</color>
<color name="group_button_dialog_pressed_holo_light">#ffffffff</color>
<color name="group_button_dialog_focused_holo_light">#4699cc00</color>
<!-- Highlight colors for the legacy themes -->
<eat-comment />
<color name="legacy_pressed_highlight">#fffeaa0c</color>
<color name="legacy_selected_highlight">#fff17a0a</color>
<color name="legacy_long_pressed_highlight">#ffffffff</color>
<!-- General purpose colors for Holo-themed elements -->
<eat-comment />
<!-- A light Holo shade of blue -->
<color name="holo_blue_light">#ff33b5e5</color>
<!-- A light Holo shade of gray -->
<color name="holo_gray_light">#33999999</color>
<!-- A light Holo shade of green -->
<color name="holo_green_light">#ff99cc00</color>
<!-- A light Holo shade of red -->
<color name="holo_red_light">#ffff4444</color>
<!-- A dark Holo shade of blue -->
<color name="holo_blue_dark">#ff0099cc</color>
<!-- A dark Holo shade of green -->
<color name="holo_green_dark">#ff669900</color>
<!-- A dark Holo shade of red -->
<color name="holo_red_dark">#ffcc0000</color>
<!-- A Holo shade of purple -->
<color name="holo_purple">#ffaa66cc</color>
<!-- A light Holo shade of orange -->
<color name="holo_orange_light">#ffffbb33</color>
<!-- A dark Holo shade of orange -->
<color name="holo_orange_dark">#ffff8800</color>
<!-- A really bright Holo shade of blue -->
<color name="holo_blue_bright">#ff00ddff</color>
<!-- A really bright Holo shade of gray -->
<color name="holo_gray_bright">#33CCCCCC</color>
<drawable name="notification_template_icon_bg">#3333B5E5</drawable>
<drawable name="notification_template_icon_low_bg">#0cffffff</drawable>
<!-- Keyguard colors -->
<color name="keyguard_avatar_frame_color">#ffffffff</color>
<color name="keyguard_avatar_frame_shadow_color">#80000000</color>
<color name="keyguard_avatar_nick_color">#ffffffff</color>
<color name="keyguard_avatar_frame_pressed_color">#ff35b5e5</color>
<color name="accessibility_focus_highlight">#80ffff00</color>
</resources>
Yes, you could use either the JavaScript setTimeout()
method or setInterval()
method to invoke the code that you would like to run. Here's how you might do it with setTimeout:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
If you look at this url: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/
this part of the schema may be what you are looking for.
ID INTEGER NOT NULL
PRIMARY KEY GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
Add the "code" folder to the project properties within Visual Studio
Project->Properties->Configuration Properties->C/C++->Additional Include Directories
Now you may have a better solution to resolve this scenario, but other way which i preferred.
const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
// code here
}
I preferred above solution over the indexOf check where you need to check index as well.
if ( arr.indexOf( foo ) !== -1 ) { }
I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess) But in my case I want to create my DB based on some parameters I defined in .env file so I did these
1) First I define .env file something like this in my docker root project directory
MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306
2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file
version: '2'
services:
### MySQL Container
mysql:
build:
context: ./mysql
args:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
ports:
- "${MYSQL_PORT}:3306"
3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this
FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD
ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d
EXPOSE 3306
4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder
mysqldump -h <server name> -u<user> -p <db name> > data.sql
The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this
--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;
-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...
So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE
placeholder with the name of my DB that I have set it in .env file.
|- docker-compose.yml
|- .env
|- mysql
|- Dockerfile
|- data.sql
Now you are ready to build and run your container
public static <T> T defaultWhenNull(@Nullable T object, @NonNull T def) {
return (object == null) ? def : object;
}
Example:
defaultWhenNull(getNullableString(), "");
Always evaluates the default value
(as oposed to cond ? nonNull() : notEvaluated()
)
This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using Optional.orElse()
;-)
I can suggest you a javascript oriented approach which makes it easy to work with javascript files in your project.
Create a javascript section in your jinja template file and place all variables you want to use in your javascript files in a window object:
Start.html
...
{% block scripts %}
<script type="text/javascript">
window.appConfig = {
debug: {% if env == 'development' %}true{% else %}false{% endif %},
facebook_app_id: {{ facebook_app_id }},
accountkit_api_version: '{{ accountkit_api_version }}',
csrf_token: '{{ csrf_token }}'
}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}
Jinja will replace values and our appConfig object will be reachable from our other script files:
App.js
var AccountKit_OnInteractive = function(){
AccountKit.init({
appId: appConfig.facebook_app_id,
debug: appConfig.debug,
state: appConfig.csrf_token,
version: appConfig.accountkit_api_version
})
}
I have seperated javascript code from html documents with this way which is easier to manage and seo friendly.
Create a function and copy the code using winsock which is mentioned already by Software_Developer.
For Instance:
#ifdef _WIN32
// this is required only for windows
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
//...
}
#endif
winsock code here
#ifdef _WIN32
WSACleanup();
#endif
This does what you want, I think:
git log --all --pretty=format: --name-only --diff-filter=D | sort -u
... which I've just taken more-or-less directly from this other answer.
Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT
i.e 204 No Content as in place of HttpStatus.OK
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
Any value of T will be ignored for 204, but not for 404
public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$
if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
} else {
LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
}
}
checked
attribute is a boolean value so "checked"
value of other "string"
except boolean false
converts to true
.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
Under APK/ALPHA TESTING/MANAGE TESTERS you find:
Choose the method you want. Then you need to first upload your Apk. Before it can be published you need to go to the usual steps in publishing which means: you need icons, the FSK ratings, screenshots etc.
After you added it you click on publish.
You find the link for your testers at:
I don't have enough rep to put this under comments to the existing answers:
unescape
is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent
converts a js string to escaped UTF-8 and decodeURIComponent
only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error
because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // ©
So you need to know your data when using decodeURIComponent.
decodeURIComponent won't work on "%C2"
or any lone byte over 0x7f
because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you ©
Unescape wouldn't work properly on that // ©
AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.
Yes, you can do this use this below code it may help you.
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
display : block;_x000D_
padding : 10px;_x000D_
text-align : center;_x000D_
border: 5px solid #000;_x000D_
margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
<div class="childDiv1">_x000D_
First Div Child_x000D_
</div>_x000D_
<div class="childDiv2">_x000D_
Second Div Child_x000D_
</div>_x000D_
<div class="childDiv3">_x000D_
Third Div Child_x000D_
</div>_x000D_
<div class="childDiv4">_x000D_
Fourth Div Child_x000D_
</div>_x000D_
</div>
_x000D_
in the "global and static" area :)
There are several memory areas in C++:
See here for a detailed answer to your question:
The following summarizes a C++ program's major distinct memory areas. Note that some of the names (e.g., "heap") do not appear as such in the draft [standard].
Memory Area Characteristics and Object Lifetimes
-------------- ------------------------------------------------
Const Data The const data area stores string literals and
other data whose values are known at compile
time. No objects of class type can exist in
this area. All data in this area is available
during the entire lifetime of the program.
Further, all of this data is read-only, and the
results of trying to modify it are undefined.
This is in part because even the underlying
storage format is subject to arbitrary
optimization by the implementation. For
example, a particular compiler may store string
literals in overlapping objects if it wants to.
Stack The stack stores automatic variables. Typically
allocation is much faster than for dynamic
storage (heap or free store) because a memory
allocation involves only pointer increment
rather than more complex management. Objects
are constructed immediately after memory is
allocated and destroyed immediately before
memory is deallocated, so there is no
opportunity for programmers to directly
manipulate allocated but uninitialized stack
space (barring willful tampering using explicit
dtors and placement new).
Free Store The free store is one of the two dynamic memory
areas, allocated/freed by new/delete. Object
lifetime can be less than the time the storage
is allocated; that is, free store objects can
have memory allocated without being immediately
initialized, and can be destroyed without the
memory being immediately deallocated. During
the period when the storage is allocated but
outside the object's lifetime, the storage may
be accessed and manipulated through a void* but
none of the proto-object's nonstatic members or
member functions may be accessed, have their
addresses taken, or be otherwise manipulated.
Heap The heap is the other dynamic memory area,
allocated/freed by malloc/free and their
variants. Note that while the default global
new and delete might be implemented in terms of
malloc and free by a particular compiler, the
heap is not the same as free store and memory
allocated in one area cannot be safely
deallocated in the other. Memory allocated from
the heap can be used for objects of class type
by placement-new construction and explicit
destruction. If so used, the notes about free
store object lifetime apply similarly here.
Global/Static Global or static variables and objects have
their storage allocated at program startup, but
may not be initialized until after the program
has begun executing. For instance, a static
variable in a function is initialized only the
first time program execution passes through its
definition. The order of initialization of
global variables across translation units is not
defined, and special care is needed to manage
dependencies between global objects (including
class statics). As always, uninitialized proto-
objects' storage may be accessed and manipulated
through a void* but no nonstatic members or
member functions may be used or referenced
outside the object's actual lifetime.
This way you can use upto 'N' letters.
char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
if(a[i] != 'b'){
indexOf++;
}else{
System.out.println("index of given: "+indexOf);
}}
In line style - this works for me every time
<div class="imgWrapper">
<img src="/theImg.jpg" style="max-width: 100%">
</div>
In Bash, you can also redirect to a subshell using process substitution:
command > >(stdlog pipe) 2> >(stderr pipe)
For the case at hand:
command 2> >(grep 'something') >/dev/null
As of this time, the latest draft of the HTTPbis specification, which is intended to replace and make RFC 2616 obsolete, states:
The 400 (Bad Request) status code indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
This definition, while of course still subject to change, ratifies the widely used practice of responding to logical errors with a 400.
After messing with this for days, my final fix for our issues required two things;
1) We added this line of code to all of our .Net libraries that make out bound api calls to other vendors that had also disabled their SSL v3.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // (.Net 4 and below)
2) This is the final and FULL registry changes you will need when you are running ASP.Net 4.0 sites and will need to be slightly changed after you upgrade to ASP.Net 4.5.
After we rebooted the servers - all problems went away after this.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
Add this to eclipse.ini:
-vm
your_java_path\bin\javaw.exe
...but be aware that you must add these lines before -vmargs
Here is another example that return's a boolean value using try/catch.
private boolean doSomeThing(int index){
try {
if(index%2==0)
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
System.out.println("Finally!!! ;) ");
}
return false;
}
Inspect the element, then use this in the console
s = $($0).scope()
// `s` is the scope object if it exists
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
rt.jar
contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.
For MacOS it is called classes.jar
and located under /System/Library/Frameworks/<java_version>/Classes
. Same not messing with it rule applies there as well :).
http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html
This one worked for me
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
The error message from xcode app installation sometime can be very misleading, I have aligned the entitlements many times, but the root cause is not because of that, it is because I have changed the certificate and my build pipeline script was using wrong certificate SHA value:
/usr/bin/codesign --force --sign 701BB03735D5960C855D6E79223414F93F40065E --entitlements $workspace/xxx.app.xcent --timestamp=none $workspace/xxxx.app
for my case, nothing's wrong with my entitlement file, it is because 701BB03735D5960C855D6E79223414F93F40065E
is wrong, but the error message always print out as The executable was signed with invalid entitlements
. Wasted my whole day for this.
Just use parseInt()
and be sure to include the radix so you get predictable results:
parseInt(d, 10);
USE THIS
I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.
http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/
I hope this helps people because it was exactly what I was looking for
As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.
If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS
Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");
, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.
.iOS-device {
style-you-want-to-set: yada;
}
When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.
/* file ab.c */
static void function1(void)
{
puts("function1 called");
}
And store the following code in another file ab1.c
/* file ab1.c */
int main(void)
{
function1();
getchar();
return 0;
}
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */
Login to Server as Admin
Go To Security > Logins > New Login
Step 1:
Login Name : SomeName
Step 2:
Select SQL Server / Windows Authentication.
More Info on, what is the differences between sql server authentication and windows authentication..?
Choose Default DB and Language of your choice
Click OK
Try to connect with the New User Credentials, It will prompt you to change the password. Change and login
OR
Try with query :
USE [master] -- Default DB
GO
CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO
--123456 is the Password And Username is Login User
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.
The following instructions from this blog article helped me in the end:
cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.
http://www.cplusplus.com/reference/stl/vector/vector/
int size = 5; // declare the size of the vector
vector<int> myvector(size, 0); // create a vector to hold "size" int's
// all initialized to zero
myvector[0] = 1234; // assign values like a c++ array
For older Ubuntu distros i.e 16.04, 14.04, 12.04 etc
sudo apt-get install zip unzip php7.0-zip
@mplungjan, @eduard-luca
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,12,0,0,0);
return mm === (date.getMonth()+1) &&
dd === date.getDate() &&
yyyy === date.getFullYear();
}
new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.
Example:
new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
Another alternative is to use getUTCDate().
Both Jonathan and Charles are right... you've got to stop the service first, then uninstall/reinstall. Combining their two answers makes the perfect batch file or PowerShell script.
I will make mention of a caution learned the hard way -- Windows 2000 Server (possibly the client OS as well) will require a reboot before the reinstall no matter what. There must be a registry key that is not fully cleared until the box is rebooted. Windows Server 2003, Windows XP and later OS versions do not suffer that pain.
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents()
on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
the reverse function comes in handy here:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
Try this:
setlocal EnableDelayedExpansion
...
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
I'm surprised nobody mentioned the command php artisan route:list
, which gives a list of all registered app routes (including Auth::routes()
and Passport::routes()
if registered)
For latest OSX versions,
Get Info
Sharing & Permission
sectionRead & Write
privilege for the users+
icon to add usernameFinally click settings icon
and select Apply to enclosed items...
You can try something like this. Here on click of image button I toggle the imageview.
holder.imgitem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(!onclick){
mSparseBooleanArray.put((Integer) view.getTag(), true);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
onclick=true;}
else if(onclick)
{
mSparseBooleanArray.put((Integer) view.getTag(), false);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);
onclick=false;
}
}
});
Mac OS X and some other Unixes at least have the user path compiled into sshd for security reasons so those of us that install git as /usr/local/git/{bin,lib,...} can run into trouble as the git executables are not in the precompiled path. To override this I prefer to edit my /etc/sshd_config changing:
#PermitUserEnvironment no
to
PermitUserEnvironment yes
and then create ~/.ssh/environment files as needed. My git users have the following in their ~/.ssh/environment file:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin
Note variable expansion does not occur when the ~/.ssh/environment file is read so:
PATH=$PATH:/usr/local/git/bin
will not work.
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
For me the UnicodeWriter
class from Python 2 CSV module documentation didn't really work as it breaks the csv.writer.write_row()
interface.
For example:
csv_writer = csv.writer(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)
works, while:
csv_writer = UnicodeWriter(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)
will throw AttributeError: 'int' object has no attribute 'encode'
.
As UnicodeWriter
obviously expects all column values to be strings, we can convert the values ourselves and just use the default CSV module:
def to_utf8(lst):
return [unicode(elem).encode('utf-8') for elem in lst]
...
csv_writer.writerow(to_utf8(row))
Or we can even monkey-patch csv_writer to add a write_utf8_row
function - the exercise is left to the reader.
1) Download connector from here https://www.mysql.com/products/connector/
2) Select JDBC driver for mysql
3) click on Platform Independent (Architecture Independent), ZIP Archive
4) Download the file and unzip it
5) (For Eclipse)Click Project->properties-> Java Build Path->Libraries (For Netbeans) right click libraries on left bar-> add jar
6) Click on add external jar
7) select mysql-connector-java-5.1.40-bin.jar
8) Done!
NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write()
to write output to the Output window.
The Console.Write
method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read
reads input from whatever is hooked up to the standard input.
When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.
You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole
documentation, it appears that the function will reset stdin
and stdout
handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout
for Windows to steal it from me, but I haven't tried.)
In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine
the way you are, and check the output results in the Test Results window when it's done.
Use
func contains(_ str: String) -> Bool
let string = "hello Swift"
let containsSwift = string.contains("Swift")
print(containsSwift) // prints true
I fixed this issue by moving my directory from my exFAT drive which does not support symlinking.
My exFat drive is shared between osx and a bootcamp windows partition so when I tried to clone and npm install my project it was failing but never explains that exFAT doesn't support this functionality.
There are drivers out there that you can install to add the ability to symlink but you'll have to do a lot of your setup manually compared to running a simple npm script.
I made the same error using sudo for my installation. (oops)
brew install python
brew linkapps python
brew link --overwrite python
This brought everything back to normal.
You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.
Both Date
and moment
will parse the input string in the local time zone of the browser by default. However Date
is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD
, using hyphens, or if it is YYYY-MM-DD HH:mm:ss
, it will interpret it as local time. Unlike Date
, moment
will always be consistent about how it parses.
The correct way to parse an input moment as UTC in the format you provided would be like this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
Refer to this documentation.
If you want to then format it differently for output, you would do this:
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString
explicitly.
Note that it is very important to provide the input format. Without it, a date like 01-04-2013
might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.
For some needs, a deque may also be useful. You can add and remove items on both ends of a deque at O(1) cost.
from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
this should work
.navbar-nav {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.
Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).
One example would be for modeling trees. If you are using a HashMap to represent a tree structure, where the key is the parent and the value is list of children, then the values for the null
key would be the root nodes.
Try to minimize the use of <br>
as much as you possibly can. HTML is supposed to carry content and structure, <br>
is neither. A simple workaround is to wrap your input elements in <p>
elements, like so:
<form name="publish" id="publish" action="publishprocess.php" method="post">
<p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
<p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>
<p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
<p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>
<p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>
<p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
<p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>
<p>District Restriction:<?php echo $locationtext.$cityname; ?></p>
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
If you're using coffee-script, it's as easy as:
newObject = {}
newObject[key] = value for own key,value of oldObject
Though this isn't a deep clone.
Overloading is the concept in which you have same signatures or methods with same name but different parameters and overriding, we have same name methods with different parameters also have inheritance is known as overriding.
It's useful to have descriptions of what each flag does. By using a CLI like bit you'll have access to flag descriptions as you're typing.
You could use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
You can keep your CONTACT parameter with the following approach:
using (var stream = new MemoryStream())
{
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.
Found as accepted answer here
I faced this Issue before and I fixed it with vary simple workaround way
For your Component.html
<select class="form-control" ngValue="op1" (change)="gotit($event.target.value)">
<option *ngFor="let workout of workouts" value="{{workout.name}}" name="op1" >{{workout.name}}</option>
</select>
Then in your component.ts you can detect the selected option by
gotit(name:string) {
//Use it from hare
console.log(name);
}
Because the vertical-align
is set at baseline as default.
Use vertical-align:top
instead:
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align:top;
}
http://jsfiddle.net/Lighty_46/RHM5L/9/
Or as @f00644 said you could apply float
to the child elements as well.
The best - and simplest - solution might be this:
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();
Documentation for finishAndRemoveTask()
:
Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.
Is that what you're looking for?
You'll need to use sp_addlinkedserver
to create a server link. See the reference documentation for usage. Once the server link is established, you'll construct the query as normal, just prefixing the database name with the other server. I.E:
-- FROM DB1
SELECT *
FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
INNER JOIN [DB2].[MyDatabaseOnDB2].[dbo].[MyOtherTable] tab2
ON tab1.ID = tab2.ID
Once the link is established, you can also use OPENQUERY
to execute a SQL statement on the remote server and transfer only the data back to you. This can be a bit faster, and it will let the remote server optimize your query. If you cache the data in a temporary (or in-memory) table on DB1
in the example above, then you'll be able to query it just like joining a standard table. For example:
-- Fetch data from the other database server
SELECT *
INTO #myTempTable
FROM OPENQUERY([DB2], 'SELECT * FROM [MyDatabaseOnDB2].[dbo].[MyOtherTable]')
-- Now I can join my temp table to see the data
SELECT * FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
INNER JOIN #myTempTable tab2 ON tab1.ID = tab2.ID
Check out the documentation for OPENQUERY to see some more examples. The example above is pretty contrived. I would definitely use the first method in this specific example, but the second option using OPENQUERY
can save some time and performance if you use the query to filter out some data.
Function isset()
is faster, check http://www.php.net/manual/en/function.array-key-exists.php#82867
$(document).ready(function(){ _x000D_
$("#btn_clone").click(function(){ _x000D_
$("#a_clone").clone().appendTo("#b_clone"); _x000D_
}); _x000D_
});
_x000D_
.container{_x000D_
padding: 15px;_x000D_
border: 12px solid #23384E;_x000D_
background: #28BAA2;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head> _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head> _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p> _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p> _x000D_
<button id="btn_clone">Click Me!</button> _x000D_
</div> _x000D_
</body> _x000D_
</html>
_x000D_
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
data.rename(columns={'gdp':'log(gdp)'}, inplace=True)
The rename
show that it accepts a dict as a param for columns
so you just pass a dict with a single entry.
Also see related
convert Map to POJO example.Notice the Map key contains underline and field variable is hump.
User.class POJO
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class User {
@JsonProperty("user_name")
private String userName;
@JsonProperty("pass_word")
private String passWord;
}
The App.class test the example
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) {
Map<String, String> info = new HashMap<>();
info.put("user_name", "Q10Viking");
info.put("pass_word", "123456");
ObjectMapper mapper = new ObjectMapper();
User user = mapper.convertValue(info, User.class);
System.out.println("-------------------------------");
System.out.println(user);
}
}
/**output
-------------------------------
User(userName=Q10Viking, passWord=123456)
*/
I find dstat to be quite good. Has to be installed though. Gives you way more information than you need. Netstat will give you packet rates but not bandwith also. netstat -s
if I got your question correct...
main() method is defined in the class below...
public class ToBeCalledClass{
public static void main (String args[ ]) {
System.out.println("I am being called");
}
}
you want to call this main method in another class.
public class CallClass{
public void call(){
ToBeCalledClass.main(null);
}
}
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
if(target.matches("\\S"))
// then string contains at least one non-whitespace character
Note use of back-slash cap-S, meaning "non-whitespace char"
I'd wager this is the simplest (and perhaps the fastest?) solution.
Building on Henks answer I have created some test methods with his answer and some added, more optimized, methods. I found the results differ based on the size of the input string. Therefore, I have tested with two result sets. In the fastest method, the linked source has a even faster way. But, since it is characterized as unsafe I have left this out.
Long input string results:
Short input string results:
Code:
public class RemoveWhitespace
{
public static string RemoveStringReader(string input)
{
var s = new StringBuilder(input.Length); // (input.Length);
using (var reader = new StringReader(input))
{
int i = 0;
char c;
for (; i < input.Length; i++)
{
c = (char)reader.Read();
if (!char.IsWhiteSpace(c))
{
s.Append(c);
}
}
}
return s.ToString();
}
public static string RemoveLinqNativeCharIsWhitespace(string input)
{
return new string(input.ToCharArray()
.Where(c => !char.IsWhiteSpace(c))
.ToArray());
}
public static string RemoveLinq(string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
public static string RemoveRegex(string input)
{
return Regex.Replace(input, @"\s+", "");
}
private static Regex compiled = new Regex(@"\s+", RegexOptions.Compiled);
public static string RemoveRegexCompiled(string input)
{
return compiled.Replace(input, "");
}
public static string RemoveForLoop(string input)
{
for (int i = input.Length - 1; i >= 0; i--)
{
if (char.IsWhiteSpace(input[i]))
{
input = input.Remove(i, 1);
}
}
return input;
}
public static string StringSplitThenJoin(this string str)
{
return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
}
public static string RemoveInPlaceCharArray(string input)
{
var len = input.Length;
var src = input.ToCharArray();
int dstIdx = 0;
for (int i = 0; i < len; i++)
{
var ch = src[i];
switch (ch)
{
case '\u0020':
case '\u00A0':
case '\u1680':
case '\u2000':
case '\u2001':
case '\u2002':
case '\u2003':
case '\u2004':
case '\u2005':
case '\u2006':
case '\u2007':
case '\u2008':
case '\u2009':
case '\u200A':
case '\u202F':
case '\u205F':
case '\u3000':
case '\u2028':
case '\u2029':
case '\u0009':
case '\u000A':
case '\u000B':
case '\u000C':
case '\u000D':
case '\u0085':
continue;
default:
src[dstIdx++] = ch;
break;
}
}
return new string(src, 0, dstIdx);
}
}
Tests:
[TestFixture]
public class Test
{
// Short input
//private const string input = "123 123 \t 1adc \n 222";
//private const string expected = "1231231adc222";
// Long input
private const string input = "123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222";
private const string expected = "1231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc222";
private const int iterations = 1000000;
[Test]
public void RemoveInPlaceCharArray()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveInPlaceCharArray(input);
}
stopwatch.Stop();
Console.WriteLine("InPlaceCharArray: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveStringReader()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveStringReader(input);
}
stopwatch.Stop();
Console.WriteLine("String reader: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveLinqNativeCharIsWhitespace()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveLinqNativeCharIsWhitespace(input);
}
stopwatch.Stop();
Console.WriteLine("LINQ using native char.IsWhitespace: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveLinq()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveLinq(input);
}
stopwatch.Stop();
Console.WriteLine("LINQ: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveRegex()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveRegex(input);
}
stopwatch.Stop();
Console.WriteLine("Regex: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveRegexCompiled()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveRegexCompiled(input);
}
stopwatch.Stop();
Console.WriteLine("RegexCompiled: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[Test]
public void RemoveForLoop()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.RemoveForLoop(input);
}
stopwatch.Stop();
Console.WriteLine("ForLoop: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
[TestMethod]
public void StringSplitThenJoin()
{
string s = null;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
s = RemoveWhitespace.StringSplitThenJoin(input);
}
stopwatch.Stop();
Console.WriteLine("StringSplitThenJoin: " + stopwatch.ElapsedMilliseconds + " ms");
Assert.AreEqual(expected, s);
}
}
Edit: Tested a nice one liner from Kernowcode.
This seems to be a bug in iOS 8. There are two fixes to this problem :
Toggle between simulator keyboard and MacBook keyboard using the Command+K shortcut.
Reattach keyboard to simulator :
a. Open Simulator
b. Select Hardware -> Keyboard
c. Uncheck and then check 'Connect Hardware Keyboard'
OR simply press the Shift + Command + K shortcut
just pass the columnName as parameter of YEAR
SELECT YEAR(ASOFDATE) from PSASOFDATE;
another is to use DATE_FORMAT
SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;
UPDATE 1
I bet the value is varchar with the format MM/dd/YYYY, it that's the case,
SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));
LAST RESORT if all the queries fail
use SUBSTRING
SELECT SUBSTRING('11/15/2012', 7, 4)
str = Replace(str, vbLf, "")
This code takes all the line break's out of the code
if you just want the last one out:
If Right(str, 1) = vbLf Then str = Left(str, Len(str) - 1)
is the way how you tryed OK.
Update:
line feed = ASCII 10, form feed = ASCII 12 and carriage return = ASCII 13. Here we see clearly what we all know: the PC comes from the (electric) typewriter
vbLf is Chr (10) and means that the cursor jumps one line lower (typewriter: turn the roller) vbCr is Chr (13) means the cursor jumps to the beginning (typewriter: pull back the roll)
In DOS, a line break is always VBCrLf or Chr (13) & Chr (10), in files anyway, but e.g. also with the text boxes in VB.
In an Excel cell, on the other hand, a line break is only VBLf, the second line then starts at the first position even without vbCr. With vbCrLf then go one cell deeper.
So it depends on where you read and get your String from. if you want to remove all the vbLf (Char(10)) and vbCr (Char(13)) in your tring, you can do it like that:
strText = Replace(Replace(strText, Chr(10), ""), Chr(13), "")
If you only want t remove the Last one, you can test on do it like this:
If Right(str, 1) = vbLf or Right(str, 1) = vbCr Then str = Left(str, Len(str) - 1)
Code worked very well! You can overload onSizeChanged method, if not only Text has to be Changed.
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
isStale = true;
super.onSizeChanged(w, h, oldw, oldh);
}
I liked the bubble sort extension method approach on "Richie"'s blog above, but I don't necessarily want to just sort comparing the entire object. I more often want to sort on a specific property of the object. So I modified it to accept a key selector the way OrderBy does so you can choose which property to sort on:
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
if (source == null) return;
Comparer<TKey> comparer = Comparer<TKey>.Default;
for (int i = source.Count - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
TSource o1 = source[j - 1];
TSource o2 = source[j];
if (comparer.Compare(keySelector(o1), keySelector(o2)) > 0)
{
source.Remove(o1);
source.Insert(j, o1);
}
}
}
}
Which you would call the same way you would call OrderBy except it will sort the existing instance of your ObservableCollection instead of returning a new collection:
ObservableCollection<Person> people = new ObservableCollection<Person>();
...
people.Sort(p => p.FirstName);
This is a "roundabout" solution but you could use ipython
Start ipython notebook from terminal:
$ ipython notebook
It will open in a browser where you can run the javascript
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
If using jQuery 1.7+:
You can call off
before on
:
$('#myButton').off('click', onButtonClicked) // remove handler
.on('click', onButtonClicked); // add handler
If not:
You can just unbind it first event:
$('#myButton').unbind('click', onButtonClicked) //remove handler
.bind('click', onButtonClicked); //add handler
As far as I know, JFrame cannot do Modal mode. Use JDialog instead and call setModalityType(Dialog.ModalityType type)
to set it to be modal (or not modal).
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.
This works fine in all newer browsers:
#container {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background-color: #cccccc;_x000D_
margin: 10px; _x000D_
}
_x000D_
<div id="container">_x000D_
<div class="block">1</div> _x000D_
<div class="block">2</div> _x000D_
<div class="block">3</div> _x000D_
<div class="block">4</div> _x000D_
<div class="block">5</div> _x000D_
</div>
_x000D_
Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
Why don't you simply hide, append, then show, like this:
<div id="parent1" style=" width: 300px; height: 300px; background-color: yellow;">
<div id="child" style=" width: 100px; height: 100px; background-color: red;"></div>
</div>
<div id="parent2" style=" width: 300px; height: 300px; background-color: green;">
</div>
<input id="mybutton" type="button" value="move">
<script>
$("#mybutton").click(function(){
$('#child').hide(1000, function(){
$('#parent2').append($('#child'));
$('#child').show(1000);
});
});
</script>
You can specify an empty string as an argument to join, if no argument is specified a comma is used.
arr.join('');
To get an array of values from multiple checked checkboxes, use jQuery map/get functions:
$('input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
This will return array with checked values, like this one: ['1', '2']
Here is working example on jsfiddle: http://jsfiddle.net/7PV2e/
My situation was slightly different, I did git reset HEAD~
three times.
To undo it I had to do
git reset HEAD@{3}
so you should be able to do
git reset HEAD@{N}
But if you have done git reset using
git reset HEAD~3
you will need to do
git reset HEAD@{1}
{N} represents the number of operations in reflog, as Mark pointed out in the comments.
VARCHAR(MAX)
is big enough to accommodate TEXT
field. TEXT
, NTEXT
and IMAGE
data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARCHAR(MAX)
, NVARCHAR(MAX)
and VARBINARY(MAX)
.
The core problem is the js errors:
$('#purpose').on('change', function () {
// if (this.value == '1'); { No semicolon and I used === instead of ==
if (this.value === '1'){
$("#business").show();
} else {
$("#business").hide();
}
});
// }); remove
http://jsfiddle.net/Bushwazi/2kGzZ/3/
I had to clean up the html & js...I couldn't help myself.
HTML:
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<form id="business">
<label for="business">Business Name</label>
<input type='text' class='text' name='business' value size='20' />
</form>
CSS:
#business {
display:none;
}
JS:
$('#purpose').on('change', function () {
if(this.value === "1"){
$("#business").show();
} else {
$("#business").hide();
}
});
Adapt the code from MsAjax string.
Just remove all of the _validateParams
code and you are most of the way to a full fledged .NET string class in JavaScript.
Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.
P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.
<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
var a = String.format("Hello {0}!", "world");
alert(a);
</script>
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343
/*
Copyright (c) 2009, CodePlex Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/
(function(window) {
$type = String;
$type.__typeName = 'String';
$type.__class = true;
$prototype = $type.prototype;
$prototype.endsWith = function String$endsWith(suffix) {
/// <summary>Determines whether the end of this instance matches the specified string.</summary>
/// <param name="suffix" type="String">A string to compare to.</param>
/// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
return (this.substr(this.length - suffix.length) === suffix);
}
$prototype.startsWith = function String$startsWith(prefix) {
/// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
/// <param name="prefix" type="String">The String to compare.</param>
/// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
return (this.substr(0, prefix.length) === prefix);
}
$prototype.trim = function String$trim() {
/// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
return this.replace(/^\s+|\s+$/g, '');
}
$prototype.trimEnd = function String$trimEnd() {
/// <summary >Removes all trailing white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
return this.replace(/\s+$/, '');
}
$prototype.trimStart = function String$trimStart() {
/// <summary >Removes all leading white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
return this.replace(/^\s+/, '');
}
$type.format = function String$format(format, args) {
/// <summary>Replaces the format items in a specified String with the text equivalents of the values of corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
/// <param name="format" type="String">A format string.</param>
/// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
/// <returns type="String">A copy of format in which the format items have been replaced by the string equivalent of the corresponding instances of object arguments.</returns>
return String._toFormattedString(false, arguments);
}
$type._toFormattedString = function String$_toFormattedString(useLocale, args) {
var result = '';
var format = args[0];
for (var i = 0; ; ) {
// Find the next opening or closing brace
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if ((open < 0) && (close < 0)) {
// Not found: copy the end of the string and break
result += format.slice(i);
break;
}
if ((close > 0) && ((close < open) || (open < 0))) {
if (format.charAt(close + 1) !== '}') {
throw new Error('format stringFormatBraceMismatch');
}
result += format.slice(i, close + 1);
i = close + 2;
continue;
}
// Copy the string before the brace
result += format.slice(i, open);
i = open + 1;
// Check for double braces (which display as one and are not arguments)
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}
if (close < 0) throw new Error('format stringFormatBraceMismatch');
// Find the closing brace
// Get the string between the braces, and split it around the ':' (if any)
var brace = format.substring(i, close);
var colonIndex = brace.indexOf(':');
var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;
if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');
var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);
var arg = args[argNumber];
if (typeof (arg) === "undefined" || arg === null) {
arg = '';
}
// If it has a toFormattedString method, call it. Otherwise, call toString()
if (arg.toFormattedString) {
result += arg.toFormattedString(argFormat);
}
else if (useLocale && arg.localeFormat) {
result += arg.localeFormat(argFormat);
}
else if (arg.format) {
result += arg.format(argFormat);
}
else
result += arg.toString();
i = close + 1;
}
return result;
}
})(window);
Or you can do it like this!
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i += 2
return new_list
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
That's the SHOW CREATE TABLE query. You can query the SCHEMA TABLES, too.
SHOW CREATE TABLE YourTableName;
Just two steps needed:
Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
after setContentView().
In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />
Hope it helps and happy coding :)
If the map is to contain only entries that are known at compile time and the keys to the map are integers, then you do not need to use a map at all.
char get_value(int key)
{
switch (key)
{
case 1:
return 'a';
case 2:
return 'b';
case 3:
return 'c';
default:
// Do whatever is appropriate when the key is not valid
}
}
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
Example as per doc
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'jmZ'}}</p>
</div>`
})
export class DatePipeComponent {
today: number = Date.now();
}
Template
{{ dateObj | date }} // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }} // output is '9:43 PM'
{{ dateObj | date:'mmss' }} // output is '43:11'
{{dateObj | date: 'dd/MM/yyyy'}} // 15/06/2015
To Use in your component.
@Injectable()
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need.
}
}
In your app.module.ts
providers: [DatePipe,...]
all you have to do is use this service now.
Just to cover an edge case:) and because the question title asks (at least now) how to copy the output of a command directly to clipboard.
Often times I find it useful to copy the output of the command after it was already executed and I don’t want to or can’t execute the command again.
For this scenario, we can either use gdm or a similar mouse utility and select using the mouse. apt-get install gdm
and then either the right click or the Cntrl+Shift+c and Cntrl+Shift+v combinations for copy and paste in the terminal
Or, which is the preferred method for me (as the mouse cannot select properly inside one pane when you have multiple panes side by side and you need to select more than one line), using tmux we can copy into the tmux buffer using the standard [ , space , move to select , enter or you can select a block of code. Also this is particularly useful when you are inside one of the lanes of the cli multiplexer like tmux AND you need to select a bunch of text, but not the line numbers (my vim setup renders line numbers)
After this you can use the command:
tmux save-buffer - | xclip -i
You can of course alias it to something you like or bind directly in the tmux configuration file
This is just to give you a conceptual answer to cover this edge case when it’s not possible to execute the command again. If you need more specific code examples, let me know
Cheers
The proper syntax is (in example):
$query = mysql_query('SELECT * FROM beer ORDER BY quality');
while($row = mysql_fetch_assoc($query)) $results[] = $row;