Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road... probably me!
I typed in
instead of of
in the ngFor expression.
Befor 2-beta.17, it should be:
<div *ngFor="#talk of talks">
As of beta.17, use the let
syntax instead of #
. See the UPDATE further down for more info.
Note that the ngFor syntax "desugars" into the following:
<template ngFor #talk [ngForOf]="talks">
<div>...</div>
</template>
If we use in
instead, it turns into
<template ngFor #talk [ngForIn]="talks">
<div>...</div>
</template>
Since ngForIn
isn't an attribute directive with an input property of the same name (like ngIf
), Angular then tries to see if it is a (known native) property of the template
element, and it isn't, hence the error.
UPDATE - as of 2-beta.17, use the let
syntax instead of #
. This updates to the following:
<div *ngFor="let talk of talks">
Note that the ngFor syntax "desugars" into the following:
<template ngFor let-talk [ngForOf]="talks">
<div>...</div>
</template>
If we use in
instead, it turns into
<template ngFor let-talk [ngForIn]="talks">
<div>...</div>
</template>
If you can give up the scales/axis labels, you can rescale the data to (0, 1) interval. This works for example for different 'wiggle' trakcs on chromosomes, when you're generally interested in local correlations between the tracks and they have different scales (coverage in thousands, Fst 0-1).
# rescale numeric vector into (0, 1) interval
# clip everything outside the range
rescale <- function(vec, lims=range(vec), clip=c(0, 1)) {
# find the coeficients of transforming linear equation
# that maps the lims range to (0, 1)
slope <- (1 - 0) / (lims[2] - lims[1])
intercept <- - slope * lims[1]
xformed <- slope * vec + intercept
# do the clipping
xformed[xformed < 0] <- clip[1]
xformed[xformed > 1] <- clip[2]
xformed
}
Then, having a data frame with chrom
, position
, coverage
and fst
columns, you can do something like:
ggplot(d, aes(position)) +
geom_line(aes(y = rescale(fst))) +
geom_line(aes(y = rescale(coverage))) +
facet_wrap(~chrom)
The advantage of this is that you're not limited to two trakcs.
The source file jquery-1.2.6.min.js
is not called the jQuery command $()
is executed earlier than <..src='jquery-1.2.6.min.js'>
.
Please run <.. src="/js/jquery-1.2.6.min.js..">
at first and make sure the src path is right, then execute jquery command
$(document).ready(function()
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
Another solution is to use an Oracle Collection as a Hashmap:
declare
-- create a type for your "Array" - it can be of any kind, record might be useful
type hash_map is table of varchar2(1000) index by varchar2(30);
my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
i varchar2(30);
begin
my_hmap('a') := 'apple';
my_hmap('b') := 'box';
my_hmap('c') := 'crow';
-- then how you use it:
dbms_output.put_line (my_hmap('c')) ;
-- or to loop on every element - it's a "collection"
i := my_hmap.FIRST;
while (i is not null) loop
dbms_output.put_line(my_hmap(i));
i := my_hmap.NEXT(i);
end loop;
end;
Wouldn't:
z <- df[df$x > quantile(df$x, .25) - 1.5*IQR(df$x) &
df$x < quantile(df$x, .75) + 1.5*IQR(df$x), ] #rows
accomplish this task quite easily?
Both T1
and T2
can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.
See this article for more info.
Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.
And note the pros/cons of using volatile
vs more complex means of sharing state.
This solution will first resize the columns based on column data, if the resized width is smaller than header size, it will resize columns to at least fit the header. This is a pretty ugly solution, but it works.
lstContacts.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
colFirstName.Width = (colFirstName.Width < 60 ? 60 : colFirstName.Width);
colLastName.Width = (colLastName.Width < 61 ? 61 : colLastName.Width);
colPhoneNumber.Width = (colPhoneNumber.Width < 81 ? 81 : colPhoneNumber.Width);
colEmail.Width = (colEmail.Width < 40 ? 40 : colEmail.Width);
lstContacts is the ListView. colFirstName is a column, where 60 is the width required to fit the title. Etc.
System.Convert works fine by me.
using System;
...
Bool fixed = Convert.ToBoolean(NullableBool);
In MS SQL SERVER:
With user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName)
REFERENCES pkTableName(pkTableColumnName);
Without user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);
I managed to get that error by passing an IQueryable
into a method that then used that IQueryable 'list' as part of a another query to the same context.
public void FirstMethod()
{
// This is returning an IQueryable
var stockItems = _dbContext.StockItems
.Where(st => st.IsSomething);
SecondMethod(stockItems);
}
public void SecondMethod(IEnumerable<Stock> stockItems)
{
var grnTrans = _dbContext.InvoiceLines
.Where(il => stockItems.Contains(il.StockItem))
.ToList();
}
To stop that happening I used the approach here and materialised that list before passing it the second method, by changing the call to SecondMethod
to be SecondMethod(stockItems.ToList()
Based on easy-confirm-plugin i did it:
(function($) {
$.postconfirm = {};
$.postconfirm.locales = {};
$.postconfirm.locales.ptBR = {
title: 'Esta certo disto?',
text: 'Esta certo que quer realmente ?',
button: ['Cancela', 'Confirma'],
closeText: 'fecha'
};
$.fn.postconfirm = function(options) {
var options = jQuery.extend({
eventType: 'click',
icon: 'help'
}, options);
var locale = jQuery.extend({}, $.postconfirm.locales.ptBR, options.locale);
var type = options.eventType;
return this.each(function() {
var target = this;
var $target = jQuery(target);
var getDlgDv = function() {
var dlger = (options.dialog === undefined || typeof(options.dialog) != 'object');
var dlgdv = $('<div class="dialog confirm">' + locale.text + '</div>');
return dlger ? dlgdv : options.dialog;
}
var dialog = getDlgDv();
var handler = function(event) {
$(dialog).dialog('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
};
var init = function()
{
$target.bind(type, handler);
};
var buttons = {};
buttons[locale.button[0]] = function() { $(dialog).dialog("close"); };
buttons[locale.button[1]] = function() {
$(dialog).dialog("close");
alert('1');
$target.unbind(type, handler);
$target.click();
$target.attr("disabled", true);
};
$(dialog).dialog({
autoOpen: false,
resizable: false,
draggable: true,
closeOnEscape: true,
width: 'auto',
minHeight: 120,
maxHeight: 200,
buttons: buttons,
title: locale.title,
closeText: locale.closeText,
modal: true
});
init();
});
var _attr = $.fn.attr;
$.fn.attr = function(attr, value) {
var returned = _attr.apply(this, arguments);
if (attr == 'title' && returned === undefined)
{
returned = '';
}
return returned;
};
};
})(jQuery);
you only need call in this way:
<script type="text/javascript">
$(document).ready(function () {
$(".mybuttonselector").postconfirm({ locale: {
title: 'title',
text: 'message',
button: ['bt_0', 'bt_1'],
closeText: 'X'
}
});
});
</script>
static String getDeviceName() {
try {
Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getMethod = systemPropertiesClass.getMethod("get", String.class);
Object object = new Object();
Object obj = getMethod.invoke(object, "ro.product.device");
return (obj == null ? "" : (String) obj);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
you can get 'idol3' by this way.
i just switched positions and worked for me (showing only mobile )
<style>_x000D_
.MobileContent {_x000D_
_x000D_
display: none;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
@media screen and (max-width: 768px) {_x000D_
_x000D_
.MobileContent {_x000D_
_x000D_
display:block;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
</style>_x000D_
<div class="MobileContent"> Something </div>
_x000D_
To fix this, i put this class on the webpage
<style>
td.vcenter {
vertical-align: middle !important;
text-align: center !important;
}
</style>
and this in my TemplateField
<asp:TemplateField ItemStyle-CssClass="vcenter">
as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.
Hope it helps
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
if any interested I've made a typescript version:
interface IResizeImageOptions {
maxSize: number;
file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
const file = settings.file;
const maxSize = settings.maxSize;
const reader = new FileReader();
const image = new Image();
const canvas = document.createElement('canvas');
const dataURItoBlob = (dataURI: string) => {
const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
const max = bytes.length;
const ia = new Uint8Array(max);
for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
return new Blob([ia], {type:mime});
};
const resize = () => {
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
let dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise((ok, no) => {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = (readerEvent: any) => {
image.onload = () => ok(resize());
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
})
};
and here's the javascript result:
var resizeImage = function (settings) {
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
usage is like:
resizeImage({
file: $image.files[0],
maxSize: 500
}).then(function (resizedImage) {
console.log("upload resized image")
}).catch(function (err) {
console.error(err);
});
or (async
/await
):
const config = {
file: $image.files[0],
maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!
Check - LSNRCTL> stat I got result like -
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1522)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for 32-bit Windows: Version 11.2.0.1.0 - Production
Start Date 17-APR-2016 10:12:38
Uptime 0 days 10 hr. 6 min. 16 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
C:\product\11.2.0\dbhome_1\network\admin\listener.ora
Listener Log File c:\app\admin\diag\tnslsnr\admin-PC\listener\alert\log.xml Listening
Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1522ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1522)))
Services Summary... Service "CLRExtProc" has 1 instance(s). Instance
"CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "orcl" has 1 instance(s). Instance "orcl", status READY, has 1 handler(s) for this service...
Service "orclXDB" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this service...
The command completed successfully.
From above details - My port no is - 1522 and i am able to create connection using "orcl" instance - so i used port as 1522 and instance as "orcl" -- Now URL is -
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:orcl", "SYS as SYSDBA","password");
It worked for me So please check LSNRCTL> stat in command prompt and configure your connection url accordingly.
Hope it will help Someone.
#! /bin/sh
# Run all programs in a directory in parallel
# Usage: run-parallel directory delay
# Copyright 2013 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution
if [ $# -eq 0 ]
then
echo
echo "run-parallel by Marc Perkel"
echo
echo "This program is used to run all programs in a directory in parallel"
echo "or to rerun them every X seconds for one minute."
echo "Think of this program as cron with seconds resolution."
echo
echo "Usage: run-parallel [directory] [delay]"
echo
echo "Examples:"
echo " run-parallel /etc/cron.20sec 20"
echo " run-parallel 20"
echo " # Runs all executable files in /etc/cron.20sec every 20 seconds or 3 times a minute."
echo
echo "If delay parameter is missing it runs everything once and exits."
echo "If only delay is passed then the directory /etc/cron.[delay]sec is assumed."
echo
echo 'if "cronsec" is passed then it runs all of these delays 2 3 4 5 6 10 12 15 20 30'
echo "resulting in 30 20 15 12 10 6 5 4 3 2 executions per minute."
echo
exit
fi
# If "cronsec" is passed as a parameter then run all the delays in parallel
if [ $1 = cronsec ]
then
$0 2 &
$0 3 &
$0 4 &
$0 5 &
$0 6 &
$0 10 &
$0 12 &
$0 15 &
$0 20 &
$0 30 &
exit
fi
# Set the directory to first prameter and delay to second parameter
dir=$1
delay=$2
# If only parameter is 2,3,4,5,6,10,12,15,20,30 then automatically calculate
# the standard directory name /etc/cron.[delay]sec
if [[ "$1" =~ ^(2|3|4|5|6|10|12|15|20|30)$ ]]
then
dir="/etc/cron.$1sec"
delay=$1
fi
# Exit if directory doesn't exist or has no files
if [ ! "$(ls -A $dir/)" ]
then
exit
fi
# Sleep if both $delay and $counter are set
if [ ! -z $delay ] && [ ! -z $counter ]
then
sleep $delay
fi
# Set counter to 0 if not set
if [ -z $counter ]
then
counter=0
fi
# Run all the programs in the directory in parallel
# Use of timeout ensures that the processes are killed if they run too long
for program in $dir/* ; do
if [ -x $program ]
then
if [ "0$delay" -gt 1 ]
then
timeout $delay $program &> /dev/null &
else
$program &> /dev/null &
fi
fi
done
# If delay not set then we're done
if [ -z $delay ]
then
exit
fi
# Add delay to counter
counter=$(( $counter + $delay ))
# If minute is not up - call self recursively
if [ $counter -lt 60 ]
then
. $0 $dir $delay &
fi
# Otherwise we're done
just change your div width to 160px if you have a padding of 20px it adds 40px extra to the width of your div so you need to subtract 40px from the width in order to keep your div looking normal and not distorted with extra width on it and your text all messed up.
If you are using Angular CLI 6, you can use the deployUrl/baseHref options in angular.json (projects > xxx > architect > build > configurations > production). In this way, you can easily specify the baseUrl per project.
Check that your settings are correct by looking at the index.html of the built app.
SELECT cols
FROM table
WHERE cols IS NULL
Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):
23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.
So VC++ 2008 Dinkumware implementation is faulty.
Old answer:
You got that error because in certain implementations of the std lib the set::iterator
is the same as set::const_iterator
.
For example libstdc++ (shipped with g++) has it (see here for the entire source code):
typedef typename _Rep_type::const_iterator iterator;
typedef typename _Rep_type::const_iterator const_iterator;
And in SGI's docs it states:
iterator Container Iterator used to iterate through a set.
const_iterator Container Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)
On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterator
s.
If you use MVC, tables, it works like this:
<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>
ok i found this one IMDB scraper
for C#: http://web3o.blogspot.de/2010/11/aspnetc-imdb-scraping-api.html
PHP here: http://web3o.blogspot.de/2010/10/php-imdb-scraper-for-new-imdb-template.html
alternatively a imdbapi.org implementation for c#:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using HtmlAgilityPack; // http://htmlagilitypack.codeplex.com/
public class IMDBHelper
{
public static imdbitem GetInfoByTitle(string Title)
{
string url = "http://imdbapi.org/?type=xml&limit=1&title=" + Title;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(source);
XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml, LoadOptions.None);
imdbitem i = new imdbitem();
i.rating = xdoc.Descendants("rating").Select(x => x.Value).FirstOrDefault();
i.rating_count = xdoc.Descendants("rating_count").Select(x => x.Value).FirstOrDefault();
i.year = xdoc.Descendants("year").Select(x => x.Value).FirstOrDefault();
i.rated = xdoc.Descendants("rated").Select(x => x.Value).FirstOrDefault();
i.title = xdoc.Descendants("title").Select(x => x.Value).FirstOrDefault();
i.imdb_url = xdoc.Descendants("imdb_url").Select(x => x.Value).FirstOrDefault();
i.plot_simple = xdoc.Descendants("plot_simple").Select(x => x.Value).FirstOrDefault();
i.type = xdoc.Descendants("type").Select(x => x.Value).FirstOrDefault();
i.poster = xdoc.Descendants("poster").Select(x => x.Value).FirstOrDefault();
i.imdb_id = xdoc.Descendants("imdb_id").Select(x => x.Value).FirstOrDefault();
i.also_known_as = xdoc.Descendants("also_known_as").Select(x => x.Value).FirstOrDefault();
i.language = xdoc.Descendants("language").Select(x => x.Value).FirstOrDefault();
i.country = xdoc.Descendants("country").Select(x => x.Value).FirstOrDefault();
i.release_date = xdoc.Descendants("release_date").Select(x => x.Value).FirstOrDefault();
i.filming_locations = xdoc.Descendants("filming_locations").Select(x => x.Value).FirstOrDefault();
i.runtime = xdoc.Descendants("runtime").Select(x => x.Value).FirstOrDefault();
i.directors = xdoc.Descendants("directors").Descendants("item").Select(x => x.Value).ToList();
i.writers = xdoc.Descendants("writers").Descendants("item").Select(x => x.Value).ToList();
i.actors = xdoc.Descendants("actors").Descendants("item").Select(x => x.Value).ToList();
i.genres = xdoc.Descendants("genres").Descendants("item").Select(x => x.Value).ToList();
return i;
}
public class imdbitem
{
public string rating { get; set; }
public string rating_count { get; set; }
public string year { get; set; }
public string rated { get; set; }
public string title { get; set; }
public string imdb_url { get; set; }
public string plot_simple { get; set; }
public string type { get; set; }
public string poster { get; set; }
public string imdb_id { get; set; }
public string also_known_as { get; set; }
public string language { get; set; }
public string country { get; set; }
public string release_date { get; set; }
public string filming_locations { get; set; }
public string runtime { get; set; }
public List<string> directors { get; set; }
public List<string> writers { get; set; }
public List<string> actors { get; set; }
public List<string> genres { get; set; }
}
}
I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path
in the invoke scripts for standalone projects.
However sys.path.append
isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth
files. Better (and more readable): site.addsitedir
.
And script.py
wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path
themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path
-frobbing.
Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
table.ListRows.Add Position:=1
Set lastRow = table.ListRows(1).Range
Else
Set lastRow = table.ListRows(table.ListRows.Count).Range
End If
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
The Method Works Properly For me:
var lanopt = $(".language-option");
lanopt.on("show.bs.collapse",".collapse", function(){
lanopt.find(".collapse.in").collapse("hide");
});
This is your code
$q = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users');
Try this
$id = $q->result()[0]->id;
or this one, it's simpler
$id = $q->row()->id;
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
with opencv 4.0;
-DOPENCV_GENERATE_PKGCONFIG=ON
to build argumentspkg-config --cflags --libs opencv4
instead of opencvGo inside bin folder in C drive where Postgres is installed. run following command in git bash or Command prompt:
pg_ctl.exe restart -D "<path upto data>"
Ex:
pg_ctl.exe restart -D "C:\Program Files\PostgreSQL\9.6\data"
Another way: type "services.msc" in run popup(windows + R). This will show all services running Select Postgres service from list and click on start/stop/restart.
Thanks
Consider the following:
class Bad(object):
def __eq__(self, other):
return True
c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Just a few other random ideas for completeness's sake. If they work for you, use them. Otherwise, you're probably better off trying something else.
You could also do this with a dictionary:
>>> x = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> y = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> x == y
True
This option is more complicated, but you may also find it useful:
class Klass(object):
def __init__(self, some_vars):
#initialize conditions here
def __nonzero__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
foo = Klass()
if foo:
print "foo is true!"
else:
print "foo is false!"
Dunno if that works for you, but it's another option to consider. Here's one more way:
class Klass(object):
def __init__(self):
#initialize conditions here
def __eq__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
x = Klass(some_values)
y = Klass(some_other_values)
if x == y:
print 'x == y'
else:
print 'x!=y'
The last two I haven't tested, but the concepts should be enough to get you going if that's what you want to go with.
(And for the record, if this is just a one time thing, you're probably just better off using the method you presented at first. If you're doing the comparison in lots of places, these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky.)
Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):
Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);
As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using
' statement:
// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "LoadFromRepository";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", fileID);
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
filename = SaveToFileSystem(rdr, folderfilepath);
}
}
}
}
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress()
:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink()
method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.
I think the annotation you are looking for is:
public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;
And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html
Use std::remove_if
algorithm.
Edit:
Work with collections should be like:
Life will be easier if you won't mix this steps.
std::remove_if
. or list::remove_if
( if you know that you work with list and not with the TCollection
)std::for_each
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
In regedit.exe
go to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate
It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.)
To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this Unix Time Conversion online tool.
finally, this code is worked for me to open the email client from android device. try this snippet.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "[email protected]");
testIntent.setData(data);
startActivity(testIntent);
This is exactly what bytearray
is for:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
If you're using Python 3.x, you can use bytes
instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes
is just an alias for str
. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
The accepted answer works for me.
Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.
[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]
then Right click, Script Table as, SELECT To, New Query Window
And the query will be generated for you with the right FROM, which you can use in your JOIN
To understand JavaBean you need to notice the following:
JavaBean is conceptual stuff and can not represent a class of specific things
JavaBean is a development tool can be visualized in the operation of reusable software components
JavaBean is based on the Sun JavaBeans specification and can be reusable components. Its biggest feature is the re-usability.
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
I managed to find network.http.connect.timeout for much older versions of Mozilla:
This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).
Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.
It would seem that network.http.connect.timeout
hasn't done anything for some time.
I also saw references to network.http.request.timeout
, so I did a Google search. The results include lots of links to people recommending that others include it in about:config
in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:
Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.
The same page includes additional information about network.http.connect.timeout
:
Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.
Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.
I'm just writing this to remind myself...
Array.prototype.slice.call(arguments);
== Array.prototype.slice(arguments[1], arguments[2], arguments[3], ...)
== [ arguments[1], arguments[2], arguments[3], ... ]
Or just use this handy function $A to turn most things into an array.
function hasArrayNature(a) {
return !!a && (typeof a == "object" || typeof a == "function") && "length" in a && !("setInterval" in a) && (Object.prototype.toString.call(a) === "[object Array]" || "callee" in a || "item" in a);
}
function $A(b) {
if (!hasArrayNature(b)) return [ b ];
if (b.item) {
var a = b.length, c = new Array(a);
while (a--) c[a] = b[a];
return c;
}
return Array.prototype.slice.call(b);
}
example usage...
function test() {
$A( arguments ).forEach( function(arg) {
console.log("Argument: " + arg);
});
}
You can use preg_match:
$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
Download Git on Msys. Then:
git clone git://project.url.here
You can use this implementation of onTouchEvent. It prevent from reacting underneath activity to the touch event (as mentioned howettl).
@Override
public boolean onTouchEvent ( MotionEvent event ) {
// I only care if the event is an UP action
if ( event.getAction () == MotionEvent.ACTION_UP ) {
// create a rect for storing the window rect
Rect r = new Rect ( 0, 0, 0, 0 );
// retrieve the windows rect
this.getWindow ().getDecorView ().getHitRect ( r );
// check if the event position is inside the window rect
boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
// if the event is not inside then we can close the activity
if ( !intersects ) {
// close the activity
this.finish ();
// notify that we consumed this event
return true;
}
}
// let the system handle the event
return super.onTouchEvent ( event );
}
Source: http://blog.twimager.com/2010/08/closing-activity-by-touching-outside.html
Axios is a promise based HTTP client for the browser and node.js.
It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js team when migrating from the 1.0 version which included a REST client by default.
Performing a
GET
request// Make a request for a user with a given ID axios.get('http://query.yahooapis.com/v1/publ...') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Or even just axios(url)
is enough as a GET
request is the default.
Being the author of the response that you highlight in your question, and admittedly coming to this one a bit late, I'd have to say that among the many reasons that have been listed, the productivity of a professional developer is one of the most highly-regarded skills.
By productivity, I mean the ability to do your job efficiently with the best-possible results. IDEs enable this on many levels. I'm not an Emacs expert, but I doubt that it lacks any of the features of the major IDEs.
Design, documentation, tracking, developing, building, analyzing, deploying, and maintenance, key stepping stones in an enterprise application, can all be done within an IDE.
Why you wouldn't use something so powerful if you have the choice?
As an experiment, commit yourself to use an IDE for, say, 30 days, and see how you feel. I would love to read your thoughts on the experience.
Both of them increase the variable i
by one. It's like saying i = i + 1
. The difference is subtle. If you're using it in a loop like this, there's no difference:
for (int i = 0; i < 100; i++) {
}
for (int i = 0; i < 100; ++i) {
}
If you want to know the difference, look at this example:
int a = 0;
int b = a++; // b = 0; a = 1
a = 0;
b = ++a: // b = 1; a = 1
The idea is that ++a
increments a
and returns that value, while a++
returns a's value and then increments a
.
You can add the following code:
this.ActiveControl = null; //this = form
Use:
<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />
<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />
<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />
Fill the content =" ... " according to the content of your page.
For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.
To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.
Adding to what b_levitt said, you can get the SSDT-BI plugin for Visual Studio 2013 here: http://www.microsoft.com/en-us/download/details.aspx?id=42313
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
The app should contain a templatetags
directory, at the same level as models.py
, views.py
, etc. If this doesn’t already exist, create it - don’t forget the __init__.py
file to ensure the directory is treated as a Python package.
define_action.py
inside of the templatetags directory with the following code:from django import template
register = template.Library()
@register.simple_tag
def define(val=None):
return val
Note: Development server won’t automatically restart. After adding the templatetags
module, you will need to restart your server before you can use the tags or filters in templates.
{% load define_action %}
{% if item %}
{% define "Edit" as action %}
{% else %}
{% define "Create" as action %}
{% endif %}
Would you like to {{action}} this item?
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
select * from [schema_name].sys.tables
This should work. Make sure you are on the server which consists of your "[schema_name]"
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
Nothing. It was added to the C99 standard.
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
For IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
The OP refined his question to how a php script is called from a script. The php statement 'require' is good for dependancy as the script will stop if required script is not found.
#!/usr/bin/php
<?
require '/relative/path/to/someotherscript.php';
/* The above script runs as though executed from within this one. */
printf ("Hello world!\n");
?>
With Oracle 12c (June 2013), you are able to use it like the following.
SELECT * FROM MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :
"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!
In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.
Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."
On Windows, just check in the windows task manager if there are any other adb processes running.
Or run adb kill-server
If yes, just kill it & then perform the adb start-server
command.
I hope, it should solve the problem.
Similar to @artur just without jQuery, with plain javascript:
// Using @Sean-bright's "elt" variable
var selection=elt.options[elt.selectedIndex].innerHTML;
string connectString = "Data Source=(local);" + "Integrated Security=true";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);
You need to make sure and have the following:
#include <windows.h>
and not this:
#include "windows.h"
If that's not the problem, then check RichieHindle's response.
I thought my javascript implementation would be a good reference to:
/*
* Check to see if the second coord is within the precision ( meters )
* of the first coord and return accordingly
*/
function checkWithinBound(coord_one, coord_two, precision) {
var distance = 3959000 * Math.acos(
Math.cos( degree_to_radian( coord_two.lat ) ) *
Math.cos( degree_to_radian( coord_one.lat ) ) *
Math.cos(
degree_to_radian( coord_one.lng ) - degree_to_radian( coord_two.lng )
) +
Math.sin( degree_to_radian( coord_two.lat ) ) *
Math.sin( degree_to_radian( coord_one.lat ) )
);
return distance <= precision;
}
/**
* Get radian from given degree
*/
function degree_to_radian(degree) {
return degree * (Math.PI / 180);
}
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
To run jar, first u have to create
executable jar
then
java -jar xyz.jar
command will work
You can get a JSON file that maps country codes to phone codes from http://country.io/phone.json:
...
BD: "880",
BE: "32",
BF: "226",
BG: "359",
BA: "387",
...
If you want country names then http://country.io/names.json will give you that:
...
"AL": "Albania",
"AM": "Armenia",
"AO": "Angola",
"AQ": "Antarctica",
"AR": "Argentina",
...
See http://country.io/data for more details.
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:
ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then
ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
HTH, -ft
Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)
After thorough research I found the solution
Encoding
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // bXkgcGxhbmkgdGV4dA==
Decoding
let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // my plain data
More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/
I'm not entirely sure what you want, and your last line of code does not help either, but anyway:
"Chained" filtering is done by "chaining" the criteria in the boolean index.
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
A B C D
d 1 3 9 6
If you want to chain methods, you can add your own mask method and use that one.
In [90]: def mask(df, key, value):
....: return df[df[key] == value]
....:
In [92]: pandas.DataFrame.mask = mask
In [93]: df = pandas.DataFrame(np.random.randint(0, 10, (4,4)), index=list('abcd'), columns=list('ABCD'))
In [95]: df.ix['d','A'] = df.ix['a', 'A']
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [97]: df.mask('A', 1)
Out[97]:
A B C D
a 1 4 9 1
d 1 3 9 6
In [98]: df.mask('A', 1).mask('D', 6)
Out[98]:
A B C D
d 1 3 9 6
To check if a string got any characters, ie. not null or whitespaces, check StringUtils.hasText
-method (if you are using Spring of course)
Example:
StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true
I had this problem too (encountered through Macports compilers). Previous versions of Xcode would let you install command line tools through xcode/Preferences, but xcode5 doesn't give a command line tools option in the GUI, that so I assumed it was automatically included now. Try running this command:
xcode-select --install
(as per this answer)
sudo apt-get install libc6-dev
(as per this comment)
apk add libc-dev
// get current URL
$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);
For any of you still having problems as of Sept. 2012, go here: http://support.microsoft.com/kb/2527041 ...and grab the SQLManagementStudio_x(32|64)_ENU.exe
(if you've already installed SQL Server 2008 Express R2), or SQL Server 2008 Express R2 with Tools, i.e. SQLEXPRWT_x64_ENU.exe or SQLEXPRWT_x32_ENU.exe
(if you haven't).
From there, follow similar instructions as above (i.e. use the "Perform new installation and add shared features" selection, as "Management Tools - Basic" is considered a "shared feature"), if you've already installed SQL Server Express 2008 R2 (as I had). And if you haven't done that yet, then of course you're going to follow this way as you need to install the new instance anyway.
This solved things for me, and hopefully it will for you, too!
Try this:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if count == 10:
location-=1
count=0
else:
count +=1
if location==-1:
location=0
if keys[K_RIGHT]:
if count == 10:
location+=1
count=0
else:
count +=1
if location==5:
location=4
This will mean you only move 1/10 of the time. If it still moves to fast you could try increasing the value you set "count" too.
If you want to get the form data directly from Http request, without any model bindings or FormCollection
you can use this:
[HttpPost]
public ActionResult SubmitAction() {
// This will return an string array of all keys in the form.
// NOTE: you specify the keys in form by the name attributes e.g:
// <input name="this is the key" value="some value" type="test" />
var keys = Request.Form.AllKeys;
// This will return the value for the keys.
var value1 = Request.Form.Get(keys[0]);
var value2 = Request.Form.Get(keys[1]);
}
I usually use a plain old VARCHAR filtering for an IPAddress works fine.
If you want to filter on ranges of IP address I'd break it into four integers.
Take double array as an example, if the initial input values
array is not empty, the following code snippet is superior to traditional direct for-loop
in time complexity:
public static void resetValues(double[] values) {
int len = values.length;
if (len > 0) {
values[0] = 0.0;
}
for (int i = 1; i < len; i += i) {
System.arraycopy(values, 0, values, i, ((len - i) < i) ? (len - i) : i);
}
}
Note: This solution only works for Webkit browsers, which incorrectly apply pseudo-elements to self-closing tags.
As an addendum to above answers it is worth noting that in some cases one needs to insert a space instead of merely ignoring <br>
:
For instance the above answers will turn
Monday<br>05 August
to
Monday05 August
as I had verified while I tried to format my weekly event calendar. A space after "Monday" is preferred to be inserted. This can be done easily by inserting the following in the CSS:
br {
content: ' '
}
br:after {
content: ' '
}
This will make
Monday<br>05 August
look like
Monday 05 August
You can change the content
attribute in br:after
to ', '
if you want to separate by commas, or put anything you want within ' '
to make it the delimiter! By the way
Monday, 05 August
looks neat ;-)
See here for a reference.
As in the above answers, if you want to make it tag-specific, you can. As in if you want this property to work for tag <h3>
, just add a h3
each before br
and br:after
, for instance.
It works most generally for a pseudo-tag.
You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)
The nvm install script by default adds initialization code to your $HOME/.profile
, which is only loaded by a login shell (in a desktop environment you may never see a login shell).
The nvm command in your login shell is not propagated to sub-shells (like console windows and IDE terminals after you log in). This snippet in your $HOME/.bashrc
will only load nvm if it is an interactive shell and has not been loaded already
# if nvm dir is not set and the standard nvm directory exists
if [ -z "$NVM_DIR" -a -d "$HOME/.nvm" ] ; then
# set nvm dir
export NVM_DIR="$HOME/.nvm"
fi
# if nvm dir is set and this shell is interactive
if [ -d "$NVM_DIR" -a -n "$PS1" ] ; then
# if nvm command is not defined
if ! type -t nvm >/dev/null ; then
# set it
source "$NVM_DIR/nvm.sh"
fi
fi
Putting this in your $HOME/.bashrc
file will fix the missing nvm problem in interactive bash shells, even from a gui, and even if nvm is installed in a non-standard location.
For attaching fragment to an activity programmatically in Kotlin, you can look at the following code:
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create fragment instance
val fragment : FragmentName = FragmentName.newInstance()
// for passing data to fragment
val bundle = Bundle()
bundle.putString("data_to_be_passed", DATA)
fragment.arguments = bundle
// check is important to prevent activity from attaching the fragment if already its attached
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, fragment, "fragment_name")
.commit()
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentName.kt
class FragmentName : Fragment() {
companion object {
fun newInstance() = FragmentName()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// receiving the data passed from activity here
val data = arguments!!.getString("data_to_be_passed")
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
}
If you are familiar with Extensions in Kotlin then you can even better this code by following this article.
This means your MySQL table is corrupted and you need to repair it. Use
myisamchk -r /DB_NAME/wp_posts
from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.
Post uses the message body to send the information back to the server, as opposed to Get, which uses the query string (everything after the question mark). It is possible to send both a Get query string and a Post message body in the same request, but that can get a bit confusing so is best avoided.
Generally, best practice dictates that you use Get when you want to retrieve data, and Post when you want to alter it. (These rules aren't set in stone, the specs don't forbid altering data with Get, but it's generally avoided on the grounds that you don't want people making changes just by clicking a link or typing a URL)
Conversely, you can use Post to retrieve data without changing it, but using Get means you can bookmark the page, or share the URL with other people, things you couldn't do if you'd used Post.
As for the actual format of the data sent in the message body, that's entirely up to the sender and is specified with the Content-Type
header. If not specified, the default content-type for HTML forms is application/x-www-form-urlencoded
, which means the server will expect the post body to be a string encoded in a similar manner to a GET query string. However this can't be depended on in all cases. RFC2616 says the following on the Content-Type header:
Any HTTP/1.1 message containing an entity-body SHOULD include a
Content-Type header field defining the media type of that body. If
and only if the media type is not given by a Content-Type field, the
recipient MAY attempt to guess the media type via inspection of its
content and/or the name extension(s) of the URI used to identify the
resource. If the media type remains unknown, the recipient SHOULD
treat it as type "application/octet-stream".
or a single select statement...
DECLARE @results VarChar(1000)
SELECT @results = CASE
WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number
type):
ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);
This creates a new column in my_table_name
called my_new_boolean_column
with default values of 0. The column will not accept NULL
values and restricts the accepted values to either 0
or 1
.
Disclosure: I wrote FieldVal.
Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.
You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.
Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx
function validate_form(data) {
// This would work on the back end too (if you're using Node)
// Validate the provided data
var validator = new FieldVal(data);
validator.get("email", BasicVal.email(true));
validator.get("title", BasicVal.string(true));
validator.get("url", BasicVal.url(true));
return validator.end();
}
$(document).ready(function(){
// Create a form and add some fields
var form = new FVForm()
.add_field("email", new FVTextField("Email"))
.add_field("title", new FVTextField("Title"))
.add_field("url", new FVTextField("URL"))
.on_submit(function(value){
// Clear the existing errors
form.clear_errors();
// Use the function above to validate the input
var error = validate_form(value);
if (error) {
// Pass the error into the form
form.error(error);
} else {
// Use the data here
alert(JSON.stringify(value));
}
})
form.element.append(
$("<button/>").text("Submit")
).appendTo("body");
//Pre-populate the form
form.val({
"email": "[email protected]",
"title": "Your Title",
"url": "http://www.example.com"
})
});
If you use Guava (former Google Collections) library there is a solution:
SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);
The returned SetView
is a Set
, it is a live representation you can either make immutable or copy to another set. test1
and test2
are left intact.
I knew I had this proto'd somewhere :)
Array.prototype.init = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this[n] = x; }
return this;
}
var a = (new Array(5)).init(0);
var b = [].init(0,4);
Edit: tests
In response to Joshua and others methods I ran my own benchmarking, and I'm seeing completely different results to those reported.
Here's what I tested:
//my original method
Array.prototype.init = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this[n] = x; }
return this;
}
//now using push which I had previously thought to be slower than direct assignment
Array.prototype.init2 = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this.push(x); }
return this;
}
//joshua's method
function newFilledArray(len, val) {
var a = [];
while(len--){
a.push(val);
}
return a;
}
//test m1 and m2 with short arrays many times 10K * 10
var a = new Date();
for(var i=0; i<10000; i++)
{
var t1 = [].init(0,10);
}
var A = new Date();
var b = new Date();
for(var i=0; i<10000; i++)
{
var t2 = [].init2(0,10);
}
var B = new Date();
//test m1 and m2 with long array created once 100K
var c = new Date();
var t3 = [].init(0,100000);
var C = new Date();
var d = new Date();
var t4 = [].init2(0,100000);
var D = new Date();
//test m3 with short array many times 10K * 10
var e = new Date();
for(var i=0; i<10000; i++)
{
var t5 = newFilledArray(10,0);
}
var E = new Date();
//test m3 with long array created once 100K
var f = new Date();
var t6 = newFilledArray(100000, 0)
var F = new Date();
Results:
IE7 deltas:
dA=156
dB=359
dC=125
dD=375
dE=468
dF=412
FF3.5 deltas:
dA=6
dB=13
dC=63
dD=8
dE=12
dF=8
So by my reckoning push is indeed slower generally but performs better with longer arrays in FF but worse in IE which just sucks in general (quel surprise).
I personally need to ensure the page keeps state, so all the text boxes and other input fields retain their values. by doing meta refresh it's like a new post, IsPostBack is always false so all your controls are in the initialized state again. To retain state put this at the end of your Page_Load(). create a hidden button on the page with an event hooked up, something like butRefresh with event butRefresh_Click(...). This code sets a timer on the page to fire a postback just like a user clicked the refresh button themselves. all state and session is retained. Enjoy! (P.S. you may need to put the directive in the @Page header EnableEventValidation="false" if you receive an error on postback.
//tell the browser to post back again in 5 seconds while keeping state of all controls
ClientScript.RegisterClientScriptBlock(this.GetType(), "refresh", "<script>setTimeout(function(){ " + ClientScript.GetPostBackClientHyperlink(butRefresh, "refresh") + " },5000);</script>");
With jQuery, never use inline onclick
javascript. Keep it unobtrusive. Do this instead, and remove the onclick
completely.
Also, note the use of the :checked
pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked
selector instead filters elements that are actually checked, regardless of what the html started as.
$('button').click(function() {
alert($('input[name="myname"][value="b"]').length);
$('input[name="myname"][value="b"]').attr('checked','checked');
$('#b').attr('checked',true);
alert($('input[name="myname"]:checked').val());
});
I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.
var scrollDownTo =$("#show_question_" + nQueId).position().top;
console.log(scrollDownTo);
$('#slider_light_box_container').animate({
scrollTop: scrollDownTo
}, 1000, function(){
});
}
You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.
Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method
If you are looking for a form reset:
<input type="reset" value="Reset Form Values"/>
or to reset other aspects of the form not handled by the browser
<input type="reset" onclick="doFormReset();" value="Reset Form Values"/>
Using jQuery
function doFormReset(){
$(".invalid").removeClass("invalid");
}
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
Though I'm using Mac OS 10.9, this solution may work for someone else as well, perhaps on Ubuntu.
In the XAMPP console, I only found that phpMyAdmin started working again after restarting everything including the Apache Web Server.
No problemo, now.
simple way to prevent the whole app from getting effected by system font size is to updateConfiguration using a base activity.
//in base activity add this code.
public void adjustFontScale( Configuration configuration) {
configuration.fontScale = (float) 1.0;
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adjustFontScale( getResources().getConfiguration());
}
You can use the CONCAT
with CURDATE()
to the entire time of the day and then filter by using the BETWEEN
in WHERE
condition:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))
Function is a set of logic that can be used to manipulate data.
While, Method is function that is used to manipulate the data of the object where it belongs. So technically, if you have a function that is not completely related to your class but was declared in the class, its not a method; It's called a bad design.
Regarding objects, especially in lazy-load scenario, one should consider garbage collector is running in idle CPU cycles, so presuming you're going into trouble when a lot of objects are loading small time penalty will solve the memory freeing.
Use time_nanosleep to enable GC to collect memory. Setting variable to null is desirable.
Tested on production server, originally the job consumed 50MB and then was halted. After nanosleep was used 14MB was constant memory consumption.
One should say this depends on GC behaviour which may change from PHP version to version. But it works on PHP 5.3 fine.
eg. this sample (code taken form VirtueMart2 google feed)
for($n=0; $n<count($ids); $n++)
{
//unset($product); //usefull for arrays
$product = null
if( $n % 50 == 0 )
{
// let GC do the memory job
//echo "<mem>" . memory_get_usage() . "</mem>";//$ids[$n];
time_nanosleep(0, 10000000);
}
$product = $productModel->getProductSingle((int)$ids[$n],true, true, true);
...
adb shell "su 0 mkdir /sdcard/com.test"
adb shell "su 0 mv -F /data/data/com.test/files/ /sdcard/com.test/"
adb pull /sdcard/com.test
Compactness and the ability to inline an if-then-else construct into an expression.
shlex has a .split()
function. It differs from str.split()
in that it does not preserve quotes and treats a quoted phrase as a single word:
>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']
NB: it works well for Unix-like command line strings. It doesn't work for natural-language processing.
SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use
It is certified for SharePoint 2007
The list of supported operations for Lists.asmx could be found here
In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:
<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Announcements",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
$("#tasksUL").append(liHtml);
});
}
});
});
</script>
<ul id="tasksUL"/>
For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" />
element.
This question already mentions, and links to other Stack Overflow questions regarding this topic.
string = string.split("\\");
In JavaScript, the backslash is used to escape special characters, such as newlines (\n
). If you want to use a literal backslash, a double backslash has to be used.
So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\")
will show a dialog containing two backslashes.
Depending on your meaning of "character":
[A-Za-z]
- all letters (uppercase and lowercase)
[^0-9]
- all non-digit characters
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.
With xunit you have Assert.Throws, so you can do things like this:
[Fact]
public void CantDecrementBasketLineQuantityBelowZero()
{
var o = new Basket();
var p = new Product {Id = 1, NetPrice = 23.45m};
o.AddProduct(p, 1);
Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
}
[Fact] is the xunit equivalent of [TestMethod]
I remember the StaticSelectedStyle-CssClass attribute used to work in ASP.NET 2.0. And in .NET 4.0 if you change the Menu control's RenderingMode attribute "Table" (thus making it render the menu as s and sub-s like it did back '05) it will at least write your specified StaticSelectedStyle-CssClass into the proper html element.
That may be enough for you page to work like you want. However my work-around for the selected menu item in ASP 4.0 (when leaving RenderingMode to its default), is to mimic the control's generated "selected" CSS class but give mine the "!important" CSS declaration so my styles take precedence where needed.
For instance by default the Menu control renders an "li" element and child "a" for each menu item and the selected menu item's "a" element will contain class="selected" (among other control generated CSS class names including "static" if its a static menu item), therefore I add my own selector to the page (or in a separate stylesheet file) for "static" and "selected" "a" tags like so:
a.selected.static
{
background-color: #f5f5f5 !important;
border-top: Red 1px solid !important;
border-left: Red 1px solid !important;
border-right: Red 1px solid !important;
}
This is a simple ping I use in one of the projects:
public static class Ping {
public String net = "NO_CONNECTION";
public String host = "";
public String ip = "";
public int dns = Integer.MAX_VALUE;
public int cnt = Integer.MAX_VALUE;
}
public static Ping ping(URL url, Context ctx) {
Ping r = new Ping();
if (isNetworkConnected(ctx)) {
r.net = getNetworkType(ctx);
try {
String hostAddress;
long start = System.currentTimeMillis();
hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
long dnsResolved = System.currentTimeMillis();
Socket socket = new Socket(hostAddress, url.getPort());
socket.close();
long probeFinish = System.currentTimeMillis();
r.dns = (int) (dnsResolved - start);
r.cnt = (int) (probeFinish - dnsResolved);
r.host = url.getHost();
r.ip = hostAddress;
}
catch (Exception ex) {
Timber.e("Unable to ping");
}
}
return r;
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
@Nullable
public static String getNetworkType(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
return activeNetwork.getTypeName();
}
return null;
}
Usage: ping(new URL("https://www.google.com:443/"), this);
Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}
I found a easy way to get that.
Example: Unix command(this way you don't need 2 commands.),
$ mysql -u root -p -e 'SHOW VARIABLES LIKE "%version%";'
Sample outputs:
+-------------------------+-------------------------+
| Variable_name | Value |
+-------------------------+-------------------------+
| innodb_version | 5.5.49 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.49-0ubuntu0.14.04.1 |
| version_comment | (Ubuntu) |
| version_compile_machine | x86_64 |
| version_compile_os | debian-linux-gnu |
+-------------------------+-------------------------+
In above case mysql version is 5.5.49.
Please find this useful reference.
I had to do the same for one of my projects and I ended up writing my own as well. I called it HorzListView is now part of my open source Aniqroid library.
http://aniqroid.sileria.com/doc/api/ (Look for downloads at the bottom or use google code project to see more download options: http://code.google.com/p/aniqroid/downloads/list)
The class documentation is here: http://aniqroid.sileria.com/doc/api/com/sileria/android/view/HorzListView.html
If nothing works Restart your PC . Restarting my computer does the trick
Edit: The answer below may be satisfactory, but it has some drawbacks:
There is a noticeable pause for the running of the script. I'm on a 160 ms latency, and it's enough to be annoying.
It works by building a new range each time you edit a given row. This gives an 'invalid contents' to previous entries some of the time
I hope others can clean this up somewhat.
Here's another way to do it, that saves you a ton of range naming:
Three sheets in the worksheet: call them Main, List, and DRange (for dynamic range.) On the Main sheet, column 1 contains a timestamp. This time stamp is modified onEdit.
On List your categories and subcategories are arranged as a simple list. I'm using this for plant inventory at my tree farm, so my list looks like this:
Group | Genus | Bot_Name
Conifer | Abies | Abies balsamea
Conifer | Abies | Abies concolor
Conifer | Abies | Abies lasiocarpa var bifolia
Conifer | Pinus | Pinus ponderosa
Conifer | Pinus | Pinus sylvestris
Conifer | Pinus | Pinus banksiana
Conifer | Pinus | Pinus cembra
Conifer | Picea | Picea pungens
Conifer | Picea | Picea glauca
Deciduous | Acer | Acer ginnala
Deciduous | Acer | Acer negundo
Deciduous | Salix | Salix discolor
Deciduous | Salix | Salix fragilis
...
Where | indicates separation into columns.
For convenience I also used the headers as names for named ranges.
DRrange A1 has the formula
=Max(Main!A2:A1000)
This returns the most recent timestamp.
A2 to A4 have variations on:
=vlookup($A$1,Inventory!$A$1:$E$1000,2,False)
with the 2 being incremented for each cell to the right.
On running A2 to A4 will have the currently selected Group, Genus and Species.
Below each of these, is a filter command something like this:
=unique(filter(Bot_Name,REGEXMATCH(Bot_Name,C1)))
These filters will populate a block below with matching entries to the contents of the top cell.
The filters can be modified to suit your needs, and to the format of your list.
Back to Main: Data validation in Main is done using ranges from DRange.
The script I use:
function onEdit(event) {
//SETTINGS
var dynamicSheet='DRange'; //sheet where the dynamic range lives
var tsheet = 'Main'; //the sheet you are monitoring for edits
var lcol = 2; //left-most column number you are monitoring; A=1, B=2 etc
var rcol = 5; //right-most column number you are monitoring
var tcol = 1; //column number in which you wish to populate the timestamp
//
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn(); //scol is the column number of the edited cell
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
for(var looper=scol+1; looper<=rcol; looper++) {
s.getRange(r.getRow(),looper).setValue(""); //After edit clear the entries to the right
}
}
}
}
Original Youtube presentation that gave me most of the onEdit timestamp component: https://www.youtube.com/watch?v=RDK8rjdE85Y
import java.net.*;
public class Demo{
public static void main(){
String data = "data=Hello+World!";
URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(data.getBytes("UTF-8"));
con.getInputStream();
}
}
A Natural Join is where 2 tables are joined on the basis of all common columns.
common column : is a column which has same name in both tables + has compatible datatypes in both the tables. You can use only = operator
A Inner Join is where 2 tables are joined on the basis of common columns mentioned in the ON clause.
common column : is a column which has compatible datatypes in both the tables but need not have the same name.
You can use only any comparision operator like =
, <=
, >=
, <
, >
, <>
I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".
I find this easier to read...
If printDialog IsNot Nothing Then
'blah
End If
than this...
If Not obj Is Nothing Then
'blah
End If
Try This: Application.ExitThread();
You'll have to make this separate try
blocks:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
This assumes you want to run code c
only if code b
failed.
If you need to run code c
regardless, you need to put the try
blocks one after the other:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
pass
try:
code c
except ExplicitException:
pass
try:
code d
except ExplicitException:
pass
I'm using except ExplicitException
here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError
, KeyboardInterrupt
and SystemExit
as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.
Using an attribute of a function as static variable has some potential drawbacks:
Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact.
An alternative would be a pattern using lexical closures, which are supported with the nonlocal
keyword in python 3.
def make_counter():
i = 0
def counter():
nonlocal i
i = i + 1
return i
return counter
counter = make_counter()
Sadly I know no way to encapsulate this solution into a decorator.
Here's how you can POST XML on Windows using curl command line on Windows. Better use batch/.cmd file for that:
curl -i -X POST -H "Content-Type: text/xml" -d ^
"^<?xml version=\"1.0\" encoding=\"UTF-8\" ?^> ^
^<Transaction^> ^
^<SomeParam1^>Some-Param-01^</SomeParam1^> ^
^<Password^>SomePassW0rd^</Password^> ^
^<Transaction_Type^>00^</Transaction_Type^> ^
^<CardHoldersName^>John Smith^</CardHoldersName^> ^
^<DollarAmount^>9.97^</DollarAmount^> ^
^<Card_Number^>4111111111111111^</Card_Number^> ^
^<Expiry_Date^>1118^</Expiry_Date^> ^
^<VerificationStr2^>123^</VerificationStr2^> ^
^<CVD_Presence_Ind^>1^</CVD_Presence_Ind^> ^
^<Reference_No^>Some Reference Text^</Reference_No^> ^
^<Client_Email^>[email protected]^</Client_Email^> ^
^<Client_IP^>123.4.56.7^</Client_IP^> ^
^<Tax1Amount^>^</Tax1Amount^> ^
^<Tax2Amount^>^</Tax2Amount^> ^
^</Transaction^> ^
" "http://localhost:8080"
([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))
example:
// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));
SELECT
o.name
FROM
sys.sql_modules sm
INNER JOIN sys.objects o ON
o.object_id = sm.object_id
WHERE
sm.definition LIKE '%<table name>%'
Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.
First install a pod :-
pod 'SwiftGifOrigin'
and import in your class
import SwiftGifOrigin
then write this code in viewDidiload method
yourImageView.image = UIImage.gif(name: "imageName")
Note:- plz do not include the file extension in the gif file name. Ex:-
//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
See source: https://github.com/swiftgif/SwiftGif
I guess the most effective way to find duplicates in a list is:
from collections import Counter
def duplicates(values):
dups = Counter(values) - Counter(set(values))
return list(dups.keys())
print(duplicates([1,2,3,6,5,2]))
It uses Counter
once on all the elements, and then on all unique elements. Subtracting the first one with the second will leave out the duplicates only.
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
See: http://googletesting.blogspot.com/2007/02/tott-naming-unit-tests-responsibly.html
For test method names, I personally find using verbose and self-documented names very useful (alongside Javadoc comments that further explain what the test is doing).
I needed a very simple solution to hide something after sometime and managed to get this to work:
In angular you can do this:
$timeout(self.hideError,2000);
Here is the function that i call when the timeout has been reached
self.hideError = function(){
self.HasError = false;
self.ErrorMessage = '';
};
So now my dialog/ui can use those properties to hide elements.
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
Using your current str_replace method:
$FileName = str_replace("'", "", $UserInput);
While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.
With str_replace, you could even have an array of strings you want to remove entirely:
$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example
$FileName = str_replace( $remove, "", $UserInput );
in spring boot project we can write logging.level.root=WARN but here problem is, we have to restart again even we added devtools dependency, in property file if we are modified any value will not autodetectable, for this limitation i came to know the solution i,e we can add actuator in pom.xml and pass the logger level as below shown in postman client in url bar http://localhost:8080/loggers/ROOT or http://localhost:8080/loggers/com.mycompany and in the body you can pass the json format like below
{
"configuredLevel": "WARN"
}
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
The default string representation for a dictionary seems to be just right:
>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}
Not sure if you can get at the "variable name", since variables in Python are just labels for values. See this question.
I had the same problem, which went away after I listed my library last: gcc prog.c -lm
The problem could also be a in a different namespace in svc file as it is in svc.cs file.
In svc file namespace must be in the following format.
Service="Namespace.SvcClassName"
For an activity derived from ListActivity that implements LoaderManager.LoaderCallbacks using a SimpleCursorAdapter it did not work to restore the position in onReset(), because the activity was almost always restarted and the adapter was reloaded when the details view was closed. The trick was to restore the position in onLoadFinished():
in onListItemClick():
// save the selected item position when an item was clicked
// to open the details
index = getListView().getFirstVisiblePosition();
View v = getListView().getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - getListView().getPaddingTop());
in onLoadFinished():
// restore the selected item which was saved on item click
// when details are closed and list is shown again
getListView().setSelectionFromTop(index, top);
in onBackPressed():
// Show the top item at next start of the app
index = 0;
top = 0;
a
is defined locally in the function, and can't be used outside the function. If you want to return a char
array from the function, you'll need to allocate it dynamically:
char *a = malloc(1000);
And at some point call free
on the returned pointer.
You should also see a warning at this line: char b = "blah";
: you're trying to assign a string literal to a char
.
I was able to set the env. variables by sourcing (source command inside the shell (ksh) scirpt) the file that was settign them. Then I called the .ksh script from the external Tools
$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
return ($(b).text()) < ($(a).text()) ? 1 : -1;
}
// decending sort
function dec_sort(a, b){
return ($(b).text()) > ($(a).text()) ? 1 : -1;
}
live demo : http://jsbin.com/eculis/876/edit
use the keyword break
instead of return
On linux, you can run this command and see the result :
ps aux | grep "java"
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
In my case, I had a sequence with the same name.
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
I had several inconveniences with all the solutions because I needed the type of Instant variable and the Time Zone always interfered changing everything, then combining solutions I saw that this is a good option.
LocalDate today = LocalDate.now();
Instant startDate = Instant.parse(today.toString()+"T00:00:00Z");
Instant endDate = Instant.parse(today.toString()+"T23:59:59Z");
and we have as a result
startDate = 2020-01-30T00:00:00Z
endDate = 2020-01-30T23:59:59Z
I hope it helps you
You can simplify it somewhat by changing the first two lines of the function to this:
var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
Or, just change the parameter to the RegExp constructor to be
^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
This behavior is expected. flex container will stretch all its children by default. Image have no exception. (ie, parent will have align-items: stretch
property )
To keep the aspect ratio we've two solutions:
align-items: stretch
property to align-items: flex-start
or align-self: center
etc,
http://jsfiddle.net/e394Lqnt/3/or
align-self: center
or align-self: flex-start
etc.
http://jsfiddle.net/e394Lqnt/2/Here are a variety of ways to do this, along with some benchmarks. The best methods are versions using optimized code from other libraries. The bottleneck.move_mean
method is probably best all around. The scipy.convolve
approach is also very fast, extensible, and syntactically and conceptually simple, but doesn't scale well for very large window values. The numpy.cumsum
method is good if you need a pure numpy
approach.
Note: Some of these (e.g. bottleneck.move_mean
) are not centered, and will shift your data.
import numpy as np
import scipy as sci
import scipy.signal as sig
import pandas as pd
import bottleneck as bn
import time as time
def rollavg_direct(a,n):
'Direct "for" loop'
assert n%2==1
b = a*0.0
for i in range(len(a)) :
b[i]=a[max(i-n//2,0):min(i+n//2+1,len(a))].mean()
return b
def rollavg_comprehension(a,n):
'List comprehension'
assert n%2==1
r,N = int(n/2),len(a)
return np.array([a[max(i-r,0):min(i+r+1,N)].mean() for i in range(N)])
def rollavg_convolve(a,n):
'scipy.convolve'
assert n%2==1
return sci.convolve(a,np.ones(n,dtype='float')/n, 'same')[n//2:-n//2+1]
def rollavg_convolve_edges(a,n):
'scipy.convolve, edge handling'
assert n%2==1
return sci.convolve(a,np.ones(n,dtype='float'), 'same')/sci.convolve(np.ones(len(a)),np.ones(n), 'same')
def rollavg_cumsum(a,n):
'numpy.cumsum'
assert n%2==1
cumsum_vec = np.cumsum(np.insert(a, 0, 0))
return (cumsum_vec[n:] - cumsum_vec[:-n]) / n
def rollavg_cumsum_edges(a,n):
'numpy.cumsum, edge handling'
assert n%2==1
N = len(a)
cumsum_vec = np.cumsum(np.insert(np.pad(a,(n-1,n-1),'constant'), 0, 0))
d = np.hstack((np.arange(n//2+1,n),np.ones(N-n)*n,np.arange(n,n//2,-1)))
return (cumsum_vec[n+n//2:-n//2+1] - cumsum_vec[n//2:-n-n//2]) / d
def rollavg_roll(a,n):
'Numpy array rolling'
assert n%2==1
N = len(a)
rolling_idx = np.mod((N-1)*np.arange(n)[:,None] + np.arange(N), N)
return a[rolling_idx].mean(axis=0)[n-1:]
def rollavg_roll_edges(a,n):
# see https://stackoverflow.com/questions/42101082/fast-numpy-roll
'Numpy array rolling, edge handling'
assert n%2==1
a = np.pad(a,(0,n-1-n//2), 'constant')*np.ones(n)[:,None]
m = a.shape[1]
idx = np.mod((m-1)*np.arange(n)[:,None] + np.arange(m), m) # Rolling index
out = a[np.arange(-n//2,n//2)[:,None], idx]
d = np.hstack((np.arange(1,n),np.ones(m-2*n+1+n//2)*n,np.arange(n,n//2,-1)))
return (out.sum(axis=0)/d)[n//2:]
def rollavg_pandas(a,n):
'Pandas rolling average'
return pd.DataFrame(a).rolling(n, center=True, min_periods=1).mean().to_numpy()
def rollavg_bottlneck(a,n):
'bottleneck.move_mean'
return bn.move_mean(a, window=n, min_count=1)
N = 10**6
a = np.random.rand(N)
functions = [rollavg_direct, rollavg_comprehension, rollavg_convolve,
rollavg_convolve_edges, rollavg_cumsum, rollavg_cumsum_edges,
rollavg_pandas, rollavg_bottlneck, rollavg_roll, rollavg_roll_edges]
print('Small window (n=3)')
%load_ext memory_profiler
for f in functions :
print('\n'+f.__doc__+ ' : ')
%timeit b=f(a,3)
print('\nLarge window (n=1001)')
for f in functions[0:-2] :
print('\n'+f.__doc__+ ' : ')
%timeit b=f(a,1001)
print('\nMemory\n')
print('Small window (n=3)')
N = 10**7
a = np.random.rand(N)
%load_ext memory_profiler
for f in functions[2:] :
print('\n'+f.__doc__+ ' : ')
%memit b=f(a,3)
print('\nLarge window (n=1001)')
for f in functions[2:-2] :
print('\n'+f.__doc__+ ' : ')
%memit b=f(a,1001)
Timing, Small window (n=3)
Direct "for" loop :
4.14 s ± 23.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
List comprehension :
3.96 s ± 27.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
scipy.convolve :
1.07 ms ± 26.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
scipy.convolve, edge handling :
4.68 ms ± 9.69 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
numpy.cumsum :
5.31 ms ± 5.11 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
numpy.cumsum, edge handling :
8.52 ms ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Pandas rolling average :
9.85 ms ± 9.63 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
bottleneck.move_mean :
1.3 ms ± 12.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Numpy array rolling :
31.3 ms ± 91.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Numpy array rolling, edge handling :
61.1 ms ± 55.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Timing, Large window (n=1001)
Direct "for" loop :
4.67 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
List comprehension :
4.46 s ± 14.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
scipy.convolve :
103 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
scipy.convolve, edge handling :
272 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
numpy.cumsum :
5.19 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
numpy.cumsum, edge handling :
8.7 ms ± 11.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Pandas rolling average :
9.67 ms ± 199 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
bottleneck.move_mean :
1.31 ms ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Memory, Small window (n=3)
The memory_profiler extension is already loaded. To reload it, use:
%reload_ext memory_profiler
scipy.convolve :
peak memory: 362.66 MiB, increment: 73.61 MiB
scipy.convolve, edge handling :
peak memory: 510.24 MiB, increment: 221.19 MiB
numpy.cumsum :
peak memory: 441.81 MiB, increment: 152.76 MiB
numpy.cumsum, edge handling :
peak memory: 518.14 MiB, increment: 228.84 MiB
Pandas rolling average :
peak memory: 449.34 MiB, increment: 160.02 MiB
bottleneck.move_mean :
peak memory: 374.17 MiB, increment: 75.54 MiB
Numpy array rolling :
peak memory: 661.29 MiB, increment: 362.65 MiB
Numpy array rolling, edge handling :
peak memory: 1111.25 MiB, increment: 812.61 MiB
Memory, Large window (n=1001)
scipy.convolve :
peak memory: 370.62 MiB, increment: 71.83 MiB
scipy.convolve, edge handling :
peak memory: 521.98 MiB, increment: 223.18 MiB
numpy.cumsum :
peak memory: 451.32 MiB, increment: 152.52 MiB
numpy.cumsum, edge handling :
peak memory: 527.51 MiB, increment: 228.71 MiB
Pandas rolling average :
peak memory: 451.25 MiB, increment: 152.50 MiB
bottleneck.move_mean :
peak memory: 374.64 MiB, increment: 75.85 MiB
In my situation, I only need the json result, and this works for me:
public interface SchoolRepository extends JpaRepository<School,Integer> {
@Query("select s.id, s.name from School s")
List<Object> getSchoolIdAndName();
}
in Controller:
@Autowired
private SchoolRepository schoolRepository;
@ResponseBody
@RequestMapping("getschoolidandname.do")
public List<Object> getSchool() {
List<Object> schools = schoolRepository.getSchoolIdAndName();
return schools;
}
Well, first of all, in Python there is no !
operator, that'd be not
. But open
would not fail silently either - it would throw an exception. And the blocks need to be indented properly - Python uses whitespace to indicate block containment.
Thus we get:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
Swift 3, with extension:
extension UIView{
var globalPoint :CGPoint? {
return self.superview?.convert(self.frame.origin, to: nil)
}
var globalFrame :CGRect? {
return self.superview?.convert(self.frame, to: nil)
}
}
All modules from package.json are installed to ./node_modules/
I couldn't find this explicitly stated but this is the package.json reference for NPM.
I wanted to posted here because of the complexity of this problem. My solution was to roll back to .Net 4.0. I have been testing for 3 days and have not been able to get System.Data.SQLite.Core.1.0.98.0 to work with .Net 4.5 or .Net 4.5.1.
The testing was exhaustive on 3 computers, 2 servers one dev PC. I have not been able to get to the source of the issue. I have tried editing the .vsproj file. I have added the SQLite.interop.dll to all folders practically. I have applied the package to all GAC folders, and removed and reapplied individually. Eventually removed.
I do have System.Data.SQLite.Core.1.0.98.0 working with .Net 4.0. I intend to continue to attempt the migration, but I think I will start a new project first and see if I can get it to work in that fashion. This was originally a .Net 3.5 web app, and in my travels I found a good amount of information still referencing that framework.
It would seem that removing http://
from the url option ensures the the correct HTTP POST header is sent.
I dont think you need to fully qualify the name of the host, just use a relative URL as below.
$.ajax({
type: "POST",
contentType: "application/json",
url: '/Hello',
data: { name: 'norm' },
dataType: "json"
});
An example of mine that works:
$.ajax({
type: "POST",
url: siteRoot + "api/SpaceGame/AddPlayer",
async: false,
data: JSON.stringify({ Name: playersShip.name, Credits: playersShip.credits }),
contentType: "application/json",
complete: function (data) {
console.log(data);
wait = false;
}
});
Possibly related: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox
Edit: After some more research I found out the OPTIONS header is used to find out if the request from the originating domain is allowed. Using fiddler, I added the following to the response headers from my server.
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, GET, OPTIONS
Once the browser received this response it then sent off the correct POST request with json data. It would seem that the default form-urlencoded content type is considered safe and so does not undergo the extra cross domain checks.
It looks like you will need to add the previously mentioned headers to your servers response to the OPTIONS request. You should of course configure them to allow requests from specific domains rather then all.
I used the following jQuery to test this.
$.ajax({
type: "POST",
url: "http://myDomain.com/path/AddPlayer",
data: JSON.stringify({
Name: "Test",
Credits: 0
}),
//contentType: "application/json",
dataType: 'json',
complete: function(data) {
$("content").html(data);
}
});?
References:
You have used '/0'
instead of '\0'
. This is incorrect: the '\0'
is a null character, while '/0'
is a multicharacter literal.
Moreover, in C it is OK to skip a zero in your condition:
while (*(forward++)) {
...
}
is a valid way to check character, integer, pointer, etc. for being zero.
In Java, by default AES supports a 128 Bit key, if you plans to use 192 Bit or 256 Bit key, java complier will throw Illegal key size Exception, which you are getting.
The solution is as victor & James suggested, you will need to download JCE (Java Cryptography Extension) as per your JRE version,(java6, java7 or java8).
The JCE zip contains following JAR:
You need to replace these jar form your <JAVA_HOME>/jre/lib/security
.
if you are on a unix system the will probably refer to /home/urs/usr/lib/jvm/java-<version>-oracle/
Sometimes just replacing local_policy.jar, US_export_policy.jar in security folder doesn't work on unix, so I suggest to copy security folder to your desktop first, replace the jar's @Desktop/security folder, delete the security folder from /jre/lib/ & move the Desktop security folder to /jre/lib/.
eg :: sudo mv security /usr/lib/jvm/java-7-oracle/jre/lib
This version is best way for blocks with fixed width:
http://codepen.io/7iomka/pen/oxxeNE
In other cases - version of dalgard
http://codepen.io/dalgard/pen/Dbnus
body {_x000D_
padding: 5%;_x000D_
}_x000D_
_x000D_
div {_x000D_
overflow: hidden;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
ul {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
justify-content:center;_x000D_
margin: 0 -4px -4px 0;_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
flex: 1 0 200px;_x000D_
height: 200px;_x000D_
max-width:200px;_x000D_
min-width:200px;_x000D_
border-right: 4px solid black;_x000D_
border-bottom: 4px solid black;_x000D_
background-color: deeppink;_x000D_
}_x000D_
li:empty {_x000D_
height: 0;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
*,_x000D_
:before,_x000D_
:after {_x000D_
box-sizing: border-box;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
<li>d</li>_x000D_
<li>e</li>_x000D_
<li>f</li>_x000D_
<li>g</li>_x000D_
<li>h</li>_x000D_
<li>i</li>_x000D_
<li>j</li>_x000D_
<li>k</li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>_x000D_
</div>
_x000D_
You are trying to insert data that is larger than allowed for the column logo
.
Use following data types as per your need
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
Use LONGBLOB
to avoid this exception.
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES
automagically:
#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = {
1,
2,
3,
4 };
Just add an else
then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
#include <chrono>
#include <iostream>
int main()
{
std::time_t ct = std::time(0);
char* cc = ctime(&ct);
std::cout << cc << std::endl;
return 0;
}
library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0
when you need in a timestamp in seconds, you can use the following:
var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
You can use this:
<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">
Here, record is the model for current row and status is boolean value.
I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.
Relative to Eclipse install dir:
For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:
grep '../../../../' * -R
Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:
grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'
Now Eclipse runs fine again.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column
.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
I had similar question however mine involved a column Convert(date,mydatetime). I had to alter the best answer as follows:
Select
count(created_date) as counted_leads,
Convert(date,created_date) as count_date
from table
group by Convert(date,created_date)
Try:
For Mac users, you only need to use the fn key if the setting "Use all F1, F2 etc. keys as function keys" (under System Preferences -> Keyboard) is checked.
Add Custom Font in Swift
myLabel.font = UIFont (name: "GILLSANSCE-ROMAN", size: 20)
May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.
//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();