You can use ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
ObjectClass object = objectMapper.readValue(data, ObjectClass.class);
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
<!-- Since angular2 stable release multiple directives are not supported on a single element(from the docs) still you can use it like below -->_x000D_
_x000D_
_x000D_
<ul class="list-group">_x000D_
<template ngFor let-item [ngForOf]="stuff" [ngForTrackBy]="trackBy_stuff">_x000D_
<li *ngIf="item.name" class="list-group-item">{{item.name}}</li>_x000D_
</template>_x000D_
</ul>
_x000D_
DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.
Last 5 rows retrieve in mysql
This query working perfectly
SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC
or
select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc
Solution for change TextView
width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
For those who want an elegant, bash version-independent solution (in fact should work in other modern shells) and those who love to use one-liners for quick tasks. Here we go!
ls | grep . && echo 'files found' || echo 'files not found'
(note as one of the comments mentioned, ls -al
and in fact, just -l
and -a
will all return something, so in my answer I use simple ls
This should work
<option *ngFor="let title of titleArray"
[value]="title.Value"
[attr.selected]="passenger.Title==title.Text ? true : null">
{{title.Text}}
</option>
I'm not sure the attr.
part is necessary.
Plain typo. hostspath
vs hostpath
;)
@echo off
set `hostspath`=%windir%\System32\drivers\etc\hosts
echo 62.116.159.4 ns1.intranet.de >> `%hostspath%`
echo 217.160.113.37 ns2.intranet.de >> `%hostpath%`
echo 89.146.248.4 ns3.intranet.de >> `%hostpath%`
echo 74.208.254.4 ns4.intranet.de >> `%hostpath%`
exit
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
I think your error was in calling the function.
In your HTML code, onclick
is calling the image()
function. However, in your script the function is named imgWindow()
. Try changing the onclick to imgWindow()
.
I don't do much JavaScript so if I have missed something, please let me know.
Good Luck!
Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:
.directive('changeClassOnScroll', function ($window) {
return {
restrict: 'A',
scope: {
offset: "@",
scrollClass: "@"
},
link: function(scope, element) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= parseInt(scope.offset)) {
element.addClass(scope.scrollClass);
} else {
element.removeClass(scope.scrollClass);
}
});
}
};
})
So you can use it like this:
<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>
or
<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>
To contribute my 5 cents to the thorough explanation from Amadan.
Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:
Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".
class Human:
gender
nationality
favorite_drink
core_characteristic
favorite_beverage
name
age
def love
def drink
def laugh
def do_your_special_thing
class Americans(Humans)
def drink(beverage):
if beverage != favorite_drink: print "You call that a drink?"
else: print "Great!"
class French(Humans)
def drink(beverage, cheese):
if beverage == favourite_drink and cheese == None: print "No cheese?"
elif beverage != favourite_drink and cheese == None: print "Révolution!"
class Brazilian(Humans)
def do_your_special_thing
win_every_football_world_cup()
class Germans(Humans)
def drink(beverage):
if favorite_drink != beverage: print "I need more beer"
else: print "Lecker!"
class HighSchoolStudent(Americans):
def __init__(self, name, age):
self.name = name
self.age = age
jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()
for friends in [jeff, hans, ronaldo]:
friends.laugh()
friends.drink("cola")
friends.do_your_special_thing()
print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False
Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).
But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).
So each human has a favorite_drink, but every nationality tend towards a special kind of drink.
If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink()
Method.
But that's still at the class-level and because of this it's still a generalization.
hans = German(favorite_drink = "Cola")
instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )
The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__
) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.
But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.
To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)
On the .ASPX
page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
response(data.d);
}
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>
In your .ASPX.CS
code-behind file:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");
SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
con.Open();
cmd.Parameters.AddWithValue("@Name", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}
As scoota269 says, you should use onSubmit
instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)
<form action="#" onsubmit="handle">
<input type="text" name="txt" />
</form>
<script>
function handle(e){
e.preventDefault(); // Otherwise the form will be submitted
alert("FORM WAS SUBMITTED");
}
</script>
If you want to have an event on the input-field then you need to make sure your handle()
will return false, otherwise the form will get submitted.
<form action="#">
<input type="text" name="txt" onkeypress="handle(event)" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
e.preventDefault(); // Ensure it is only this code that runs
alert("Enter was pressed was presses");
}
}
</script>
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)
By C89, variable can only be defined at the top of a block.
if (a == 1)
int b = 10; // it's just a statement, syntacitially error
if (a == 1)
{ // refer to the beginning of a local block
int b = 10; // at the top of the local block, syntacitially correct
} // refer to the end of a local block
if (a == 1)
{
func();
int b = 10; // not at the top of the local block, syntacitially error, I guess
}
svn delete --keep-local the_file
Replace
var myNewString = myOldString.replace ("username," visitorName);
with
var myNewString = myOldString.replace("username", visitorName);
Depending on the size and number of files being copied, you could copy the destination directory over the source first with "yes to all", then do the original copy you were doing, also with "yes to all" set. That should give you the same results.
Historically, 255 characters has often been the maximum length of a VARCHAR
in some DBMSes, and it sometimes still winds up being the effective maximum if you want to use UTF-8 and have the column indexed (because of index length limitations).
Your thread's locale is set to one in which the decimal mark is "," instead of ".".
Try using this:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().
Basically, a field declared as a FileField
, when accessed, gives you an instance of class FieldFile
, which gives you several methods to interact with the underlying file. So, what you need to do is:
self.license_file.save(new_name, new_contents)
where new_name
is the filename you wish assigned and new_contents
is the content of the file. Note that new_contents
must be an instance of either django.core.files.File
or django.core.files.base.ContentFile
(see given links to manual for the details).
The two choices boil down to:
from django.core.files.base import ContentFile, File
# Using File
with open('/path/to/file') as f:
self.license_file.save(new_name, File(f))
# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))
My answer is little late but simple; but may help someone in future; I did experiment with angular versions such as 4.4.3, 5.1+, 6.x, 7.x, 8.x, 9.x and 10.x using $event (latest at the moment)
Template:
<select (change)="onChange($event)">
<option *ngFor="let v of values" [value]="v.id">{{v.name}}</option>
</select>
TS
export class MyComponent {
public onChange(event): void { // event will give you full breif of action
const newVal = event.target.value;
console.log(newVal);
}
}
Jeet's answer works in PowerShell.
git grep -n <regex> $(git rev-list --all)
The following displays all files, in any commit, that contain a password
.
# Store intermediate result
$result = git grep -n "password" $(git rev-list --all)
# Display unique file names
$result | select -unique { $_ -replace "(^.*?:)|(:.*)", "" }
In my case that happened when uninstalling AspNet 5 RC1 Update 1 to update it for .Net Core 1.0 RC2. so I installed Visual Studio 2015 update 2, selected Microsoft Web Developer tools and everything went back to normal.
public class User : List<UserData>
{
public int id { get; set; }
public string screen_name { get; set; }
}
string json = client.DownloadString(url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
var Data = serializer.Deserialize<List<UserData>>(json);
keytool
comes with the Java SDK. You should find it in the directory that contains javac
, etc.
To get the iframe to always load fresh content, add the current Unix timestamp to the end of the GET parameters. The browser then sees it as a 'different' request and will seek new content.
In Javascript, it might look like:
frames['my_iframe'].location.href='load_iframe_content.php?group_ID=' + group_ID + '×tamp=' + timestamp;
If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,
mvn help:evaluate -Dexpression=settings.localRepository
The above command will scan for projects and run some tasks. Final outcome will be like below
As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository
For the sake of completeness, here is one more option.
Let's start with a definition from python docs:
slice An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (subscript) notation uses slice objects internally (or in older versions, __getslice__() and __setslice__()).
Though the slice notation is not directly applicable to iterators in general, the itertools
package contains a replacement function:
from itertools import islice
# print the 100th line
with open('the_file') as lines:
for line in islice(lines, 99, 100):
print line
# print each third line until 100
with open('the_file') as lines:
for line in islice(lines, 0, 100, 3):
print line
The additional advantage of the function is that it does not read the iterator until the end. So you can do more complex things:
with open('the_file') as lines:
# print the first 100 lines
for line in islice(lines, 100):
print line
# then skip the next 5
for line in islice(lines, 5):
pass
# print the rest
for line in lines:
print line
And to answer the original question:
# how to read lines #26 and #30
In [365]: list(islice(xrange(1,100), 25, 30, 4))
Out[365]: [26, 30]
You can use a timedelta
object:
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract)
The difference is, re.match()
misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search()
does not. :-)
More soberly, As John D. Cook remarks, re.match()
"behaves as if every pattern has ^ prepended." In other words, re.match('pattern')
equals re.search('^pattern')
. So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $
.
Frankly given the above, I think re.match()
should be deprecated. I would be interested to know reasons it should be retained.
Hello year 2010 question.
The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.
If you use array_merge()
the numeric keys will always re-index or renumbered.
If you use array_replace()
, array_replace_recursive()
it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2
as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.
Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.
/**
* Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
*
* If the another array key is string, it will be overwrite the first array.<br>
* If the another array key is integer, it will be add to first array depend on duplicated key or not.
* If it is not duplicate key with the first, the key will be preserve and add to the first array.
* If it is duplicated then it will be re-index the number append to the first array.
*
* @param array $array1 The first array is main array.
* @param array ...$arrays The another arrays to merge with the first.
* @return array Return merged array.
*/
function arrayCustomMerge(array $array1, array ...$arrays): array
{
foreach ($arrays as $additionalArray) {
foreach ($additionalArray as $key => $item) {
if (is_string($key)) {
// if associative array.
// item on the right will always overwrite on the left.
$array1[$key] = $item;
} elseif (is_int($key) && !array_key_exists($key, $array1)) {
// if key is number. this should be indexed array.
// and if array 1 is not already has this key.
// add this array with the key preserved to array 1.
$array1[$key] = $item;
} else {
// if anything else...
// get all keys from array 1 (numbers only).
$array1Keys = array_filter(array_keys($array1), 'is_int');
// next key index = get max array key number + 1.
$nextKeyIndex = (intval(max($array1Keys)) + 1);
unset($array1Keys);
// set array with the next key index.
$array1[$nextKeyIndex] = $item;
unset($nextKeyIndex);
}
}// endforeach; $additionalArray
unset($item, $key);
}// endforeach;
unset($additionalArray);
return $array1;
}// arrayCustomMerge
<?php
$array1 = [
'cat',
'bear',
'fruitred' => 'apple',
3.1 => 'dog',
null => 'null',
];
$array2 = [
1 => 'polar bear',
20 => 'monkey',
'fruitred' => 'strawberry',
'fruityellow' => 'banana',
null => 'another null',
];
// require `arrayCustomMerge()` function here.
function printDebug($message)
{
echo '<pre>';
print_r($message);
echo '</pre>' . PHP_EOL;
}
echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);
echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;
echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);
assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:
Array
(
[0] => cat
[1] => bear
[fruitred] => apple
[3] => dog
[] => null
)
array2:
Array
(
[1] => polar bear
[20] => monkey
[fruitred] => strawberry
[fruityellow] => banana
[] => another null
)
---
arrayCustomMerge:
Array
(
[0] => cat
[1] => bear
[fruitred] => strawberry
[3] => dog
[] => another null
[4] => polar bear
[20] => monkey
[fruityellow] => banana
)
Finally got working :)
using System.Net.Mail;
using System.Text;
...
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
sorry about poor spelling before
double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);
For my 2 cents Dropbox only makes sence for personal use where you don't want to bother getting a central repo host. For any professional development you'll probably create more problems than you'll solve, as have been mentioned several times in the thread already, Dropbox isn't designed for this use case. That said, a perfectly safe method to dump repositories on Dropbox without any third-party plugins or tools is to use bundles. I have the following aliases in my .gitconfig
to save typing:
[alias]
bundle-push = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle create \"$path\" --all && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
bundle-fetch = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle verify \"$path\" && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
bundle-new = "!cd \"${GIT_PREFIX:-.}\" && if [ -z \"${1:-}\" -o -z \"${2:-}\" ]; then echo \"Usage: git bundle-new <file> <remote name>\"; exit 1; elif [ -e \"$2\" ]; then echo \"File exist\"; exit 1; else git bundle create \"$2\" --all && git remote add -f \"$1\" \"$(realpath \"$2\")\"; fi #"
Example:
# Create bundle remote (in local repo)
$ git bundle-new dropbox ~/Dropbox/my-repo.bundle
# Fetch updates from dropbox
$ git bundle-fetch dropbox
# NOTE: writes over previous bundle. Thus, roughly equivalent to push --force --prune --all
$ git bundle-push
You can either use (on the h4 elements, as they are block by default)
display: inline-block;
Or you can float the elements to the left/rght
float: left;
Just don't forget to clear the floats after
clear: left;
More visual example for the float left/right option as shared below by @VSB:
<h4> _x000D_
<div style="float:left;">Left Text</div>_x000D_
<div style="float:right;">Right Text</div>_x000D_
<div style="clear: left;"/>_x000D_
</h4>
_x000D_
Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.
The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.
This question has already great answers, but here it appears that there is a slight confusion between using single equal (=
) and double equals (==
) in
if [ "$s1" == "$s2" ]
The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash
in the starting of the script and save your script as filename.bash
. To execute, use bash filename.bash
- then you have to use ==
.
If you are using sh then use #!/bin/sh
and save your script as filename.sh
. To execute use sh filename.sh
- then you have to use single =
. Avoid intermixing them.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):
class CameraControl {
zoomMode: boolean = false
press: boolean = false
sensitivity: number = 0.02
constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
renderer.domElement.addEventListener('mousemove', event => {
if(!this.press){ return }
if(event.button == 0){
camera.position.y -= event.movementY * this.sensitivity
camera.position.x -= event.movementX * this.sensitivity
} else if(event.button == 2){
camera.quaternion.y -= event.movementX * this.sensitivity/10
camera.quaternion.x -= event.movementY * this.sensitivity/10
}
updateCallback()
})
renderer.domElement.addEventListener('mousedown', () => { this.press = true })
renderer.domElement.addEventListener('mouseup', () => { this.press = false })
renderer.domElement.addEventListener('mouseleave', () => { this.press = false })
document.addEventListener('keydown', event => {
if(event.key == 'Shift'){
this.zoomMode = true
}
})
document.addEventListener('keyup', event => {
if(event.key == 'Shift'){
this.zoomMode = false
}
})
renderer.domElement.addEventListener('mousewheel', event => {
if(this.zoomMode){
camera.fov += event.wheelDelta * this.sensitivity
camera.updateProjectionMatrix()
} else {
camera.position.z += event.wheelDelta * this.sensitivity
}
updateCallback()
})
}
}
drop it in like:
this.cameraControl = new CameraControl(renderer, camera, () => {
// you might want to rerender on camera update if you are not rerendering all the time
window.requestAnimationFrame(() => renderer.render(scene, camera))
})
Controls:
Additionally:
If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:
// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)
If you're looking to re-enable the blink tag for your own browsing, you can install this simple Chrome extension I wrote: https://github.com/etlovett/Blink-Tag-Enabler-Chrome-Extension. It just hides and shows all <blink> tags on every page using setInterval.
people.OrderBy(person => person.lastname).ToList();
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;_x000D_
var audioContext = new AudioContextFunc();_x000D_
var player=new WebAudioFontPlayer();_x000D_
var instrumVox,instrumApplause;_x000D_
var drumClap,drumLowTom,drumHighTom,drumSnare,drumKick,drumCrash;_x000D_
loadDrum(21,function(s){drumClap=s;});_x000D_
loadDrum(30,function(s){drumLowTom=s;});_x000D_
loadDrum(50,function(s){drumHighTom=s;});_x000D_
loadDrum(15,function(s){drumSnare=s;});_x000D_
loadDrum(5,function(s){drumKick=s;});_x000D_
loadDrum(70,function(s){drumCrash=s;});_x000D_
loadInstrument(594,function(s){instrumVox=s;});_x000D_
loadInstrument(1367,function(s){instrumApplause=s;});_x000D_
function loadDrum(n,callback){_x000D_
var info=player.loader.drumInfo(n);_x000D_
player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function loadInstrument(n,callback){_x000D_
var info=player.loader.instrumentInfo(n);_x000D_
player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function uhoh(){_x000D_
var when=audioContext.currentTime;_x000D_
var b=0.1;_x000D_
player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*0, 60, b*1);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*3, 56, b*4);_x000D_
}_x000D_
function applause(){_x000D_
player.queueWaveTable(audioContext, audioContext.destination, instrumApplause, audioContext.currentTime, 54, 3);_x000D_
}_x000D_
function badumtss(){_x000D_
var when=audioContext.currentTime;_x000D_
var b=0.11;_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*0, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumLowTom, when+b*0, drumLowTom.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*1, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumHighTom, when+b*1, drumHighTom.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*3, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumKick, when+b*3, drumKick.zones[0].keyRangeLow, 3.5);_x000D_
player.queueWaveTable(audioContext, audioContext.destination, drumCrash, when+b*3, drumCrash.zones[0].keyRangeLow, 3.5);_x000D_
}
_x000D_
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>_x000D_
<button onclick='badumtss();'>badumtss</button>_x000D_
<button onclick='uhoh();'>uhoh</button>_x000D_
<button onclick='applause();'>applause</button>_x000D_
<br/><a href='https://github.com/surikov/webaudiofont'>More sounds</a>
_x000D_
import datetime
def date_generator():
cur = base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
while(end>base):
base = base+delta
print base
date_generator()
Here's a solution that should always work and doesn't remove the hash.
let currentPage = new URL(window.location.href);
currentPage.searchParams.set('r', (+new Date * Math.random()).toString(36).substring(0, 5));
window.location.href = currentPage.href;
What type of LayoutManager are you using for the panel you're adding the JTextField to?
Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.
See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
ps. this has nothing to do with eclipse, its java.
One line: $ran[rand(0, count($ran) - 1)]
It's called the ternary operator
. For some more info, here's another question I answered regarding this:
If you are using CSRF enter 'before'=>'csrf'
In your case
Route::get('auth/login', ['before'=>'csrf','uses' => 'Auth\AuthController@getLogin', 'as' => 'login']);
For more details view Laravel 5 Documentation Security Protecting Routes
By default, Sublime Text set 'UTF8 without BOM'
, but that wasn't specified.
The only specicified things is 'UTF8 with BOM'
.
Hope this help :)
var elArray = [];
var elObjeto = {};
elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE
elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
Example:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Or press Ctrl-Z at a raw_input()
prompt (Windows, Ctrl-Z Linux)
Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:
where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45
$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin
Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.
You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).
You can also link with .obj or other extensions if the object files have the correct format (such as COFF).
New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__
class method in addition to __init__
and have somewhat more rational low-level behavior.
Usually, you'll want to override __getattr__
(if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.
Extra info: http://www.devx.com/opensource/Article/31482/0/page/4
Cross-posting this as a consolidated reference from the SO Documentation beta which is going offline.
Cross-site scripting is the unintended execution of remote code by a web client. Any web application might expose itself to XSS if it takes input from a user and outputs it directly on a web page. If input includes HTML or JavaScript, remote code can be executed when this content is rendered by the web client.
For example, if a 3rd party side contains a JavaScript file:
// http://example.com/runme.js
document.write("I'm running");
And a PHP application directly outputs a string passed into it:
<?php
echo '<div>' . $_GET['input'] . '</div>';
If an unchecked GET parameter contains <script src="http://example.com/runme.js"></script>
then the output of the PHP script will be:
<div><script src="http://example.com/runme.js"></script></div>
The 3rd party JavaScript will run and the user will see "I'm running" on the web page.
As a general rule, never trust input coming from a client. Every GET parameter, POST or PUT content, and cookie value could be anything at all, and should therefore be validated. When outputting any of these values, escape them so they will not be evaluated in an unexpected way.
Keep in mind that even in the simplest applications data can be moved around and it will be hard to keep track of all sources. Therefore it is a best practice to always escape output.
PHP provides a few ways to escape output depending on the context.
PHPs Filter Functions allow the input data to the php script to be sanitized or validated in many ways. They are useful when saving or outputting client input.
htmlspecialchars
will convert any "HTML special characters" into their HTML encodings, meaning they will then not be processed as standard HTML. To fix our previous example using this method:
<?php
echo '<div>' . htmlspecialchars($_GET['input']) . '</div>';
// or
echo '<div>' . filter_input(INPUT_GET, 'input', FILTER_SANITIZE_SPECIAL_CHARS) . '</div>';
Would output:
<div><script src="http://example.com/runme.js"></script></div>
Everything inside the <div>
tag will not be interpreted as a JavaScript tag by the browser, but instead as a simple text node. The user will safely see:
<script src="http://example.com/runme.js"></script>
When outputting a dynamically generated URL, PHP provides the urlencode
function to safely output valid URLs. So, for example, if a user is able to input data that becomes part of another GET parameter:
<?php
$input = urlencode($_GET['input']);
// or
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_URL);
echo '<a href="http://example.com/page?input="' . $input . '">Link</a>';
Any malicious input will be converted to an encoded URL parameter.
Sometimes you will want to send HTML or other kind of code inputs. You will need to maintain a list of authorised words (white list) and un-authorized (blacklist).
You can download standard lists available at the OWASP AntiSamy website. Each list is fit for a specific kind of interaction (ebay api, tinyMCE, etc...). And it is open source.
There are libraries existing to filter HTML and prevent XSS attacks for the general case and performing at least as well as AntiSamy lists with very easy use. For example you have HTML Purifier
This XPath:
count(//Property[long = '11007'])
returns the same value as:
count(//Property/long[text() = '11007'])
...except that the first counts Property
nodes that match the criterion and the second counts long
child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])
because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])
Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)
You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])
Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long
element.
I had to add the multiply by -1 *
to the sum of the status bar and the navigation bar, because it was going that height off the screen,
self.tableView.setContentOffset(CGPointMake(0 , -1 *
(self.navigationController!.navigationBar.height +
UIApplication.sharedApplication().statusBarFrame.height) ), animated:true)
if you want to change all the keys:
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
if you want to change single key: You can go with any of the above suggestion.
There is no callback. It's like following a link.
If you want to capture the server response, use AJAX or post it to an Iframe and grab what appears there after the iframe's onload()
event.
Use --build-arg
with each argument.
If you are passing two argument then add --build-arg
with each argument like:
docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .
In my case the problem was I was using Virtual environment
which didn't have access to global site-packages. Thus, the interpreter was not aware of the newly installed packages.
To resolve the issue, just edit or recreate your virtual interpreter and tick the Inherit global site-packages
option.
This worked for me, can also be "borrowed" from the design view, make changes -> right click -> generate change script.
BEGIN TRANSACTION
GO
ALTER TABLE dbo.YOURTABLE ADD
YOURCOLUMN bit NOT NULL CONSTRAINT DF_YOURTABLE_YOURCOLUMN DEFAULT 0
GO
COMMIT
onchange
will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.
So it is better to use onblur
event or on submitting the form.
function checkTextField(field) {_x000D_
document.getElementById("error").innerText =_x000D_
(field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
This questions is already answered here. Just put height: 100%
in both the div
and the container td
.
I tried to connect from localhost (mac) to a postgres container. I changed the port in the docker-compose file from 5432 to 3306 and started the container. No idea why I did it :|
Then I tried to connect to postgres via PSequel and adminer and the connection could not be established.
After switching back to port 5432 all works fine.
db:
image: postgres
ports:
- 5432:5432
restart: always
volumes:
- "db_sql:/var/lib/mysql"
environment:
POSTGRES_USER: root
POSTGRES_PASSWORD: password
POSTGRES_DB: postgres_db
This was my experience I wanted to share. Perhaps someone can make use of it.
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
An excellent and very fast file search utility, Agent Ransack, supports regular expression searching. It's primarily a GUI utility, but a command-line interface is also available.
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.
As I understand, you want the average value for each id at each pass. The solution is
SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;
Substract a day from the first of next month:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
Also, in case you need it to work for December too:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.
ps -A | grep [f]irefox | awk '{print $1}'
SELECT * from table where field in (SELECT distinct field from table)
If you know the the name of the file and if you always want to download that specific file, then you can easily get the ID and other attributes for your desired file from: https://developers.google.com/drive/v2/reference/files/list (towards the bottom you will find a way to run queries). In the q field enter title = 'your_file_name' and run it. You should see some result show up right below and within it should be an "id" field. That is the id you are looking for.
You can also play around with additional parameters from: https://developers.google.com/drive/search-parameters
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
It describes the external format of data passed to and from service operations
It defines the structure and types of data exchanged in service messages
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
];_x000D_
_x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
@SolutionYogi's answer works like a charm, but it seems that using $.each is less straightforward and efficient than directly appending listitems :
var mylist = $('#list');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
mylist.empty().append(listitems);
First of definition. For me unmanaged resource means some class, which implements IDisposable interface or something created with usage of calls to dll. GC doesn't know how to deal with such objects. If class has for example only value types, then I don't consider this class as class with unmanaged resources. For my code I follow next practices:
public class SomeClass : IDisposable
{
/// <summary>
/// As usually I don't care was object disposed or not
/// </summary>
public void SomeMethod()
{
if (_disposed)
throw new ObjectDisposedException("SomeClass instance been disposed");
}
public void Dispose()
{
Dispose(true);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)//we are in the first call
{
}
_disposed = true;
}
}
No. The most similar concept is most likely a StopIteration exception.
If you are looking for a simple way, here it is.
Create a utility class like this,
public class ApplicationUtils {
/**
* Sets the boolean preference value
*
* @param context the current context
* @param key the preference key
* @param value the value to be set
*/
public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(key, value).apply();
}
/**
* Get the boolean preference value from the SharedPreference
*
* @param context the current context
* @param key the preference key
* @return the the preference value
*/
public static boolean getBooleanPreferenceValue(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, false);
}
}
At your Main Activity, onCreate()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
require_once('db/connect.php');
//rand(1000000 , 9999999);
$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];
do
{
array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));
/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);
for ($i=0; $i < $row_counter; $i++)
{
$current_row = $ids_array[$i];
$rand = rand(1000000 , 9999999);
mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}
I assume that you have a similar view regarding the zoom functionality as I have in this picture:
Now if you mark one of the Zoom In
/Zoom Out
lines and choose Add Keyboard Shortcut
:
You will find that this particular shortcut Numpad +
is already occupied so there is a conflict:
So you'll just have assign this Zoom In
/Zoom Out
to some other keyboard shortcut:
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
Using newInstance()
directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...)
with the corresponding exceptions.
The easiest (but somewhat dirty) way:
String result = "" + a + b + c + d + e
Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.
For conciseness I'd use the SeriesGroupBy:
In [11]: c = df.groupby(['state', 'office_id'])['sales'].sum().rename("count")
In [12]: c
Out[12]:
state office_id
AZ 2 925105
4 592852
6 362198
CA 1 819164
3 743055
5 292885
CO 1 525994
3 338378
5 490335
WA 2 623380
4 441560
6 451428
Name: count, dtype: int64
In [13]: c / c.groupby(level=0).sum()
Out[13]:
state office_id
AZ 2 0.492037
4 0.315321
6 0.192643
CA 1 0.441573
3 0.400546
5 0.157881
CO 1 0.388271
3 0.249779
5 0.361949
WA 2 0.411101
4 0.291196
6 0.297703
Name: count, dtype: float64
For multiple groups you have to use transform (using Radical's df):
In [21]: c = df.groupby(["Group 1","Group 2","Final Group"])["Numbers I want as percents"].sum().rename("count")
In [22]: c / c.groupby(level=[0, 1]).transform("sum")
Out[22]:
Group 1 Group 2 Final Group
AAHQ BOSC OWON 0.331006
TLAM 0.668994
MQVF BWSI 0.288961
FXZM 0.711039
ODWV NFCH 0.262395
...
Name: count, dtype: float64
This seems to be slightly more performant than the other answers (just less than twice the speed of Radical's answer, for me ~0.08s).
On your project folder, open the command terminal and type
ng -v
it will give you a list of items, in that you will be able to see the angular version. See the screenshot.
Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.
ex.
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
Use CSS position: absolute;
followed by top: 0px; left 0px;
in the style
attribute of each DIV. Replace the pixel values with whatever you want.
You can use z-index: x;
to set the vertical "order" (which one is "on top"). Replace x
with a number, higher numbers are on top of lower numbers.
Here is how your new code would look:
<div>
<div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
sudo chown -R yourname:www-data cake
then
sudo chmod -R g+s cake
First command changes owner and group.
Second command adds s attribute which will keep new files and directories within cake having the same group permissions.
var test = $('input[name="testing"]:hidden');
test.val('work!');
Here is the complete C# 7 solution...
switch (value)
{
case var s when new[] { 1,2,3 }.Contains(s):
// Do something
break;
case var s when new[] { 4,5,6 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
It works with strings too...
switch (mystring)
{
case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):
// Do something
break;
...
}
In my case, there was something wrong with the .NET Core Windows Hosting Bundle installation.
I had that installed and had restarted IIS using ("net stop was /y" and "net start w3svc") after installation, but I would get that 500.19 error with Error Code 0x8007000d and Config Source -1: 0:.
I managed to resolve the issue by repairing the .NET Core Windows Hosting Bundle installation and restarting IIS using the commands I mentioned above.
Hope this helps someone!
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
Resetting IIS
a. From the Start menu, choose All Programs, and then choose Accessories. b. Right-click Command Prompt, and then choose Run as administrator.
At the command prompt, type the following command to change to the Microsoft.NET\Framework64\v4.0.30319 folder, and then press Enter.
cd\Windows\Microsoft.NET\Framework64\v4.0.30319
At the command prompt, type the following command, and then press Enter.
aspnet_regiis.exe -iru
At the command prompt, type the following command, and then press Enter. iisreset
Using sed
, if you don't know what the last character actually is:
$ grep company_name file.txt | cut -d '=' -f2 | sed 's/.$//'
"Abc Inc"
Replace with:
$('#something').click(function() {
location.reload();
});
EDIT (2019) This answer is now pretty redundant but there is another answer with more relevant information.
It rather depends on the web server and web browser:
Internet explorer All versions 2GB-1
Mozilla Firefox All versions 2GB-1
IIS 1-5 2GB-1
IIS 6 4GB-1
Although IIS only support 200KB by default, the metabase needs amending to increase this.
http://www.motobit.com/help/scptutl/pa98.htm
The POST method itself does not have any limit on the size of data.
This shows the number of connections per each DB:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
And this gives the total:
SELECT
COUNT(dbid) as TotalConnections
FROM
sys.sysprocesses
WHERE
dbid > 0
If you need more detail, run:
sp_who2 'Active'
Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)
npm start -- --port "port number"
Context
means current.
Context
use to do operation for current screen.
ex.
1. getApplicationContext()
2. getContext()
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
Not an answer to the original question. But this might help someone.
To see the changes you have done (know which files are marked as --assume-unchanged)
git ls-files -v
The resulted list of files will have a prefix with one character (ex : H or h) If it is a lowercase (i.e. h) then the file was marked --assume-unchanged
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
If the table has an index which you can iterate over I would put update top(10000)
statement in a while loop moving over the data. That would keep the transaction log slim and won't have such a huge impact on the disk system. Also, I would recommend to play with maxdop
option (setting it closer to 1).
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
See the doc : it will close all running tasks using the executable file something.exe
, more or less like linux' killall
I got the top answer working (can't reply yet) after one small edit
This did not work for me:
FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl
The first single quote for each string should be changed to a backtick (`) like this:
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
After the change I run:
sudo sendmailconfig
And I'm in business :)
You can do it in a single query:
Select t.Id, t.title, z.dupCount
From yourtable T
Join
(select title, Count (*) dupCount
from yourtable
group By title
Having Count(*) > 1) z
On z.title = t.Title
order By dupCount Desc
On the side, a trick that can be useful:
If you hold your multiple strings in a TStrings, you just have to use the Text property of the TStrings like in the following example.
Label1.Caption := Memo1.Lines.Text;
And you'll get your multi-line label...
REST stands for representational state transfer. That means that state itself is not transferred but a mere representation of it is. The most common example is a pure HTML server based app (no javascript). The browser knows nothing about the application itself but through links and resources, the server is able transfer the state of the application to the browser. Where a button would normally change a state variable (e.g. page open) in a regular windows application, in the browser you have a link that represents such a state change.
The idea is to use hypermedia. And perhaps to create new hypermedia types. Potentially we can expand the browser with javascript/AJAX and create new custom hypermedia types. And we would have a true REST application.
This is my short version of what REST stands for, the problem is that it is hard to implement. I personally say RESTful, when I want to make reference to the REST principles but I know I am not really implementing the whole concept of REST. We don't really say SOAPful, because you either use SOAP or not. I think most people don't do REST the way it was envisioned by it's creator Roy Fielding, we actually implement RESTful or RESTlike architectures. You can see his dissertation, and you will find the REST acronym but not the word RESTful.
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
I hope this answer isn't late. Because the gallery widget doesn't support multiple selection by default, but you can custom the gridview which accepted your multiselect intent. The other option is to extend the gallery view and add in your own code to allow multiple selection.
This is the simple library can do it: https://github.com/luminousman/MultipleImagePick
Update:
From @ilsy's comment, CustomGalleryActivity in this library use manageQuery
, which is deprecated, so it should be changed to getContentResolver().query()
and cursor.close()
like this answer
name() is literally the textual name in the java code of the enum. That means it is limited to strings that can actually appear in your java code, but not all desirable strings are expressible in code. For example, you may need a string that begins with a number. name() will never be able to obtain that string for you.
To connect to cmd in a Windows container, use
docker exec -it d8c25fde2769 cmd
Where d8c25fde2769 is the container id.
I think the root for this confusion is well explained in this wikipedia article.
While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.
If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon
, too.
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__))
or #pragma pack(1)
, what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.
Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align
option, it isn't enabled by default nor with -Wall
or -Wextra
. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.
Consider the following:
struct __attribute__((__packed__)) my_struct {
char c;
int i;
};
struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;
Here, the type of a
is a packed struct (as defined above). Similarly, b
is a pointer to a packed struct. The type of of the expression a.i
is (basically) an int l-value with 1 byte alignment. c
and d
are both normal int
s. When reading a.i
, the compiler generates code for unaligned access. When you read b->i
, b
's type still knows it's packed, so no problem their either. e
is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i
, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall
or -Wextra
).
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
I tested this command:
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 19 && adb shell input keyevent 19 && adb shell input keyevent 23
and only works on window's prompt, maybe because of some driver
The adb shell svc wifi enable|disable
solution only works with root permissions.
Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
Why not try .test()
? ... Try its and best boolean (true or false):
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)');
return results.test(window.location.href);
}
Tutorial: http://www.w3schools.com/jsref/jsref_regexp_test.asp
The error you mean is due to missing additional include path. Try adding it with: INCLUDEPATH += C:\path\to\include\files\ Hope it works. Regards.
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.
This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.
NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.
NOTE: The only sandbox setting available is now IFRAME
. I you want to use an onsubmit
attribute in the beginning form tag: <form onsubmit="myFunctionName()">
, it may cause the form to disappear from the screen after the form submission.
If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.
If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault();
to your code in the submit event handler function. Or you'll need to use the google.script.run
client side API.
A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.
This example shows an upload form with Google Apps Script HTML Service.
There are various ways to end up at the Google Apps Script code editor.
I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.
This example is a "Stand Alone" app with HTML Service.
HTML Service - Create a web app using HTML, CSS and Javascript
Google Apps Script only has two types of files inside of a Project
:
Script files have a .gs
extension. The .gs
code is a server side code written in JavaScript, and a combination of Google's own API.
Copy and Paste the following code
Save It
Create the first Named Version
Publish it
Set the Permissions
and you can start using it.
Code.gs file (Created by Default)
//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to
function doGet(e) {
return HtmlService.createTemplateFromFile('Form')
.evaluate() // evaluate MUST come before setting the Sandbox mode
.setTitle('Name To Appear in Browser Tab')
.setSandboxMode();//Defaults to IFRAME which is now the only mode available
}
function processForm(theForm) {
var fileBlob = theForm.picToLoad;
Logger.log("fileBlob Name: " + fileBlob.getName())
Logger.log("fileBlob type: " + fileBlob.getContentType())
Logger.log('fileBlob: ' + fileBlob);
var fldrSssn = DriveApp.getFolderById(Your Folder ID);
fldrSssn.createFile(fileBlob);
return true;
}
Create an html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1 id="main-heading">Main Heading</h1>
<br/>
<div id="formDiv">
<form id="myForm">
<input name="picToLoad" type="file" /><br/>
<input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
<script>
function picUploadJs(frmData) {
document.getElementById('status').style.display = 'inline';
google.script.run
.withSuccessHandler(updateOutput)
.processForm(frmData)
};
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput() {
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = "The File was UPLOADED!";
}
</script>
</html>
This is a full working example. It only has two buttons and one <div>
element, so you won't see much on the screen. If the .gs
script is successful, true is returned, and an onSuccess
function runs. The onSuccess function (updateOutput) injects inner HTML into the div
element with the message, "The File was UPLOADED!"
File
, Manage Version
then Save the first VersionPublish
, Deploy As Web App
then UpdateWhen you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.
The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.
Another example of using the HTML Service can be seen at this link here on StackOverflow:
NOTES about deprecated UI Service:
There is a difference between the UI Service, and the Ui getUi()
method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.
Google Documentation - UI Service
Even though the UI Service is deprecated, there is a getUi()
method of the spreadsheet class to add custom menus, which is NOT deprecated:
Spreadsheet Class - Get UI method
I mention this because it could be confusing because they both use the terminology UI.
The UI method returns a Ui
return type.
You can add HTML to a UI Service, but you can't use a <button>
, <input>
or <script>
tag in the HTML with the UI Service.
Here is a link to a shared Apps Script Web App file with an input form:
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
I installed GitHubDesktop
on Windows 10 and git.exe
is located there:
C:\Users\john\AppData\Local\GitHubDesktop\app-0.7.2\resources\app\git\cmd\git.exe
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
For me, the only way on SQL 2008 R2 was this :
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE **WITH OVERRIDE**
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE **WITH OVERRIDE**
First use:
yarn application -list
Note down the application id Then to kill use:
yarn application -kill application_id
from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s
Where db
is your DbContext
. Generated query will look like (sample for EF6):
SELECT [Extent1].[Id] AS [Id]
-- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1
You can also type "top" and look at the list of running processes.
A gc-friendly piece of code:
public static<X> X[] arrayOfNotNull(X[] array) {
for (int p=0, N=array.length; p<N; ++p) {
if (array[p] == null) {
int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
X[] res = Arrays.copyOf(array, m);
for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
return res;
}
}
return array;
}
It returns the original array if it contains no nulls. It does not modify the original array.
In my case, the accepted answer is not working, It stops Exception but it causes some inconsistency in my List. The following solution is perfectly working for me.
List<String> list = new ArrayList<>();
List<String> itemsToRemove = new ArrayList<>();
for (String value: list) {
if (value.length() > 5) { // your condition
itemsToRemove.add(value);
}
}
list.removeAll(itemsToRemove);
In this code, I have added the items to remove, in another list and then used list.removeAll
method to remove all required items.
This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:
>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']
Another way is to use the filter
function. In Python 2:
>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']
In Python 3, it returns an iterator instead of a list, but you can cast it:
>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']
Though it's better practice to use a comprehension.
This the correct command that you need to install opencv
pip install opencv-python
if you get any error when you are trying to install the "opencv-python" package in pycharm, make sure that you have added your python path to 'System Variables' section of Environment variables in Windows. And also check whether you have configured a valid interpreter for your project
Making your own itoa
is also easy, try this :
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
or use the standard sprintf()
function.
You could try sorting the array based on a property, like so:
carBrands = carBrands.sort(function(x,y){
return (x == y) ? 0 : (x > y) ? 1 : -1;
});
Then you can use an iterative routine to check whether
carBrands[Math.floor(carBrands.length/2)]
// change carBrands.length to a var that keeps
// getting divided by 2 until result is the target
// or no valid target exists
is greater or lesser than the target, and so on, which will let you go through the array quickly to find whether the object exists or not.
eval "local count = redis.call('scan', 0, 'match', 'key:*:key', 'count', 10000) if count ~= 0 then return #count[2] end " 0
eval "local count = redis.call('sscan', 'key.key:all', 0, 'match', '*', 'count', 1000000) if count ~= 0 then return #count[2] end " 0
I think you will want to use ThreadSafeClientConnManager.
You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html
Or in the AndroidHttpClient
which uses it internally.
I am set Tooltips On My Working Project That Is 100% Working
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
visibility: hidden;_x000D_
width: 120px;_x000D_
background-color: black;_x000D_
color: #fff;_x000D_
text-align: center;_x000D_
border-radius: 6px;_x000D_
padding: 5px 0;_x000D_
_x000D_
/* Position the tooltip */_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
An Euler path is a path that passes through every edge exactly once. If it ends at the initial vertex then it is an Euler cycle.
A Hamiltonian path is a path that passes through every vertex exactly once (NOT every edge). If it ends at the initial vertex then it is a Hamiltonian cycle.
In an Euler path you might pass through a vertex more than once.
In a Hamiltonian path you may not pass through all edges.
You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;
Here's a simple example:
SELECT id, 1 AS sort_order
FROM b
UNION
SELECT id, 2 AS sort_order
FROM a
MINUS
SELECT id, 2 AS sort_order
FROM b
ORDER BY 2;
Pending Intent is an intent who provides all permission to other application to do a particular works. When the main activity is destroyed, Android OS takes back the permission from it.
Also please explain why encoding should be taken into consideration. Can't I simply get what bytes the string has been stored in? Why this dependency on encoding?!!!
Because there is no such thing as "the bytes of the string".
A string (or more generically, a text) is composed of characters: letters, digits, and other symbols. That's all. Computers, however, do not know anything about characters; they can only handle bytes. Therefore, if you want to store or transmit text by using a computer, you need to transform the characters to bytes. How do you do that? Here's where encodings come to the scene.
An encoding is nothing but a convention to translate logical characters to physical bytes. The simplest and best known encoding is ASCII, and it is all you need if you write in English. For other languages you will need more complete encodings, being any of the Unicode flavours the safest choice nowadays.
So, in short, trying to "get the bytes of a string without using encodings" is as impossible as "writing a text without using any language".
By the way, I strongly recommend you (and anyone, for that matter) to read this small piece of wisdom: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes
standard module, so it does not require big dependencies. It is OS independant and its use is made easy:
from mss import mss
with mss() as sct:
sct.shot()
And just find the screenshot.png
file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot
objects and OpenCV/Numpy/PIL/etc..
If you are using System.Text.Json
then you can use [JsonIgnore]
.
FQ: System.Text.Json.Serialization.JsonIgnoreAttribute
Official Microsoft Docs: JsonIgnoreAttribute
As stated here:
The library is built-in as part of the .NET Core 3.0 shared framework.
For other target frameworks, install the System.Text.Json NuGet package. The package supports:
- .NET Standard 2.0 and later versions
- .NET Framework 4.6.1 and later versions
- .NET Core 2.0, 2.1, and 2.2
You could try the following:
import matplotlib.pyplot as plt
import numpy as np
def plot_figures(figures, nrows = 1, ncols=1):
"""Plot a dictionary of figures.
Parameters
----------
figures : <title, figure> dictionary
ncols : number of columns of subplots wanted in the display
nrows : number of rows of subplots wanted in the figure
"""
fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
for ind,title in zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
axeslist.ravel()[ind].set_title(title)
axeslist.ravel()[ind].set_axis_off()
plt.tight_layout() # optional
# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}
# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)
plt.show()
However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.
I hope this helps.
By pretty-print, I assume you mean indented, like so
{
"data": 1234
}
rather than
{"data":1234}
The easiest way to do this is with MarshalIndent
, which will let you specify how you would like it indented via the indent
argument. Thus, json.MarshalIndent(data, "", " ")
will pretty-print using four spaces for indentation.
You can also upload using HTML5. You can use this AJAX uploader.
The JS code is basically:
$scope.doPhotoUpload = function () {
// ..
var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
myUploader.send();
// ..
}
Which reads from an HTML input element
<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">
This one seems to be a better fit:
<#if userName?has_content>
... do something
</#if>
http://freemarker.sourceforge.net/docs/ref_builtins_expert.html
Integer value of ARGB color to hexadecimal string:
String hex = Integer.toHexString(color); // example for green color FF00FF00
Hexadecimal string to integer value of ARGB color:
int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);
public table2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 485, 218);
setTitle("jtable");
getContentPane().setLayout(null);
String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
{ "Row2/1", "Row2/2", "Row2/3" },
{ "Row3/1", "Row3/2", "Row3/3" },
{ "Row4/1", "Row4/2", "Row4/3" }, };
String header[] = { "Column 1", "Column 2", "Column 3" };
// Table
JTable table = new JTable(data,header);
// ScrollPane
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(36, 37, 407, 79);
getContentPane().add(scrollPane);
}
}
try this!!
The naive way to do it is:
int myRand = rand() % 66; // for 0-65
This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.
To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:
rand() | rand() % 3
---------+------------
0 | 0
1 | 1
2 | 2
3 | 0
See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.
There are various ways to get around this problem; see here for an explanation of how Java's Random
handles it.
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };
There are two options you have:
Update the model in-memory, and save (plain javascript array.push):
person.friends.push(friend);
person.save(done);
or
PersonModel.update(
{ _id: person._id },
{ $push: { friends: friend } },
done
);
I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).
However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.
If you are using Bootstrap 4:
<ol class="font-weight-bold">
<li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
<li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
</ol>
I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
Click "query tool" button in the list of "tool".
And then click the "open file" image button in the tool bar.
You have something like
class B
{
A * a;
}
B * b = new B;
b->a = new A;
If you then call delete b;
, nothing happens to a, and you have a memory leak. Trying to remember to delete b->a;
is not a good solution, but there are a couple of others.
B::~B() {delete a;}
This is a destructor for B that will delete a. (If a is 0, that delete does nothing. If a is not 0 but doesn't point to memory from new, you get heap corruption.)
auto_ptr<A> a;
...
b->a.reset(new A);
This way you don't have a as a pointer, but rather an auto_ptr<> (shared_ptr<> will do as well, or other smart pointers), and it is automatically deleted when b is.
Either of these ways works well, and I've used both.
Got this error on eclipse IDE version 4.10, Spring boot 2.2.0.M4, changed the Spring boot version to 2.2.0.M2 (after many other solutions recommended and it solved the error). Maybe something missing or broken in the latest version of Spring boot starter project module maven POM.
Using T-SQL:
My job is executing stored procedure. You can easy change @command
to run your sql.
EXEC msdb.dbo.sp_add_job
@job_name = N'MakeDailyJob',
@enabled = 1,
@description = N'Procedure execution every day' ;
EXEC msdb.dbo.sp_add_jobstep
@job_name = N'MakeDailyJob',
@step_name = N'Run Procedure',
@subsystem = N'TSQL',
@command = 'exec BackupFromConfig';
EXEC msdb.dbo.sp_add_schedule
@schedule_name = N'Everyday schedule',
@freq_type = 4, -- daily start
@freq_interval = 1,
@active_start_time = '230000' ; -- start time 23:00:00
EXEC msdb.dbo.sp_attach_schedule
@job_name = N'MakeDailyJob',
@schedule_name = N'Everyday schedule' ;
EXEC msdb.dbo.sp_add_jobserver
@job_name = N'MakeDailyJob',
@server_name = @@servername ;
If you are using Chromium on Ubuntu using the nightly ppa, then you should have the chromium-browser-inspector
Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.
Run script.
Alt+PgDn - puts you in Script Output panel.
Ctrl+Shift+D - clears panel.
Alt+PgUp - puts you back in editor panel.
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src
attribute.
$("#myiframe").attr("src", "newwebpage.html");
Use the rawurlencode
function instead.
If you want to print the picture using imshow() you also execute plt.show()
Little late to the party, but here goes nothing...
function isEmailValid(emailAdress) {
var EMAIL_REGEXP = new RegExp('^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$', 'i');
return EMAIL_REGEXP.test(emailAdress)
}
I find the accepted answer, and all the others strange, since they pass self
to an abstract class. An abstract class is not instantiated so can't have a self
.
So try this, it works.
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def foo():
"""An abstract method. No need to write pass"""
class Derived(Abstract):
def foo(self):
print('Hooray!')
FOO = Derived()
FOO.foo()
you can't call sendRedirect(), after you have already used forward(). So, you get that exception.
A little late to the party, found this while looking for an example of the marker click event. The undefined error the original poster got is because the onClick function is referred to before it's defined. Swap line 2 and 3 and it should work.
Is something like this what you're looking for?
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
Usage:
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:
>>> import array
>>> a1 = array.array('B', 'Hello, World!')
>>> a1
array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
>>> a2 = array.array('B', ('secret'*3))
>>> for i in range(len(a1)):
a1[i] ^= a2[i]
>>> a1.tostring()
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
BLOB
primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB
intended to retain character-based data.
Here's the Query Analyzer template for an in-line function - it returns 2 values by default:
-- =============================================
-- Create inline function (IF)
-- =============================================
IF EXISTS (SELECT *
FROM sysobjects
WHERE name = N'<inline_function_name, sysname, test_function>')
DROP FUNCTION <inline_function_name, sysname, test_function>
GO
CREATE FUNCTION <inline_function_name, sysname, test_function>
(<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>)
RETURNS TABLE
AS
RETURN SELECT @p1 AS c1,
@p2 AS c2
GO
-- =============================================
-- Example to execute function
-- =============================================
SELECT *
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>
(<value_for_@param1, , 1>,
<value_for_@param2, , 'a'>)
GO
This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
s.Name, t.Name
If you want to separate table space from index space, you need to use AND i.index_id IN (0,1)
for the table space (index_id = 0
is the heap space, index_id = 1
is the size of the clustered index = data pages) and AND i.index_id > 1
for the index-only space
Use the ArrayList copy constructor, then sort that.
List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);
After making the copy, any changes to newList do not affect oldList.
Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.
Another weird subtle difference on GitHub is that changes to forks are not counted in your activity log until your changes are pulled into the original repo. What's more, to change a fork into a proper clone, you have to contact Github support, apparently.
From Why are my contributions not showing up:
Commit was made in a fork
Commits made in a fork will not count toward your contributions. To make them count, you must do one of the following:
Open a pull request to have your changes merged into the parent repository. To detach the fork and turn it into a standalone repository on GitHub, contact GitHub Support. If the fork has forks of its own, let support know if the forks should move with your repository into a new network or remain in the current network. For more information, see "About forks."
Probably the best way is to handle the trailing white spaces when you read your data file. If you use read.csv
or read.table
you can set the parameterstrip.white=TRUE
.
If you want to clean strings afterwards you could use one of these functions:
# Returns string without leading white space
trim.leading <- function (x) sub("^\\s+", "", x)
# Returns string without trailing white space
trim.trailing <- function (x) sub("\\s+$", "", x)
# Returns string without leading or trailing white space
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
To use one of these functions on myDummy$country
:
myDummy$country <- trim(myDummy$country)
To 'show' the white space you could use:
paste(myDummy$country)
which will show you the strings surrounded by quotation marks (") making white spaces easier to spot.
You can use:
EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal
AVOID USING:
() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=
I was getting the same error. I was using Intellij IDEA and I wanted to run Spring boot application. So, solution from my side is as follow.
Go to Run menu -> Run configuration -> Click on Add button from the left panel and select maven -> In parameters add this text -> spring-boot:run
Now press Ok and Run.
It seems that the original test case is wrong.
I can confirm that the selector #my_parent_element *
works with unbind()
.
Let's take the following html as an example:
<div id="#my_parent_element">
<div class="div1">
<div class="div2">hello</div>
<div class="div3">my</div>
</div>
<div class="div4">name</div>
<div class="div5">
<div class="div6">is</div>
<div class="div7">
<div class="div8">marco</div>
<div class="div9">(try and click on any word)!</div>
</div>
</div>
</div>
<button class="unbind">Now, click me and try again</button>
And the jquery bit:
$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
alert('hi!');
})
$('button.unbind').click(function() {
$('#my_parent_element *').unbind('click');
})
You can try it here: http://jsfiddle.net/fLvwbazk/7/
I solved it by adding this to the /etc/profile - system wide (or to user local .profile, or _.bash_profile_):
# SSH-AGENT
#!/usr/bin/env bash
SERVICE='ssh-agent'
WHOAMI=`who am i |awk '{print $1}'`
if pgrep -u $WHOAMI $SERVICE >/dev/null
then
echo $SERVICE running.
else
echo $SERVICE not running.
echo starting
ssh-agent > ~/.ssh/agent_env
fi
. ~/.ssh/agent_env
This starts a new ssh-agent if not running for the current user, or re-sets the ssh-agent env parameter if running.
You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.
Here is the Kotlin solution:
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
return super.onKeyUp(keyCode, event)
}
if (mWebView.canGoBack()) {
mWebView.goBack()
} else {
finish()
}
return true
}
Well you missed quotation mark around your string selectcard
it should be "selectcard"
if (card.value == selectcard)
should be
if (card.value == "selectcard")
Here is complete code for that
function validate()
{
var ddl = document.getElementById("cardtype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "selectcard")
{
alert("Please select a card type");
}
}
try
pip3 install --user --upgrade pandas
To run the command without a shell, pass the command as a list and implement the redirection in Python using [subprocess]
:
#!/usr/bin/env python
import subprocess
with open('test.nt', 'wb', 0) as file:
subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
stdout=file)
Note: no > test.nt
at the end. stdout=file
implements the redirection.
To run the command using the shell in Python, pass the command as a string and enable shell=True
:
#!/usr/bin/env python
import subprocess
subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
shell=True)
Here's the shell is responsible for the output redirection (> test.nt
is in the command).
To run a bash command that uses bashisms, specify the bash executable explicitly e.g., to emulate bash process substitution:
#!/usr/bin/env python
import subprocess
subprocess.check_call('program <(command) <(another-command)',
shell=True, executable='/bin/bash')
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));
Use the >>
operator to append text to a file.