This error can also occur if you accidentally use commas instead of AND
in the ON
clause of a JOIN
:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
Another way to make the parser raise the same exception is the following incorrect clause.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
system_user_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The nested SELECT
statement in the IN
clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.
For sake of completeness, the correct syntax is as follows.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The stored procedure of which this query is a portion not only parsed, but returned the expected result.
use moment in your function like this
moment(new Date(date)).format('MM/DD/YYYY')
Triggers cannot modify the changed data (Inserted
or Deleted
) otherwise you could get infinite recursion as the changes invoked the trigger again. One option would be for the trigger to roll back the transaction.
Edit: The reason for this is that the standard for SQL is that inserted and deleted rows cannot be modified by the trigger. The underlying reason for is that the modifications could cause infinite recursion. In the general case, this evaluation could involve multiple triggers in a mutually recursive cascade. Having a system intelligently decide whether to allow such updates is computationally intractable, essentially a variation on the halting problem.
The accepted solution to this is not to permit the trigger to alter the changing data, although it can roll back the transaction.
create table Foo (
FooID int
,SomeField varchar (10)
)
go
create trigger FooInsert
on Foo after insert as
begin
delete inserted
where isnumeric (SomeField) = 1
end
go
Msg 286, Level 16, State 1, Procedure FooInsert, Line 5
The logical tables INSERTED and DELETED cannot be updated.
Something like this will roll back the transaction.
create table Foo (
FooID int
,SomeField varchar (10)
)
go
create trigger FooInsert
on Foo for insert as
if exists (
select 1
from inserted
where isnumeric (SomeField) = 1) begin
rollback transaction
end
go
insert Foo values (1, '1')
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
This is what worked for me -
Download HAXM intaller from Intel site. https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
If using avast, disable "Enable hardware-assisted virtualization" under: Settings > Troubleshooting by unchecking.
Do a hard boot (power button) just to be safe.
I think I just figured it out. I changed the (new) default
protect_from_forgery with: :exception
to
protect_from_forgery with: :null_session
as per the comment in ApplicationController
.
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
You can see the difference by looking at the source for request_forgery_protecton.rb
, or, more specifically, the following lines:
In Rails 3.2:
# This is the method that defines the application behavior when a request is found to be unverified.
# By default, \Rails resets the session when it finds an unverified request.
def handle_unverified_request
reset_session
end
In Rails 4:
def handle_unverified_request
forgery_protection_strategy.new(self).handle_unverified_request
end
Which will call the following:
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
Just to be different :)
list($whole, $decimal) = sscanf(1.5, '%d.%d');
As an added benefit, it will only split where both sides consist of digits.
I had the same issue with mind. I tried using sudo apt-get install build-essential It still won't work. I simply created a hardlink to the gcc-x binary in the /usr/bin/ folder. sudo ls /usr/bin/gcc-x /usr/bin/gcc
That worked for me!
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
This is how it worked for me:
P.S Killing Xcode and launch again is the best thing to do if facing any random issue
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
You're looking for a response header of Set-Cookie
:
xhr.getResponseHeader('Set-Cookie');
It won't work with HTTPOnly cookies though.
According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader()
, so the only reason why this could work is basically a "naughty" browser.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
Ok, well I looked at the provided samples from rrainn and Soonil, and I found a solution that does not mess up error handling.
I modified the CustomExceptionHandler so it stores the original UncaughtExceptionHandler from the Thread we associate the new one. At the end of the new "uncaughtException"- Method I just call the old function using the stored UncaughtExceptionHandler.
In the DefaultExceptionHandler class you need sth. like this:
public class DefaultExceptionHandler implements UncaughtExceptionHandler{
private UncaughtExceptionHandler mDefaultExceptionHandler;
//constructor
public DefaultExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler)
{
mDefaultExceptionHandler= pDefaultExceptionHandler;
}
public void uncaughtException(Thread t, Throwable e) {
//do some action like writing to file or upload somewhere
//call original handler
mStandardEH.uncaughtException(t, e);
// cleanup, don't know if really required
t.getThreadGroup().destroy();
}
}
With that modification on the code at http://code.google.com/p/android-remote-stacktrace you have a good working base for logging in the field to your webserver or to sd-card.
#button {
line-height: 12px;
width: 18px;
font-size: 8pt;
font-family: tahoma;
margin-top: 1px;
margin-right: 2px;
position: absolute;
top: 0;
right: 0;
}
I figured that one solution would be to run a batch operation on the Eclipse JAR's which contain the icons and double their size. After a bit of tinkering, it worked. Results are pretty good - there's still a few "stubborn" icons which are tiny but most look good.
I put together the code into a small project: https://github.com/davidglevy/eclipse-icon-enlarger
The project works by:
The only problem I've found with this solution is that it really only works once - if you need to download plugins then do so in the original location and re-apply the icon increase batch process.
On the Dell XPS it takes about 5 minutes to run.
Happy for suggestions/improvements but this is really just an adhoc solution while we wait for the Eclipse team to get a fix out.
jQuery has the inArray
function:
I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.
var fs = require("fs");
function main() {
fs.readdir("./node_modules", function (err, dirs) {
if (err) {
console.log(err);
return;
}
dirs.forEach(function(dir){
if (dir.indexOf(".") !== 0) {
var packageJsonFile = "./node_modules/" + dir + "/package.json";
if (fs.existsSync(packageJsonFile)) {
fs.readFile(packageJsonFile, function (err, data) {
if (err) {
console.log(err);
}
else {
var json = JSON.parse(data);
console.log('"'+json.name+'": "' + json.version + '",');
}
});
}
}
});
});
}
main();
In my case, the above script outputs:
"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0", // Remember: remove the comma character in the last line.
Now, you can copy&paste them. Have fun!
Wrap the text in a span
or similar and use the following CSS:
.your-div {
position: relative;
}
.your-div span {
position: absolute;
bottom: 0;
right: 0;
}
hive stores only the meta data in metastore and original data in out side of hive when we use external table we can give location' ' by these our original data wont effect when we drop the table
curl_getinfo()
must be added before closing the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);
Make sure to delete java references from system32, SysWOW64, and delete javapath from ProgramData\Oracle\Java. It solves the issue
I'm unclear about your question. From http://effbot.org/tkinterbook/entry.htm#patterns, it seems you just need to do an assignment after you called the delete. To add entry text to the widget, use the insert method. To replace the current text, you can call delete before you insert the new text.
e = Entry(master)
e.pack()
e.delete(0, END)
e.insert(0, "")
Could you post a bit more code?
I found a quick and easy solution to what I wanted using json_normalize()
included in pandas 1.01
.
from urllib2 import Request, urlopen
import json
import pandas as pd
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])
This gives a nice flattened dataframe with the json data that I got from the Google Maps API.
I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:
renderer.setClearColorHex( 0x000000, 1 );
in your threejs
init function. Change it to:
renderer.setClearColorHex( 0xffffff, 1 );
Update: Thanks to HdN8 for the updated solution:
renderer.setClearColor( 0xffffff, 0);
Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor()
function:
var renderer = new THREE.WebGLRenderer({ alpha: true });
Update #3: Mr.doob points out that since r78
you can alternatively use the code below to set your scene's background colour:
var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
shell@android:/ $ dumpsys cpuinfo
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
47% 1118/com.wxg.sodproject: 12% user + 35% kernel
1.6% 1225/android.process.media: 1% user + 0.6% kernel
1.3% 263/mpdecision: 0.1% user + 1.2% kernel
0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
0.1% 883/com.android.systemui: 0.1% user + 0% kernel
0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
0% 118/mmcqd/0: 0% user + 0% kernel
0% 179/surfaceflinger: 0% user + 0% kernel
0% 46/kinteractiveup: 0% user + 0% kernel
0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
0% 239/sdcard: 0% user + 0% kernel
0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait
You can use the below code to format it to two decimal places
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];
NSLog(@"Result...%@",numberString);//Result 22.37
Swift 4:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .up
let str = String(describing: formatter.string(from: 12.2345)!)
print(str)
Is contextmenu
an event?
I would use onmousedown
or onclick
then grab the MouseEvent
's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).
df.drop(labels=df[df.index % 3 != 0].index, axis=0) # every 3rd row (mod 3)
Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.
cd ~/.janus/snipmate-snippets
git submodule add <git@github ...> snippets
(Bouke Versteegh comments that you don't have to use /.
, as in snippets/.
: snippets
is enough)
See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:
submodule: drop the top-level requirement
Use the new
rev-parse --prefix
option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.Since the interpretation of a relative submodule URL depends on whether or not "
remote.origin.url
" is configured, explicitly block relative URLs in "git submodule add
" when not at the top level of the working tree.Signed-off-by: John Keeping
Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f
This makes '
git rev-parse
' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.This is useful for shell scripts where we may want to
cd
to the top of the working tree but need to handle relative paths given by the user on the command line.
You should download chgcolor.zip from http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html and also download echoj.zip from www.mailsend-online.com/blog/?p=41 They're both towards the bottom of the page. Extract both folders to the desktop and copy the executables(.exe files) from inside the extracted folders to the C:\Windows directory. This will allow them to be executed from the command line. Open up notepad and copy the following into it:
@echo off
chgcolor 03
echoj "hi "
chgcolor 0d
echoj "world"
chgcolor 07
echoj $0a
Save the file to the Desktop as hi.bat. Now open the command prompt and navigate to your Desktop folder and type "hi.bat" without the quotes. That should get you started besure to read both webpages to get a full tutorial.
Empty slice and nil slice are initialized differently in Go:
var nilSlice []int
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}
fmt.Println(nilSlice == nil) // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false
As for all three slices, len and cap are 0.
If you're using Windows it's not possible - read below. You can use the local address of your machine instead and then you'll be able to capture stuff. See CaptureSetup/Loopback.
Summary: you can capture on the loopback interface on Linux, on various BSDs including Mac OS X, and on Digital/Tru64 UNIX, and you might be able to do it on Irix and AIX, but you definitely cannot do so on Solaris, HP-UX....
Although the page mentions that this is not possible on Windows using Wireshark alone, you can actually record it using a workaround as mentioned in a different answer.
EDIT: Some 3 years later, this answer is no longer completely correct. The linked page contains instructions for capturing on the loopback interface.
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass@dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
<html>
<head>
<title>Date picker works for all browsers(IE, Firefox, Chrome)</title>
<script>
var datefield = document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script>
if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($) { // on document.ready
$('#start_date').datepicker({
dateFormat: 'yy-mm-dd'
});
$('#end_date').datepicker({
dateFormat: 'yy-mm-dd'
});
})
}
</script>
</head>
<body>
<input name="start_date" id="start_date" type="date" required>
<input name="end_date" id="end_date" required>
</body>
</html>
Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though
Note, the parentheses are required for UPDATE statements:
update top (100) table1 set field1 = 1
Cardview
is a bit coy. I had list of colors in my structure and Model is like
class ModelColor : Serializable {
var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE
constructor(id: Int?, title: String?, color: Int?) {
this.id = id
this.title = title
this.color = color
}
}
load the model with color, last item on constructure taking from R.color
list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))
and finaly you can setBackgriundResource
cv_add_goal_choose_color.setBackgroundResource(color)
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
As in the comments, there's no default editor set - strange - the $EDITOR
environment variable is empty. You can log in into a container with:
docker exec -it <container> bash
And run:
apt-get update
apt-get install vim
Or use the following Dockerfile:
FROM confluent/postgres-bw:0.1
RUN ["apt-get", "update"]
RUN ["apt-get", "install", "-y", "vim"]
Docker images are delivered trimmed to the bare minimum - so no editor is installed with the shipped container. That's why there's a need to install it manually.
EDIT
I also encourage you read my post about the topic.
What about using the a
option?
According to the docs:
'a+' - Open file for reading and appending. The file is created if it does not exist.
It seems to work perfectly with createWriteStream
-Djava.security.egd=file:/dev/./urandom should be right! not -Djava.security.egd=file:/dev/../dev/urandom or -Djava.security.egd=file:///dev/urandom
fs/promises and fs.Dirent
Here's an efficient, non-blocking ls
program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist
or fs.stat
calls on every path -
// main.js
import { readdir } from "fs/promises"
import { join } from "path"
async function* ls (path = ".")
{ yield path
for (const dirent of await readdir(path, { withFileTypes: true }))
if (dirent.isDirectory())
yield* ls(join(path, dirent.name))
else
yield join(path, dirent.name)
}
async function* empty () {}
async function toArray (iter = empty())
{ let r = []
for await (const x of iter)
r.push(x)
return r
}
toArray(ls(".")).then(console.log, console.error)
Let's get some sample files so we can see ls
working -
$ yarn add immutable # (just some example package)
$ node main.js
[
'.',
'main.js',
'node_modules',
'node_modules/.yarn-integrity',
'node_modules/immutable',
'node_modules/immutable/LICENSE',
'node_modules/immutable/README.md',
'node_modules/immutable/contrib',
'node_modules/immutable/contrib/cursor',
'node_modules/immutable/contrib/cursor/README.md',
'node_modules/immutable/contrib/cursor/__tests__',
'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
'node_modules/immutable/contrib/cursor/index.d.ts',
'node_modules/immutable/contrib/cursor/index.js',
'node_modules/immutable/dist',
'node_modules/immutable/dist/immutable-nonambient.d.ts',
'node_modules/immutable/dist/immutable.d.ts',
'node_modules/immutable/dist/immutable.es.js',
'node_modules/immutable/dist/immutable.js',
'node_modules/immutable/dist/immutable.js.flow',
'node_modules/immutable/dist/immutable.min.js',
'node_modules/immutable/package.json',
'package.json',
'yarn.lock'
]
For added explanation and other ways to leverage async generators, see this Q&A.
May be the storage folder doesn't have the app and framework folder and necessary permission. Inside framework folder it contains cache, sessions, testing and views. use following command this will works.
Use command line to go to your project root:
cd {your_project_root_directory}
Now copy past this command as it is:
cd storage && mkdir app && cd app && mkdir public && cd ../ && mkdir framework && cd framework && mkdir cache && mkdir sessions && mkdir testing && mkdir views && cd ../../ && sudo chmod -R 777 storage/
I hope this will solve your use.
in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.
If your vectors are sorted*, check out set_union from <algorithm>.
set_union(A.begin(), A.end(), B.begin(), B.end(), AB.begin());
There's a more thorough example in the link
*thanks rlbond
The most obvious solution to me is to use the key
keyword arg.
>>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
>>> keydict = dict(zip(X, Y))
>>> X.sort(key=keydict.get)
>>> X
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Note that you can shorten this to a one-liner if you care to:
>>> X.sort(key=dict(zip(X, Y)).get)
As Wenmin Mu and Jack Peng have pointed out, this assumes that the values in X
are all distinct. That's easily managed with an index list:
>>> Z = ["A", "A", "C", "C", "C", "F", "G", "H", "I"]
>>> Z_index = list(range(len(Z)))
>>> Z_index.sort(key=keydict.get)
>>> Z = [Z[i] for i in Z_index]
>>> Z
['A', 'C', 'H', 'A', 'C', 'C', 'I', 'F', 'G']
Since the decorate-sort-undecorate approach described by Whatang is a little simpler and works in all cases, it's probably better most of the time. (This is a very old answer!)
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
I do that the following way:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
Here is a full example with the date formatted in YYYY-MM-DD
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//cdn.jsdelivr.net/webshim/1.14.5/polyfiller.js"></script>
<script>
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
$.webshims.formcfg = {
en: {
dFormat: '-',
dateSigns: '-',
patterns: {
d: "yy-mm-dd"
}
}
};
</script>
<input type="date" />
Similar to sixty9 I renamed java.exe, javaw.exe, javaws.exe (I never delete files when troubleshooting) after I created a JAVA_HOME
environment variable and added path variables.
I had installed the Java SDK on my D:\ drive ( instead of the default).
Create a JAVA_HOME variable: Variable Name: %JAVA_HOME%
Value: D:\Program Files\Java.
Added the following to the Path variable:
%JAVA_HOME%\jre7\bin;%JAVA_HOME%\jdk1.7.0_03\bin;
Renamed java.exe
, javaw.exe
and javaws.exe
.
Restarted the system and the Android SDK
installer found my JDK and installed successfully.
Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games:
import cookielib
import urllib
import urllib2
# set these to whatever your fb account is
fb_username = "[email protected]"
fb_password = "secretpassword"
class WebGamePlayer(object):
def __init__(self, login, password):
""" Start up... """
self.login = login
self.password = password
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
You won't necessarily need the HTTPS or Redirect handlers, but they don't hurt, and it makes the opener much more robust. You also might not need cookies, but it's hard to tell just from the form that you've posted. I suspect that you might, purely from the 'Remember me' input that's been commented out.
Go to
Tools > Compatibility View settings > Uncheck the option "Display intranet sites in Compatibility View"
.
Click on Close
. It may re-launch the page and then your problem would be resolved.
(Just in case someone else is blind like me)
form
FTW! Make sure to use <form>
tag
wont work:
<div (ngSubmit)="search()" #f="ngForm" class="input-group">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Go!</button>
</span>
<input type="text" ngModel class="form-control" name="search" placeholder="Search..." aria-label="Search...">
</div>
works like charm:
<form (ngSubmit)="search()" #f="ngForm" class="input-group">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Go!</button>
</span>
<input type="text" ngModel class="form-control" name="search" placeholder="Search..." aria-label="Search...">
</form>
Just leave out the "dot-slash" ./
:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
Though, if you wanted to, you could use .\
and it would work.
D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"
If you use random
instead of * random
your code not give any error
These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.
Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):
psql -h host -p 5900 -U username database
\pset format aligned
You can do an interactive rebase and choose edit for the commit whose date you would like to alter. When the rebase process stops for amending the commit you type in for instance:
git commit --amend --date="Wed Feb 16 14:00 2011 +0100"
Afterwards you continue your interactive rebase.
UPDATE (in response to the comment of studgeek): to change the commit date instead of the author date:
GIT_COMMITTER_DATE="Wed Feb 16 14:00 2011 +0100" git commit --amend
The lines above set an environment variable GIT_COMMITTER_DATE which is used in amend commit.
Everything is tested in Git Bash.
It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.
if len(sys.argv) >= 2:
startingpoint = sys.argv[1]
else:
startingpoint = 'blah'
While most of these answers are correct to varying degrees, none of them are as succinct as I would like.
Put simply, using while True:
is just a way of running a loop that will continue to run until you explicitly break out of it using break
or return
. Since True will always evaluate to True, you have to force the loop to end when you want it to.
while True:
# do stuff
if some_condition:
break
# do more stuff - code here WILL NOT execute when `if some_condition:` evaluates to True
While normally a loop would be set to run until the while condition is false, or it reaches a predefined end point:
do_next = True
while do_next:
# do stuff
if some_condition:
do_next = False
# do more stuff - code here WILL execute even when `if some_condition:` evaluates to True
Those two code chunks effectively do the same thing
If the condition your loop evaluates against is possibly a value not directly in your control, such as a user input value, then validating the data and explicitly breaking out of the loop is usually necessary, so you'd want to do it with either method.
The while True
format is more pythonic since you know that break
is breaking the loop at that exact point, whereas do_next = False
could do more stuff before the next evaluation of do_next
.
I'm writing this answer in 2015, and for some reason (probably older versions of jQuery) none of the other answers have worked for me. I mean, they change the selected index, but it doesn't actually reflect on the actual dropdown.
Here is another way to change the index, and actually have it reflect in the dropdown:
$('#mydropdown').val('first').change();
I think this is it:
sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10
Using Debian alternatives.
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.
We can do like:
data = $form.serialize() + "&foo=bar";
For example:
var userData = localStorage.getItem("userFormSerializeData");
var userId = localStorage.getItem("userId");
$.ajax({
type: "POST",
url: postUrl,
data: $(form).serialize() + "&" + userData + "&userId=" + userId,
dataType: 'json',
success: function (response) {
//do something
}
});
Ted Hopp answered this quite nicely. I have been using res/raw for my opengl texture and shader files. I was thinking about moving them to an assets directory to provide a hierarchical organization.
This thread convinced me not to. First, because I like the use of a unique resource id. Second because it's very simple to use InputStream/openRawResource or BitmapFactory to read in the file. Third because it's very useful to be able to use in a portable library.
I've adopted Crazy Yoghurt's answer to swift's extensions.
extension UILabel {
func boldRange(_ range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
func boldSubstring(_ substr: String) {
if let text = self.attributedText {
var range = text.string.range(of: substr)
let attr = NSMutableAttributedString(attributedString: text)
while range != nil {
let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
var nsRange = NSMakeRange(start, length)
let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
break
}
range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
}
if let r = range {
boldRange(r)
}
}
}
}
May be there is not good conversion between Range and NSRange, but I didn't found something better.
Pandas version 0.21 has changed the drop
method slightly to include both the index
and columns
parameters to match the signature of the rename
and reindex
methods.
df.drop(columns=['column_a', 'column_c'])
Personally, I prefer using the axis
parameter to denote columns or index because it is the predominant keyword parameter used in nearly all pandas methods. But, now you have some added choices in version 0.21.
javascript's parseFloat doesn't take a locale parameter. So you will have to replace ,
with .
parseFloat('0,04'.replace(/,/, '.')); // 0.04
I hope it doesn't get deprecated. While writing <? blah code ?>
is fairly unnecessary and confusable with XHTML, <?=
isn't, for obvious reasons. Unfortunately I don't use it, because short_open_tag seems to be disabled more and more.
Update: I do use <?=
again now, because it is enabled by default with PHP 5.4.0.
See http://php.net/manual/en/language.basic-syntax.phptags.php
In PHP5, you should use the Document Object Model class instead. Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
I found the solution.
Variable value should be C:\Users\dipanwita.neogy\Anaconda3\Scripts
Here is what I did
ul {_x000D_
display: block;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
ul li{_x000D_
display: block;_x000D_
min-width: calc(30% - 10px);_x000D_
float: left;_x000D_
}_x000D_
_x000D_
ul li:nth-child(2n + 1){_x000D_
clear: left;_x000D_
}
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<li>0</li>_x000D_
</ul>
_x000D_
This one has been answered already here: Python memory profiler
Basically you do something like that (cited from Guppy-PE):
>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 objects. Total size = 3265516 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 25773 53 1612820 49 1612820 49 str
1 11699 24 483960 15 2096780 64 tuple
2 174 0 241584 7 2338364 72 dict of module
3 3478 7 222592 7 2560956 78 types.CodeType
4 3296 7 184576 6 2745532 84 function
5 401 1 175112 5 2920644 89 dict of class
6 108 0 81888 3 3002532 92 dict (no owner)
7 114 0 79632 2 3082164 94 dict of type
8 117 0 51336 2 3133500 96 type
9 667 1 24012 1 3157512 97 __builtin__.wrapper_descriptor
<76 more rows. Type e.g. '_.more' to view.>
>>> h.iso(1,[],{})
Partition of a set of 3 objects. Total size = 176 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 33 136 77 136 77 dict (no owner)
1 1 33 28 16 164 93 list
2 1 33 12 7 176 100 int
>>> x=[]
>>> h.iso(x).sp
0: h.Root.i0_modules['__main__'].__dict__['x']
>>>
I have used this small snippet. Might be slower but works every time.
for i in 'find . -type f -name "*.jar"'; do
jar tvf $i | grep "com.foo.bar.MyClass.clss";
if [ $? -eq 0 ]; then echo $i; fi;
done
This is an issue when migrating from gulp version 3 to 4, Simply you can add a parameter done to the call back function , see example,
const gulp = require("gulp")
gulp.task("message", function(done) {
console.log("Gulp is running...")
done()
});
With the following command:
:%s/^M$//g
To get the ^M
to appear, type CtrlV and then CtrlM. CtrlV tells Vim to take the next character entered literally.
In case if there are some characters possible between digits (e.g. thousands separators), you may try following:
declare @table table (DirtyCol varchar(100))
insert into @table values
('AB ABCDE # 123')
,('ABCDE# 123')
,('AB: ABC# 123')
,('AB#')
,('AB # 1 000 000')
,('AB # 1`234`567')
,('AB # (9)(876)(543)')
;with tally as (select top (100) N=row_number() over (order by @@spid) from sys.all_columns),
data as (
select DirtyCol, Col
from @table
cross apply (
select (select C + ''
from (select N, substring(DirtyCol, N, 1) C from tally where N<=datalength(DirtyCol)) [1]
where C between '0' and '9'
order by N
for xml path(''))
) p (Col)
where p.Col is not NULL
)
select DirtyCol, cast(Col as int) IntCol
from data
Output is:
DirtyCol IntCol
--------------------- -------
AB ABCDE # 123 123
ABCDE# 123 123
AB: ABC# 123 123
AB # 1 000 000 1000000
AB # 1`234`567 1234567
AB # (9)(876)(543) 9876543
For update, add ColToUpdate
to select list of the data
cte:
;with num as (...),
data as (
select ColToUpdate, /*DirtyCol, */Col
from ...
)
update data
set ColToUpdate = cast(Col as int)
You can try using this code:
protected ServiceConnection mServerConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "onServiceDisconnected");
}
}
public void start() {
// mContext is defined upper in code, I think it is not necessary to explain what is it
mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
mContext.startService(intent);
}
public void stop() {
mContext.stopService(new Intent(mContext, ServiceRemote.class));
mContext.unbindService(mServerConn);
}
These specific lines are the usual wrapper for jQuery plugins:
"...to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Try this, I work myself to do so
\i 'somedir\\script2.sql'
The solution might be updating some tools.
Here's my scenario from 2020 with Ruby and Python:
I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
So what was still trying to use that old 1.0 version?
It tuned out it was Ruby 2.5.5.
So I just installed Ruby 2.5.8 and removed the old one.
Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.
Here is another way to display PDF inside Div by using Iframe like below.
<div>_x000D_
<iframe src="/pdf/test.pdf" style="width:100%;height:700px;"></iframe>_x000D_
</div>_x000D_
<div>_x000D_
<!-- I agree button -->_x000D_
</div>
_x000D_
For some strange reason the SelectElement
for webdriver (version 2.25.1.0) does not properly work with the firefoxdriver (Firefox 15). Sometimes it may not select an option from a dropdownlist. It does, however, seem to work with the chromedriver... This is a link to the chromedriver... just drop it in the bin dir.
In the html form, you need to supply additional viewstate variable and disable ViewState in a server page. This requires some control on both sides , though.
Form HTML:
<html><body> <form id='postForm' action='WebForm.aspx' method='POST'>
<input type='text' name='postData' value='base-64-encoded-value' />
<input type='hidden' name='__VIEWSTATE' value='' /> <!-- still need __VIEWSTATE, even empty one -->
</form>
</body></html>
Note empty __VIEWSTATE.
WebForm.aspx:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm.aspx.cs" Inherits="WebForm"
EnableEventValidation="False" EnableViewState="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="postForm" runat="server">
<asp:TextBox ID="postData" runat="server"></asp:TextBox>
<div>
</div>
</form>
</body>
</html>
Note EnableEventValidation="False", EnableViewState="false"
to prevent validation error for empty view state.
Code Behind/Inherits values are not precise.
WebForm.cs:
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));
}
}
This is really a set of configurations for your editor to understand Laravel.
If you want to configure it all manually, here is the repo. This is for both VS code and PhpStorm.
Or if you want you can download this package.(I created) recommended to install it globally.
And then just run andylaravel setupIDE
. this will configure everything for you according to the fist repo.
If your string contains numbers only, you can make it an integer and then do padding:
String.format("%010d", Integer.parseInt(mystring));
To do it you need to have a bit of code like my example here:
file = open("Task1.csv")
numline = len(file.readlines())
print (numline)
I hope this helps everyone.
Don't over complicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,
var IE_version=(-1/*@cc_on,@_jscript_version@*/);
Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it
Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:
var IE_version=(-1/*@cc_on,@_jscript_version@*/);_x000D_
if (IE_version!==-1){_x000D_
document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");_x000D_
} else {_x000D_
document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");_x000D_
}
_x000D_
This works based on the fact that conditional comments are only visible in older versions of Internet Explorer, and IE sets @_jscript_version
to the version of the browser. For example, if you are using Internet Explorer 7, then @_jscript_version
will be set to 7
, thus, the postprocessed javascript that will be executed will actually look like this:
var IE_version=(-1,7);
which gets evaluated to 7.
If you happen to be using Microsoft IIS server, in addition to the php.ini settings mentioned by others, you may need to increase the execution timeout settings for the PHP FastCGI application in the IIS Server Manager:
Step 1) Open the IIS Server Manager (usually under Server Manager in the Start Menu, then Tools / Internet Information Services (IIS) Manager).
Step 2) Click on the main connection (not specific to any particular domain).
Step 3) Under the IIS section, find FastCGI Settings (shown below).
Step 4) Therein, right-click the PHP application and select Edit....
Step 5) Check the timeouts (shown below).
In my case, the default timeouts here were 70 and 90 seconds; the former of which was causing a 500 Internal Server Error on PHP scripts that took longer than 70 seconds.
One important consideration that I think everybody is missing here is a load-balancing (web farm) scenario. Since the server that's executing global.asax may be different than the server that's about the execute the custom error page, stashing the exception object in Application is not reliable.
I'm still looking for a reliable solution to this problem in a web farm configuration, and/or a good explanation from MS as to why you just can't pick up the exception with Server.GetLastError on the custom error page like you can in global.asax Application_Error.
P.S. It's unsafe to store data in the Application collection without first locking it and then unlocking it.
In a Ubuntu/Debian based distro, you could use apt-file
to find the name of the exact package that includes the missing header file.
# do this once
sudo apt-get install apt-file
sudo apt-file update
$ apt-file search lber.h
libldap2-dev: /usr/include/lber.h
As you could see from the output of apt-file search lber.h
, you'd just need to install the package libldap2-dev
.
sudo apt-get install libldap2-dev
I will just make things clear. TCP/UDP are two cars are that being driven on the road. suppose that traffic signs & obstacles are Errors TCP cares for traffic signs, respects everything around. Slow driving because something may happen to the car. While UDP just drives off, full speed no respect to street signs. Nothing, a mad driver. UDP doesn't have error recovery, If there's an obstacle, it will just collide with it then continue. While TCP makes sure that all packets are sent & received perfectly, No errors , so , the car just passes obstacles without colliding. I hope this is a good example for you to understand, Why UDP is preferred in gaming. Gaming needs speed. TCP is preffered in downloads, or downloaded files may be corrupted.
Firstly you need to add a where T:class
constraint - you can't call GetValue
on value types unless they're passed by ref
.
Secondly GetValue
is very slow and gets called a lot.
To get round this we can create a delegate and call that instead:
MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );
The problem is that we don't know TProperty
, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:
public class ReflectionUtility
{
internal static Func<object, object> GetGetter(PropertyInfo property)
{
// get the get method for the property
MethodInfo method = property.GetGetMethod(true);
// get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
"GetGetterHelper",
BindingFlags.Static | BindingFlags.NonPublic);
// reflection call to the generic get-method generator to generate the type arguments
MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
method.DeclaringType,
method.ReturnType);
// now call it. The null argument is because it's a static method.
object ret = constructedHelper.Invoke(null, new object[] { method });
// cast the result to the action delegate and return it
return (Func<object, object>) ret;
}
static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
where TTarget : class // target must be a class as property sets on structs need a ref param
{
// Convert the slow MethodInfo into a fast, strongly typed, open delegate
Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);
// Now create a more weakly typed delegate which will call the strongly typed one
Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
return ret;
}
}
So now your method becomes:
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
where T: class
{
// ... create table the same way
var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
{
Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
propGetters.Add(func);
}
// Add the property values per T as rows to the datatable
foreach (var item in items)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
//values[i] = props[i].GetValue(item, null);
values[i] = propGetters[i](item);
}
table.Rows.Add(values);
}
return table;
}
You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.
What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.
To resolve this with RegEx, you need to use the multiline flag (?m):
((Get-Content file.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content file.txt
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
public static class ErrorCode
{
public const IDictionary<string , string > m_ErrorCodeDic;
public static ErrorCode()
{
m_ErrorCodeDic = new Dictionary<string, string>()
{ {"1","User name or password problem"} };
}
}
Probably initialise in the constructor.
Change the window name in your two different calls:
function popitup(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.
Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):
$.ajax({
type: 'POST',
url: http://theappurl.com/api/v1/method/,
data: {},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
}
});
If using @worldofjr answer in jQuery you are getting error:
e.relatedTarget.data is not a function
you should use:
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
Not that e.relatedTarget
if wrapped by $(..)
I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.
Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:
import javax.swing.JOptionPane;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
}
The first JOptionPane
parameter (null
in this example) is used to align the dialog. null
causes it to center itself on the screen, however any java.awt.Component
can be specified and the dialog will appear in the center of that Component
instead.
I tend to use the titleBar
String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.
As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
/* By specifying a null headerMessage String, we cause the dialog to
not have a header */
infoBox(infoMessage, titleBar, null);
}
public static void infoBox(String infoMessage, String titleBar, String headerMessage)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(titleBar);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
alert.showAndWait();
}
}
One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
or
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");
Placing a $
in front of the row value to keep constant worked well for me. e.g.
=b2+a$1
I don't think that has any meaning in SQL. You might be looking at Prepared Statements in JDBC or something. In that case, the question marks are placeholders for parameters to the statement.
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe
showing the user's C:
drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
You can modify with the following
<li><a href="./Index" class="elements"><span>Clients</span></a></li>
The extra dot means you are in the same controller. If you want change the controller to a different controller then you can write this
<li><a href="../newController/Index" class="elements"><span>Clients</span></a></li>
Is your type really arbitrary? If you know it is just going to be a int float or string you could just do
if val.dtype == float and np.isnan(val):
assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN
This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)
// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;
// Rotation information
double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
If you really don't want to use numpy
you can do something like this:
def matmult(a,b):
zip_b = zip(*b)
# uncomment next line if python 3 :
# zip_b = list(zip_b)
return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))
for col_b in zip_b] for row_a in a]
x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
y = [[1,2],[1,2],[3,4]]
import numpy as np # I want to check my solution with numpy
mx = np.matrix(x)
my = np.matrix(y)
Result:
>>> matmult(x,y)
[[12, 18], [27, 42], [42, 66], [57, 90]]
>>> mx * my
matrix([[12, 18],
[27, 42],
[42, 66],
[57, 90]])
Try this: use "%40" in place of the "@"
If you are using php you can add any function to your sql statement by using: SQLite3::createFunction. In PDO you can use PDO::sqliteCreateFunction and implement the preg_match function within your statement:
See how its done by Havalite (RegExp in SqLite using Php)
Joanna Avalos answer is better, Just note that I replaced .text()
to .html()
, otherwise, some of the html elements inside that will be destroyed.
As you showed convincingly, the font-size: 100%;
will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.
I believe font-size: 100%;
can be very useful when combining it with em
-based design. As this article shows, this will create a very flexible website.
When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.
QTcreator obeys your kde-wide configurations. If you choose "obsidian-coast" as the system-wide color scheme qt creator will be all dark as well. I know it is a partial solution but it works.
That basically means that you need to import the .h file containing the declaration of States.
However, there is a lot of other stuff wrong with your code.
+alloc
'ing it. That won't work[super init]
in -init
.@class
in the header, but never imported the class.you can do like this :
<?php
$file = 'your_images.jpg';
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file));
echo file_get_contents($file);
?>
Update3: 06.2019 Some of the comments says that the answer is not clear, I'll try to clarify.
TL;DR:
Q: Can Windows containers run on Linux?
A: No. They cannot. Containers are using the underlying Operating System resources and drivers, so Windows containers can run on Windows only, and Linux containers can run on Linux only.
Q: But what about Docker for Windows? Or other VM-based solutions?
A: Docker for Windows allows you to simulate running Linux containers on Windows, but under the hood a Linux VM is created, so still Linux containers are running on Linux, and Windows containers are running on Windows.
Bonus: Read this very nice article about running Linux docker containers on Windows.
Q: So, what should I do with a .Net Framework 462 app, if I would like to run in a container?
A: It depends. Following several recommendations:
If you cannot migrate to .Net Core - As @Sebastian mentioned - you can convert your libraries to .Net Standard, and have 2 versions of app - one on .Net Framework 4.6.2, and one on .Net Core - it is not always obvious, Visual Studio supports it pretty well (with multi-targeting), but some dependencies can require extra care.
(Less recommended) In some cases, you can run windows containers. Windows containers are becoming more and more mature, with better support in platforms like Kubernetes. But to be able to run .Net Framework code, you still need to run on base image of "Server Core", which occupies about 1.4 GB. In same rare cases, you can migrate your code to .Net Core, but still run on Windows Nano servers, with an image size of 95 MB.
Leaving also the old updates for history
Update2: 08.2018 If you are using Docker-for-Windows, you can run now both windows and linux containers simultaneously: https://blogs.msdn.microsoft.com/premier_developer/2018/04/20/running-docker-windows-and-linux-containers-simultaneously/
Bonus: Not directly related to the question, but you can now run not only the linux container itself, but also orchestrator like kubernetes: https://blog.docker.com/2018/07/kubernetes-is-now-available-in-docker-desktop-stable-channel/
Updated at 2018:
Original answer in general is right, BUT several months ago, docker added experimental feature LCOW (official github repository).
From this post:
Doesn’t Docker for Windows already run Linux containers? That’s right. Docker for Windows can run Linux or Windows containers, with support for Linux containers via a Hyper-V Moby Linux VM (as of Docker for Windows 17.10 this VM is based on LinuxKit).
The setup for running Linux containers with LCOW is a lot simpler than the previous architecture where a Hyper-V Linux VM runs a Linux Docker daemon, along with all your containers. With LCOW, the Docker daemon runs as a Windows process (same as when running Docker Windows containers), and every time you start a Linux container Docker launches a minimal Hyper-V hypervisor running a VM with a Linux kernel, runc and the container processes running on top.
Because there’s only one Docker daemon, and because that daemon now runs on Windows, it will soon be possible to run Windows and Linux Docker containers side-by-side, in the same networking namespace. This will unlock a lot of exciting development and production scenarios for Docker users on Windows.
Original:
As mentioned in comments by @PanagiotisKanavos, containers are not for virtualization, and they are using the resources of the host machine. As a result, for now windows container cannot run "as-is" on linux machine.
But - you can do it by using VM - as it works on windows. You can install windows VM on your linux host, which will allow to run windows containers.
With it, IMHO run it this way on PROD environment will not be the best idea.
Also, this answer provides more details.
Be sure to include the Key
in the imports...
const {Builder, By, logging, until, Key} = require('selenium-webdriver');
searchInput.sendKeys(Key.ENTER)
worked great for me
Someone else already proposed Burkhard-Keller-Trees, but I thought I might mention them again in order to plug my own implementation. :)
http://well-adjusted.de/mspace.py/index.html
There are faster implementations around (see ActiveState's Python recipes or implementations in other languages), but I think/hope my code helps to understand these data structures.
By the way, both BK and VP trees can be used for much more than searching for similar strings. You can do similarity searches for arbitrary objects as long as you have a distance function that satisfies a few conditions (positivity, symmetry, triangle inequality).
Using split and regex :
var str = "fooBar0123".split(/(\d+)/);
console.log(str[0]); // fooBar
console.log(str[1]); // 0123
Create a view and set this as background view of the cell
UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
[lab setBackgroundColor:[UIColor grayColor]];
cell.backgroundView = lab;
[lab release];
public class Example1 extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.frame_container);
//above part is to determine which fragment is in your frame_container
setFragment(fragmentDemo);
(OR)
setFragment(new TestFragment1());
}
// This could be moved into an abstract BaseActivity
// class for being re-used by several instances
protected void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
}
To add a fragment into a Activity or FramentActivity it requires a Container. That container should be a "
Framelayout
", which can be included in xml or else you can use the default container for that like "android.R.id.content
" to remove or replace a fragment in Activity.
main.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/imagenext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="@drawable/next" />
</RelativeLayout>
Here is some code that I recently wrote. I think that it provides a basic explanation of combining class/ID names with pseudoclasses.
.content {_x000D_
width: 800px;_x000D_
border: 1px solid black;_x000D_
border-radius: 10px;_x000D_
box-shadow: 0 0 5px 2px grey;_x000D_
margin: 30px auto 20px auto;_x000D_
/*height:200px;*/_x000D_
_x000D_
}_x000D_
p.red {_x000D_
color: red;_x000D_
}_x000D_
p.blue {_x000D_
color: blue;_x000D_
}_x000D_
p#orange {_x000D_
color: orange;_x000D_
}_x000D_
p#green {_x000D_
color: green;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Class practice</title>_x000D_
<link href="wrench_favicon.ico" rel="icon" type="image/x-icon" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="content">_x000D_
<p id="orange">orange</p>_x000D_
<p id="green">green</p>_x000D_
<p class="red">red</p>_x000D_
<p class="blue">blue</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
HTML Code
<section style="background-color:rgb(237.247.249);">
<h2>Test of select menu (SelectboxIt plugin)</h2>
<select name="select_this" id="testselectset">
<option value="01">Option 1</option>
<option value="02">Option 2</option>
<option value="03">Option 3</option>
<option value="04">Option 4</option>
<option value="05">Option 5</option>
<option value="06">Option 6</option>
<option value="07">Option 7 with a really, really long text line that we shall use in order to test the wrapping of text within an option or optgroup</option>
<option value="08">Option 8</option>
<option value="09">Option 9</option>
<option value="10">Option 10</option>
</select>
</section>
Javascript Code
$(function(){
$("#testselectset").selectBoxIt({
theme: "default",
defaultText: "Make a selection...",
autoWidth: false
});
});
CSS Code
.selectboxit-container .selectboxit, .selectboxit-container .selectboxit-options {
width: 400px; /* Width of the dropdown button */
border-radius:0;
max-height:100px;
}
.selectboxit-options .selectboxit-option .selectboxit-option-anchor {
white-space: normal;
min-height: 30px;
height: auto;
}
and you have to add some Jquery Library select Box Jquery CSS
Please check this link JsFiddle Link
Try this to Change content of div using jQuery.
See more @ Change content of div using jQuery
$(document).ready(function(){
$("#Textarea").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$(".output").text(currentText);
});
});
In my case I had into the manifest file an invalid tag structure, I had an opened activity closed but inside it where were ore activities (...)
which invalidates file correctness, to find it it took quite two hours, error reported missing/unknown <activity>
.
This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.
#!usr/bin/python
from thread import *
import socket
import sys
def clientthread(conn):
buffer=""
while True:
data = conn.recv(8192)
buffer+=data
print buffer
#conn.sendall(reply)
conn.close()
def main():
try:
host = '192.168.1.3'
port = 6666
tot_socket = 26
list_sock = []
for i in range(tot_socket):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host, port+i))
s.listen(10)
list_sock.append(s)
print "[*] Server listening on %s %d" %(host, (port+i))
while 1:
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
except KeyboardInterrupt as msg:
sys.exit(0)
if __name__ == "__main__":
main()
Let's say in Swift 4 you have a button set up for a segue as an IBAction
like this @IBAction func nextLevel(_ sender: UIButton) {}
and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:
var appMode = 0
@IBAction func mySegue(_ sender: UIButton) {
if appMode == 1 { // avoid crash if button pressed during other app actions and/or conditions
let conflictingAction = sender as UIButton
conflictingAction.isEnabled = false
}
}
Please note that you will likely have other conditions within if appMode == 0
and/or if appMode == 1
that will still occur and NOT conflict with the mySegue
button. Thus, AVOIDING A CRASH.
Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:
The list is ordered by precedence (with values from lower items overriding earlier ones).
More info you can find here https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
I had tha same problem trying to compile a lib I download from the internet. In my case, there was already a #include <cstdint>
in the code. I solved it adding a:
using std::uint32_t;
This is also handy when checking if an object is a type of a class:
if someObject is SomeClass {
//someObject is a type of SomeClass
}
This should work for you
//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();
//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max();
(From here)
What worked for me was restarting IIS
I had to remove packages folder close and re-open (VS2015) solution. I was not migrating and I did not have packages checked into source control. All I can say is something got messed up and this fixed it.
I've done something like this.
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if ((sender as Form).ActiveControl is Button)
{
//CloseButton
}
else
{
//The X has been clicked
}
}
Actually None
is much better for "magic" values:
class Cheese():
def __init__(self, num_holes = None):
if num_holes is None:
...
Now if you want complete freedom of adding more parameters:
class Cheese():
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes',random_holes())
To better explain the concept of *args
and **kwargs
(you can actually change these names):
def f(*args, **kwargs):
print 'args: ', args, ' kwargs: ', kwargs
>>> f('a')
args: ('a',) kwargs: {}
>>> f(ar='a')
args: () kwargs: {'ar': 'a'}
>>> f(1,2,param=3)
args: (1, 2) kwargs: {'param': 3}
UPDATE: The image size Must be larger than (600 x 315px)
The image size can be any size because Faceboook re-size the image width & height.
The default height is 208px
& width is 398px
for a post permalink:
www.facebook.com/{username}/posts/{post_id}
But for a timeline view:
www.facebook.com/{username}
width is 377px
& height is 197px
I hope this will help you!
x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9')
I had the problem with not working curl on win8 wamp3 php5.6. Reinstalling wamp (x64 version as I had x64 in system info) made it work fine.
set_value
has been deprecated. You can now use DataFrame.at
to set by label, and DataFrame.iat
to set by integer position.
at
/iat
# Setup
df = pd.DataFrame({'A': [12, 23], 'B': [['a', 'b'], ['c', 'd']]})
df
A B
0 12 [a, b]
1 23 [c, d]
df.dtypes
A int64
B object
dtype: object
If you want to set a value in second row of the "B" to some new list, use DataFrane.at
:
df.at[1, 'B'] = ['m', 'n']
df
A B
0 12 [a, b]
1 23 [m, n]
You can also set by integer position using DataFrame.iat
df.iat[1, df.columns.get_loc('B')] = ['m', 'n']
df
A B
0 12 [a, b]
1 23 [m, n]
ValueError: setting an array element with a sequence
?I'll try to reproduce this with:
df
A B
0 12 NaN
1 23 NaN
df.dtypes
A int64
B float64
dtype: object
df.at[1, 'B'] = ['m', 'n']
# ValueError: setting an array element with a sequence.
This is because of a your object is of float64
dtype, whereas lists are object
s, so there's a mismatch there. What you would have to do in this situation is to convert the column to object first.
df['B'] = df['B'].astype(object)
df.dtypes
A int64
B object
dtype: object
Then, it works:
df.at[1, 'B'] = ['m', 'n']
df
A B
0 12 NaN
1 23 [m, n]
Even more wacky, I've found you can hack through DataFrame.loc
to achieve something similar if you pass nested lists.
df.loc[1, 'B'] = [['m'], ['n'], ['o'], ['p']]
df
A B
0 12 [a, b]
1 23 [m, n, o, p]
You can read more about why this works here.
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
I came up with a simple solution.
I have a model.cs class with:
private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }
I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />
Here is my converter:
public class RadioBoolToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int integer = (int)value;
if (integer==int.Parse(parameter.ToString()))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
And of course, in Window1's resources:
<Window.Resources>
<local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>
ObjectFactory fact = new ObjectFactory();
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
The Spinner should fire an "OnItemSelected" event when something is selected:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
I'd start by using glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
From now on is better to use the .prop() function instead of the .attr() one.
Here the jQuery documentation:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.
var div1Class = $('#div1').prop('class');
Simple PHP solution to this:
if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}
As the page is reloaded it will update on screen the new data and clear the $_POST ;)
Instead of linking to the .PDF file, instead do something like
<a href="pdf_server.php?file=pdffilename">Download my eBook</a>
which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value
In Android, application-level meta data is accessed through the Context
reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir
property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Pandas will recognise a value as null if it is a np.nan
object, which will print as NaN
in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan
objects using replace()
, and then call dropna()
on your DataFrame to delete rows with null tenants.
To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants
column:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
Now we replace any empty strings in the Tenants
column with np.nan
objects, like so:
>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
Now we can drop the null values:
>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
There you go:
<i class="glyphicon glyphicon-search"></i>
More information:
http://getbootstrap.com/components/#glyphicons
Btw. you can use this conversion tool, this will also update the code for the icons:
There's no difference - they are the same.
PHP Manual for exit
:
Note: This language construct is equivalent to
die()
.
PHP Manual for die
:
This language construct is equivalent to
exit()
.
You should also try -ggdb instead of -g if you're compiling for Android!
We are now using Qunit with Pavlov and JSTestDriver all together. This approach works well for us.
you can use setAttribute
function in Model to add a custom attribute
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
This works for me
var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });
console.log($(targetOption).val());
Thanks for all the posts.
I know this question is old, but it deserves an answer. I personally prefer to create a WSDL by hand and test for compliance using SoapUI. But sometimes (specially for complex WSDLs), you have three ways to generate one out of an XSD:
I prefer the CXF approach since I'm a CLI guy. If it has a CLI, you can automate (that's my motto). And I like the Spring WS approach the least since it uses a lot of framework specific conventions.
There are more people who know CXF (I believe) than Spring WS. So anything that can throw a learning curve for a new engineer (without any clear advantage or ROI) is something I frown upon.
It should also go w/o saying that any generated WSDL should be tested for validity and compliance (and tweaked till it complies), and that your application publishes a static wsdl (as opposed to returning an auto-generated one.)
It's been my experience that you start with a WS-I compliant wsdl and then your application auto-generates (and returns to consumers) a non-compliant one.
In other words, beware of auto magic.
import time, traceback
def every(delay, task):
next_time = time.time() + delay
while True:
time.sleep(max(0, next_time - time.time()))
try:
task()
except Exception:
traceback.print_exc()
# in production code you might want to have this instead of course:
# logger.exception("Problem while executing repetitive task.")
# skip tasks if we are behind schedule:
next_time += (time.time() - next_time) // delay * delay + delay
def foo():
print("foo", time.time())
every(5, foo)
If you want to do this without blocking your remaining code, you can use this to let it run in its own thread:
import threading
threading.Thread(target=lambda: every(5, foo)).start()
This solution combines several features rarely found combined in the other solutions:
threading.Timer
or whatever), this will terminate the chain. No further executions will happen then, even if the reason of the problem is already fixed. A simple loop and waiting with a simple sleep()
is much more robust in comparison.next_time += delay
instead.Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.
import re, sys
class Reprinter:
def __init__(self):
self.text = ''
def moveup(self, lines):
for _ in range(lines):
sys.stdout.write("\x1b[A")
def reprint(self, text):
# Clear previous text by overwritig non-spaces with spaces
self.moveup(self.text.count("\n"))
sys.stdout.write(re.sub(r"[^\s]", " ", self.text))
# Print new text
lines = min(self.text.count("\n"), text.count("\n"))
self.moveup(lines)
sys.stdout.write(text)
self.text = text
reprinter = Reprinter()
reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")
Your CRON should look like this:
*/5 * * * *
CronWTF is really usefull when you need to test out your CRON settings.
Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.
Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:
#!/usr/bin/php
that way you can call the whole thing like this
*/5 * * * * php /path/to/script.php > /path/to/logfile.log
If you want disable it in Global, you can write a custom middleware, like this
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
then add this class youappname.middlewarefilename.DisableCsrfCheck
to MIDDLEWARE_CLASSES
lists, before django.middleware.csrf.CsrfViewMiddleware
Here is a solution for those, who want to remove it from the database with Entity Framework:
prods.RemoveWhere(s => s.ID == 1);
And the extension method itself:
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace LivaNova.NGPDM.Client.Services.Data.Extensions
{
public static class DbSetExtensions
{
public static void RemoveWhere<TEntity>(this DbSet<TEntity> entities, Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var records = entities
.Where(predicate)
.ToList();
if (records.Count > 0)
entities.RemoveRange(records);
}
}
}
P.S. This simulates the method RemoveAll()
that's not available for DB sets of the entity framework.
I suggest not even using HTML onclick
handlers, and use something more common such as document.getElementById
.
HTML:
<input type="button" id="nodeGoto" />
JavaScript:
document.getElementById("nodeGoto").addEventListener("click", function() {
gotoNode(result.name);
}, false);
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for
git fetch
followed bygit merge
FETCH_HEAD" More precisely,git pull
runsgit fetch
with the given parameters and then callsgit merge
to merge the retrieved branch heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
Disclaimer: I have been exposed to a significant amount of F77
The modern equivalent of goto
(arguable, only my opinion, etc) is explicit exception handling:
Edited to highlight the code reuse better.
Pretend pseudocode in a fake python-like language with goto
:
def myfunc1(x)
if x == 0:
goto LABEL1
return 1/x
def myfunc2(z)
if z == 0:
goto LABEL1
return 1/z
myfunc1(0)
myfunc2(0)
:LABEL1
print 'Cannot divide by zero'.
Compared to python:
def myfunc1(x):
return 1/x
def myfunc2(y):
return 1/y
try:
myfunc1(0)
myfunc2(0)
except ZeroDivisionError:
print 'Cannot divide by zero'
Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
Assign the onclick like this:
divTag.onclick = printWorking;
The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking
).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>
, but this is generally not recommended.
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
You can also just do this in all the activities that you dont want to transition from:
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
I like this approach because you do not have to mess with the style of your activity.
There are multiple ways of applying aggregate functions to multiple columns.
GroupedData
class provides a number of methods for the most common functions, including count
, max
, min
, mean
and sum
, which can be used directly as follows:
Python:
df = sqlContext.createDataFrame(
[(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
("col1", "col2", "col3"))
df.groupBy("col1").sum()
## +----+---------+-----------------+---------+
## |col1|sum(col1)| sum(col2)|sum(col3)|
## +----+---------+-----------------+---------+
## | 1.0| 2.0| 0.8| 1.0|
## |-1.0| -2.0|6.199999999999999| 0.7|
## +----+---------+-----------------+---------+
Scala
val df = sc.parallelize(Seq(
(1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
(-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
).toDF("col1", "col2", "col3")
df.groupBy($"col1").min().show
// +----+---------+---------+---------+
// |col1|min(col1)|min(col2)|min(col3)|
// +----+---------+---------+---------+
// | 1.0| 1.0| 0.3| 0.0|
// |-1.0| -1.0| 0.6| 0.2|
// +----+---------+---------+---------+
Optionally you can pass a list of columns which should be aggregated
df.groupBy("col1").sum("col2", "col3")
You can also pass dictionary / map with columns a the keys and functions as the values:
Python
exprs = {x: "sum" for x in df.columns}
df.groupBy("col1").agg(exprs).show()
## +----+---------+
## |col1|avg(col3)|
## +----+---------+
## | 1.0| 0.5|
## |-1.0| 0.35|
## +----+---------+
Scala
val exprs = df.columns.map((_ -> "mean")).toMap
df.groupBy($"col1").agg(exprs).show()
// +----+---------+------------------+---------+
// |col1|avg(col1)| avg(col2)|avg(col3)|
// +----+---------+------------------+---------+
// | 1.0| 1.0| 0.4| 0.5|
// |-1.0| -1.0|3.0999999999999996| 0.35|
// +----+---------+------------------+---------+
Finally you can use varargs:
Python
from pyspark.sql.functions import min
exprs = [min(x) for x in df.columns]
df.groupBy("col1").agg(*exprs).show()
Scala
import org.apache.spark.sql.functions.sum
val exprs = df.columns.map(sum(_))
df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
There are some other way to achieve a similar effect but these should more than enough most of the time.
See also:
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.
You have to:
topic.php?id=14&like=like
For selecting within single quotes use vi'
.
For selecting within parenthesis use vi(
.
If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
you can also use Boost.
boost::filesystem::exists( filename );
it works for files and folders.
And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).
You can use async/await
for this. I would explain more, but there's nothing really to it. It's just a regular for
loop but I added the await
keyword before the construction of your Promise
What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.
// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld
So here's what that will look like ...
const someProcedure = async n =>_x000D_
{_x000D_
for (let i = 0; i < n; i++) {_x000D_
const t = Math.random() * 1000_x000D_
const x = await new Promise(r => setTimeout(r, t, i))_x000D_
console.log (i, x)_x000D_
}_x000D_
return 'done'_x000D_
}_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
See how we don't have to deal with that bothersome .then
call within our procedure? And async
keyword will automatically ensure that a Promise
is returned, so we can chain a .then
call on the returned value. This sets us up for great success: run the sequence of n
Promises, then do something important – like display a success/error message.
The European Central Bank (ECB) also has the most reliable free feed that I know of. It contains approx 28 currencies and is updated at least daily.
http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
For more formats and tools see the ECB reference page: http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
This worked for me, using MySQL:
ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
Create application.properties
file under src/main/resources
folder and write content as
server.port=8084
Its runs fine. But every time before run need to stop application first by click on red button upper on the IDE
or try
RightClick on console>click terminate/Disconnect All
This is how I solved it
if recursive:
items = os.walk(target_directory)
else:
items = [next(os.walk(target_directory))]
...
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
I have a file "cost.ini" on the root of my class path. My JAR file is named "cost.jar".
The following code:
try {
//JDK11: replace "UTF-8" with UTF_8 and remove try-catch
String rootPath = decode(getSystemResource("cost.ini").getPath()
.replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}
Path returned from .getPath()
has the format:
file:/C:/folder1/folder2/cost.jar!/cost.ini
/C:/folder1/folder2/cost.ini
Every use of File
, leads on exception, if the application provided in JAR format.
I just thought that I'd add that there is a notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]
which affects the positions of a component in its parents component array, which determines the painting order.
Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabled to return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)
The override
keyword serves two purposes:
To explain the latter:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... } // OK
}
class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};
In derived2
the compiler will issue an error for "changing the type". Without override
, at most the compiler would give a warning for "you are hiding virtual method by same name".
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
I have a sample from your code. Try this:
echo "*Select Option:*"
echo "1 - script1"
echo "2 - script2"
echo "3 - script3 "
read option
echo "You have selected" $option"."
if [ $option="1" ]
then
echo "1"
elif [ $option="2" ]
then
echo "2"
exit 0
elif [ $option="3" ]
then
echo "3"
exit 0
else
echo "Please try again from given options only."
fi
This should work. :)
In Javascript method names are camel case, so it's replace
, not Replace
:
$scope.newString = oldString.replace("stackover","NO");
Note that contrary to how the .NET Replace
method works, the Javascript replace
method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:
$scope.newString = oldString.replace(/stackover/g,"NO");
See this example.
You don't need Jquery here! The simplest solution here is (based on the answer from charles):
<html>
<body onload="document.frm1.submit()">
<form action="http://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
</html>
Unless you need a custom date and time format, it's easier, less error-prone, and more readable to use one of the built-in date time format constants:
echo date(DATE_RFC822, 1368496604);
You can do it with using a FileOutputStream
and the writeTo
method.
ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}
Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions
For those who couldnt get one of these solutions working: Send inline image in email Following the steps laid out in the solution offered by @T30 i was able to get my inline image to display without being blocked by outlook (previous methods it was blocked). If you are using exchange like we are then also when doing:
service = new ExchangeService(ExchangeVersion);
service.AutodiscoverUrl("[email protected]");
SmtpClient smtp = new SmtpClient(service.Url.Host);
you will need to pass it your exchange service url host. Other than that following this solution should allow you to easily send embedded imgages.
This is @Ben's answer updated for use with Ember...note you have to use Ember.get
because context is passed in as a String.
Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
var newContext = Ember.get(this, context);
for(var prop in newContext)
{
if (newContext.hasOwnProperty(prop)) {
ret = ret + options.fn({property:prop,value:newContext[prop]});
}
}
return ret;
});
Template:
{{#eachProperty object}}
{{key}}: {{value}}<br/>
{{/eachProperty }}