Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
A bit late but I got something similar that I'm busy building and here is the code to get current location - be sure to use local server to test.
Include relevant scripts from CDN:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">
<div id="map"></div>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
There are some great solutions here, but I'll like to take it one step further regarding the local file.
In a scenario when Google does fail, it should load a local source but maybe a physical file on the server isn't necessarily the best option. I bring this up because I'm currently implementing the same solution, only I want to fall back to a local file that gets generated by a data source.
My reasons for this is that I want to have some piece of mind when it comes to keeping track of what I load from Google vs. what I have on the local server. If I want to change versions, I'll want to keep my local copy synced with what I'm trying to load from Google. In an environment where there are many developers, I think the best approach would be to automate this process so that all one would have to do is change a version number in a configuration file.
Here's my proposed solution that should work in theory:
In theory, if my code is written properly, all I would need to do is change the version number in my app config then viola! You have a fallback solution which is automated, and you don't have to maintain physical files on your server.
What does everyone think? Maybe this is overkill, but it could be an elegant method of maintaining your AJAX libraries.
Acorn
I will add this as a reason to locally host these files.
Recently a node in Southern California on TWC has not been able to resolve the ajax.googleapis.com domain (for users with IPv4) only so we are not getting the external files. This has been intermittant up until yesterday (now it is persistant.) Because it was intermittant, I was having tons of problems troubleshooting SaaS user issues. Spent countless hours trying to track why some users were having no issues with the software, and others were tanking. In my usual debugging process I'm not in the habit of asking a user if they have IPv6 turned off.
I stumbled on the issue because I myself was using this particular "route" to the file and also am using only IPV4. I discovered the issue with developers tools telling me jquery wasn't loading, then started doing traceroutes etc... to find the real issue.
After this, I will most likely never go back to externally hosted files because: google doesn't have to go down for this to become a problem, and... any one of these nodes can be compromised with DNS hijacking and deliver malicious js instead of the actual file. Always thought I was safe in that a google domain would never go down, now I know any node in between a user and the host can be a fail point.
For example this plugIns:
Just search for under cursor in vimawesome.com
The key, as clagccs mentioned, is that the highlight does NOT conflict with your search: https://vim.fandom.com/wiki/Auto_highlight_current_word_when_idle
Screen-shot of how it does NOT conflict with search: Notes:
Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.
A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, ren.myserver.com
and stimpy.myserver.com
.
Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml
is here:
http://tomcat.apache.org/tomcat-7.0-doc/virtual-hosting-howto.html.
The full explanation of the Host
parameters you can find here:
http://tomcat.apache.org/tomcat-7.0-doc/config/host.html.
Adding a virtual host
Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.
At a minimum you need the Name
and App Base
fields defined. Tomcat will then create the following directories:
{CATALINA_HOME}\conf\Catalina\{Name}
{CATALINA_HOME}\{App Base}
App Base
will be where web applications will be deployed to the virtual host. Can be relative or absolute.Name
is usually the fully-qualified domain name (e.g. ren.myserver.com
)Alias
can be used to extend the Name
also where two addresses should resolve to the same host (e.g. www.ren.myserver.com
). Note that this needs to be reflected in DNS records.The checkboxes are as follows:
Auto Deploy
: Automatically redeploy applications placed into App Base. Dangerous for Production environments!Deploy On Startup
: Automatically boot up applications under App Base when Tomcat startsDeploy XML
: Determines whether to parse the application's /META-INF/context.xml
Unpack WARs
: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.Copy XML
: Copy an application's META-INF/context.xml
to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML
is false.Manager App
: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath ren.myserver.com
)Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml
, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml
anyway, as per the first link above, to make it stick.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
Your question is confusing and you really should post some code, but this should work:
onClick="this.disabled=true; this.value='Sending...'; submitForm(); return false;"
I think that when you use this.form.submit()
it's doing what happens naturally when you click the submit button. If you want same-page submit, you should look into using AJAX in the submitForm()
method (above).
Also, returning false
at the end of the onClick
attribute value suppresses the default event from firing (in this case submitting the form).
Angular 2 , 4 and 5 :
the simplest way : plunker
<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">
To find which field has invalid characters:
SELECT * FROM Staging.APARMRE1 FOR XML AUTO, TYPE
You can test it with this query:
SELECT top 1 'char 31: '+char(31)+' (hex 0x1F)' field
from sysobjects
FOR XML AUTO, TYPE
The result will be:
Msg 6841, Level 16, State 1, Line 3 FOR XML could not serialize the data for node 'field' because it contains a character (0x001F) which is not allowed in XML. To retrieve this data using FOR XML, convert it to binary, varbinary or image data type and use the BINARY BASE64 directive.
It is very useful when you write xml files and get error of invalid characters when validate it.
My mistake, the resource files WERE actually copied to target/test-classes
. The problem seemed to be due to spaces in my project name, e.g. Project%20Name
.
I'm now loading the file as follows and it works:
org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);
Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):
myClass().getResource("resourceFile.txt")??.toURI();
removing first characters:
x <- 'hello stackoverflow'
substring(x, 2, nchar(x))
Idea is select all characters starting from 2 to number of characters in x. This is important when you have unequal number of characters in word or phrase.
Selecting the first letter is trivial as previous answers:
substring(x,1,1)
/* Most Accurate Setting if you only want
to do this with CSS Pseudo Element */
p:before {
content: "\00a0";
padding-right: 5px; /* If you need more space b/w contents */
}
ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--'
as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.
You could make a recursive function do the work
L = size(M)
idx = zeros(L,1)
length(L)
as the maximum depthfor idx(depth) = 1:L(depth)
length(L)
, do the element operation, else call the function again with depth+1
Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.
I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A
) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h"
in the .m file of class B fixed the problem for me.
From the data you gathered, I would tend to say that encoded "/" in an uri are meant to be seen as "/" again at application/cgi level.
That's to say, that if you're using apache with mod_rewrite
for instance, it will not match pattern expecting slashes against URI with encoded slashes in it.
However, once the appropriate module/cgi/... is called to handle the request, it's up to it to do the decoding and, for instance, retrieve a parameter including slashes as the first component of the URI.
If your application is then using this data to retrieve a file (whose filename contains a slash), that's probably a bad thing.
To sum up, I find it perfectly normal to see a difference of behaviour in "/" or "%2F" as their interpretation will be done at different levels.
global $wpdb;
$insert = $wpdb->query("INSERT INTO `front-post`(`id`, `content`) VALUES ('$id', '$content')");
The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.
However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:
document.getElementById('loginSubmit').click();
Or you could do it the evil way.
var a = [1,2,3,4,5,6,7,8,9];
sum = eval(a.join("+"));
;)
use coalesce
COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.
Edit
Here's an example of COALESCE
with your query:
SELECT AVG( price )
FROM(
SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
WHERE listing_Type = 'AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) g
WHERE cume_dist < 0.50
)
AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) d
WHERE cume_dist < 0.50)
)s
HAVING COUNT(*) > 5
IMHO COALESCE
should not be use with AVG
because it modifies the value. NULL
means unknown and nothing else. It's not like using it in SUM
. In this example, if we replace AVG
by SUM
, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.
In that case, I would add price IS NOT NULL
in WHERE
clause to avoid these unknown values.
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
I would unpack your gem in the application vendor folder
gem unpack your.gem --target /path_to_app/vendor/gems/
Then add the path on the Gemfile to link unpacked gem.
gem 'your', '2.0.1', :path => 'vendor/gems/your'
cat /sys/class/net/ethX
is by far the easiest method.
The interface has to be up though, else you will get an invalid argument error.
So first:
ifconfig ethX up
Then:
cat /sys/class/net/ethX
This script logs all the file names and ids in the drive:
// Log the name and id of every file in the user's Drive
function listFiles() {
var files = DriveApp.getFiles();
while ( files.hasNext() ) {
var file = files.next();
Logger.log( file.getName() + ' ' + file.getId() );
}
}
Also, the "Files: list" page has a form at the end that lists the metadata of all the files in the drive, that can be used in case you need but a few ids.
The question, essentially, is "how to concatenate arrays in Ruby". Naturally the answer is to use concat
or +
as mentioned in nearly every answer.
A natural extension to the question would be "how to perform row-wise concatenation of 2D arrays in Ruby". When I googled "ruby concatenate matrices", this SO question was the top result so I thought I would leave my answer to that (unasked but related) question here for posterity.
In some applications you might want to "concatenate" two 2D arrays row-wise. Something like,
[[a, b], | [[x], [[a, b, x],
[c, d]] | [y]] => [c, d, y]]
This is something like "augmenting" a matrix. For example, I used this technique to create a single adjacency matrix to represent a graph out of a bunch of smaller matrices. Without this technique I would have had to iterate over the components in a way that could have been error prone or frustrating to think about. I might have had to do an each_with_index
, for example. Instead I combined zip and flatten as follows,
# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]
m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]
var hostname = window.location.origin
Will not work for IE. For IE support as well I would something like this:
var hostName = window.location.hostname;
var protocol = window.locatrion.protocol;
var finalUrl = protocol + '//' + hostname;
I ran into the same error, and in my case it was a simple matter of going to Project Properties > Maven > Update project
and/or cleaning and rebuilding the project.
The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).
Typical symptoms:
[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100
[root@host /]# netstat -plant | grep 25
tcp 0 0 :::25 :::* LISTEN 1082/exim
If this happens, make sure that you don't have two entries for localhost
in /etc/hosts
with different IP addresses, like this (bad) example:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
To avoid confusion, make sure you only have one entry for localhost
, preferably an IPv4 address, like this:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4.localdomain4 localhost4
::1 localhost6 localhost6.localdomain6
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
This is really tricky. There seems to be no solution given the following requirements.
This happens because:
Given these restrictions, it is possible to implement a solution that combines - The page Visibility API - window blur/focus - document.activeElement
That is able to:
When the iframe has focus, your blur/focus events don't get invoked at all, and the page Visibility API won't trigger on alt+tab.
I built upon @AndyE's solution and implemented this (almost good) solution here: https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test1.html (sorry, I had some trouble with JSFiddle).
This is also available on Github: https://github.com/qmagico/estante-components
This works on chrome/chromium. It kind works on firefox, except that it doesn't load the iframe contents (any idea why?)
Anyway, to resolve the last problem (4), the only way you can do that is to listen for blur/focus events on the iframe. If you have some control over the iframes, you can use the postMessage API to do that.
https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test2.html
I still haven't tested this with enough browsers. If you can find more info about where this doesn't work, please let me know in the comments below.
The following example demonstrates how to do this:
DateTime a = new DateTime(2010, 05, 12, 13, 15, 00);
DateTime b = new DateTime(2010, 05, 12, 13, 45, 00);
Console.WriteLine(b.Subtract(a).TotalMinutes);
When executed this prints "30" since there is a 30 minute difference between the date/times.
The result of DateTime.Subtract(DateTime x)
is a TimeSpan Object which gives other useful properties.
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
Use UNION
:
SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks
Or UNION ALL
if you want duplicates:
SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks
Initiate the element with as such:
<div id='foo' style="display: none"></div>
And then, use the event you want to show it, as such:
$('#foo').show();
The simplest way to go I believe.
If you are using string
datatype, below code works:
string str = str.Remove(str.Length - 1);
But when you have StringBuilder
, you have to specify second parameter length
as well.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:
Probably the best high level description I have found for tail calls, recursive tail calls and tail call optimization is the blog post
"What the heck is: A tail call"
by Dan Sugalski. On tail call optimization he writes:
Consider, for a moment, this simple function:
sub foo (int a) { a += 15; return bar(a); }
So, what can you, or rather your language compiler, do? Well, what it can do is turn code of the form
return somefunc();
into the low-level sequencepop stack frame; goto somefunc();
. In our example, that means before we callbar
,foo
cleans itself up and then, rather than callingbar
as a subroutine, we do a low-levelgoto
operation to the start ofbar
.Foo
's already cleaned itself out of the stack, so whenbar
starts it looks like whoever calledfoo
has really calledbar
, and whenbar
returns its value, it returns it directly to whoever calledfoo
, rather than returning it tofoo
which would then return it to its caller.
And on tail recursion:
Tail recursion happens if a function, as its last operation, returns the result of calling itself. Tail recursion is easier to deal with because rather than having to jump to the beginning of some random function somewhere, you just do a goto back to the beginning of yourself, which is a darned simple thing to do.
So that this:
sub foo (int a, int b) { if (b == 1) { return a; } else { return foo(a*a + a, b - 1); }
gets quietly turned into:
sub foo (int a, int b) { label: if (b == 1) { return a; } else { a = a*a + a; b = b - 1; goto label; }
What I like about this description is how succinct and easy it is to grasp for those coming from an imperative language background (C, C++, Java)
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
In my case, this problem will happen when the wpf program's architechture is not exactly same with dependency. Suppose you have one dependency that is x64, and another one is AnyCPU. Then if you choose x64, the type in AnyCPU dll will "does not exist", otherwise the type in x64 dll will "does not exist". You just cannot emilate both of them.
I was using ubuntu 18 and simply installed MySQL (password:root) with the following commands.
sudo apt install mysql-server
sudo mysql_secure_installation
When I tried to log in with the normal ubuntu user it was throwing me this issue.
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
But I was able to login to MySQL via the super user. Using the following commands I was able to log in via a normal user.
sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
exit;
Then you should be able to login to Mysql with the normal account.
you can loop through the data frame like this .
for ad in range(1,dataframe_c.size):
print(dataframe_c.values[ad])
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do
select field from table where field REGEXP '^-?[0-9]+$';
this is reasonably fast. If your field is numeric, just test for
ceil(field) = field
instead.
Please check your app's build.gradle. I had the same problem, finally I found the problem was in my build.gradle file dependencies{}, it add extra .jar file which actually didn't exist in my project as dependency. So I delete this dependency, and the problem has gone.
If your column data type is 'text' then you will get an error message as
Msg 8116, Level 16, State 1, Line 2 Argument data type text is invalid for argument 1 of replace function.
In this case you need to cast the text as nvarchar and then replace
SELECT REPLACE(REPLACE(cast(@str as nvarchar(max)), CHAR(13), ''), CHAR(10), '')
Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.
https://maps.google.com/?parameter=value
q=
Used to specify the search query in Google maps search.
eg :
https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679
near=
Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.
z=
Zoom level. Can be set 19 normally, but in certain cases can go up to 23.
ll=
Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.
sll=
Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.
t=
Sets the kind of map shown. Can be set to:
m – normal map
k – satellite
h – hybrid
p – terrain
saddr=
Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.
daddr=
Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.
via=
Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.
doflg=
Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.
msa=
Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.
reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
The better option would be to just use the resource returned array as an array, meaning :
getResources().getStringArray(R.array.your_array)[position]
This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.
This warning is also reported if you have some code like:
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = myAwesomeRootViewController
window?.makeKeyAndVisible()
In this case, go to the first page of target settings and set Main Interface
to empty, since you don't need a storyboard entry for your app.
If the string has both spaces and commas you can use the string class function
found_index = myString.find_first_of(delims_str, begin_index)
in a loop. Checking for != npos and inserting into a vector. If you prefer old school you can also use C's
strtok()
method.
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
Try like this...
<script>
function getPaging(str) {
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
or unobtrusively
$(function() {
$("li").on("click",function() {
showLoader();
$("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
});
});
using just
<li id="1">1</li>
<li id="2">2</li>
Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.
$('.someSelector').bind('touchend click', function() {
var url = $('a', this).prop('href');
var target = $('a', this).prop('target');
if(url) {
// # open in new window if "_blank" used
if(target == '_blank') {
window.open(url, target);
} else {
window.location = url;
}
}
});
For me, any of the methods mentioned above using Homebrew did not work on macOS. So, I uninstalled node using Homebrew and downloaded the node package from https://nodejs.org/en/download/ and installed it. It worked like a charm.
I was not content with any of the answers on this page, so I fiddled with this myself for a bit. I came up with the following
angular.module('showcase', []).controller('Ctrl', function() {_x000D_
var vm = this;_x000D_
vm.focusParent = function(event) {_x000D_
angular.element(event.target).parent().addClass('focus');_x000D_
};_x000D_
_x000D_
vm.blurParent = function(event) {_x000D_
angular.element(event.target).parent().removeClass('focus');_x000D_
};_x000D_
});
_x000D_
.input-merge .col-xs-2,_x000D_
.input-merge .col-xs-4,_x000D_
.input-merge .col-xs-6 {_x000D_
padding-left: 0;_x000D_
padding-right: 0;_x000D_
}_x000D_
.input-merge div:first-child .form-control {_x000D_
border-top-right-radius: 0;_x000D_
border-bottom-right-radius: 0;_x000D_
}_x000D_
.input-merge div:last-child .form-control {_x000D_
border-top-left-radius: 0;_x000D_
border-bottom-left-radius: 0;_x000D_
}_x000D_
.input-merge div:not(:first-child) {_x000D_
margin-left: -1px;_x000D_
}_x000D_
.input-merge div:not(:first-child):not(:last-child) .form-control {_x000D_
border-radius: 0;_x000D_
}_x000D_
.focus {_x000D_
z-index: 2;_x000D_
}
_x000D_
<html ng-app="showcase">_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body class="container">_x000D_
<label class="control-label">Person</label>_x000D_
<div class="input-merge" ng-controller="Ctrl as showCase">_x000D_
<div class="col-xs-4">_x000D_
<input class="form-control input-sm" name="initials" type="text" id="initials"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="person.initials" placeholder="Initials" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-2">_x000D_
<input class="form-control input-sm" name="prefixes" type="text" id="prefixes"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.prefixes" placeholder="Prefixes" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-6">_x000D_
<input class="form-control input-sm" name="surname" type="text" id="surname"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.surname" placeholder="Surname" />_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
With this it is possible to set the width of the individual inputs to your liking. Also a minor issue with the above snippets was that the input looks incomplete when focussed or when it is not valid. I fixed this with some angular code, but you can just as easily do this with jQuery or native javascript or whatever.
The code adds the class .focus to the containing div's, so it can get a higher z-index then the others when the input is focussed.
Custom Format for using . is not recognised by Excel, hence that could be the reason it could not sort.
Steps to mitigate; change the format to dd/mm/yyyy, sort as required , change the format to dd.mm.yyyy
A quick search using...
apt search Xlib.h
Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?
You can add Xlib.h to your system by running the following...
sudo apt install libx11-dev
Just place a div around the input and label...
<li>
<div>
<input id="checkid" type="checkbox" value="test" />
</div>
<div>
<label style="word-wrap:break-word">testdata</label>
</div>
</li>
simple write in your bat file
@cmd
or
@cmd /k "command1&command2"
KISS answer:
URLSession.shared.dataTask(with: URL(string: "https://google.com")!) {(data, response, error) in
print(String(data: data!, encoding: .utf8))
}.resume()
shell_exec
returns all of the output stream as a string. exec
returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.
See
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
Yes, simply set it to another value:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text
key of the array. The $_POST
is superglobal associative array and you can change the values like a normal PHP array.
Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST
array is cleared. A new form submission will generate a new $_POST
array.
If you want to persist the value across form submissions, you will need to put it in the form as an input
tag's value
attribute or retrieve it from a data store.
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Best thing is to try it for yourself.
mkdir test
cd test
git init
touch aaa.txt
git add .
git commit -a -m "New file"
mv aaa.txt bbb.txt
git add .
git status
git commit --dry-run -a
Now git status and git commit --dry-run -a shows two different results where git status shows bbb.txt as a new file/ aaa.txt is deleted, and the --dry-run commands shows the actual rename.
~/test$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: bbb.txt
#
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: aaa.txt
#
/test$ git commit --dry-run -a
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: aaa.txt -> bbb.txt
#
Now go ahead and do the check-in.
git commit -a -m "Rename"
Now you can see that the file is in fact renamed, and what's shown in git status is wrong.
Moral of the story: If you're not sure whether your file got renamed, issue a "git commit --dry-run -a". If its showing that the file is renamed, you're good to go.
public static int[] range(int[] array, int start, int end){
int returner[] = new int[end-start];
for(int x = 0; x <= end-start-1; x++){
returner[x] = array[x+start];
}
return returner;
}
this is a way to do the same thing as Array.copyOfRange but without importing anything
First all answers are right, you can pass the data except custom objects by using Intent
. If you want to pass the custom objects, you have to implement Serialazable
or Parcelable
to your custom object class. I thought it's too much complicated...
So if your project is simple, try to use DataCache
. That provides super simple way for passing data.
Ref: Github project CachePot
1- Set this to View or Activity or Fragment which will send data
DataCache.getInstance().push(obj);
2- Get data anywhere like below
public class MainFragment extends Fragment
{
private YourObject obj;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
obj = DataCache.getInstance().pop(YourObject.class);
}//end onCreate()
}//end class MainFragment
Drop the spaces around the =
sign:
#!/bin/bash
STR="Hello World"
echo $STR
You should explore SQL Server\Memory Manager performance counters.
C++11: Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
You can combine two (or more) constructors via default parameters:
class Foo {
public:
Foo(char x, int y=0); // combines two constructors (char) and (char, int)
// ...
};
Use an init method to share common code:
class Foo {
public:
Foo(char x);
Foo(char x, int y);
// ...
private:
void init(char x, int y);
};
Foo::Foo(char x)
{
init(x, int(x) + 7);
// ...
}
Foo::Foo(char x, int y)
{
init(x, y);
// ...
}
void Foo::init(char x, int y)
{
// ...
}
See the C++FAQ entry for reference.
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
if you are using login page in your website go to web.config file
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="index.aspx" >
</forms>
</authentication>
replace your authentication tag to above (where index.aspx will be your startup page)
and one more thing write this in your web.config file inside
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
</files>
</defaultDocument>
</system.webServer>
<location path="index.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:
jQuery Ajax POST example with PHP (Note the sanitize posted data remark) and
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Basically, the difference is that the GET request has the url and parameters in one string and then sends null:
http.open("GET", url+"?"+params, true);
http.send(null);
whereas the POST request sends the url and the parameters in separate commands:
http.open("POST", url, true);
http.send(params);
Here is a working example:
ajaxPOST.html:
<html>
<head>
<script type="text/javascript">
function ajaxPOSTTest() {
try {
// Opera 8.0+, Firefox, Safari
ajaxPOSTTestRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
var url = "ajaxPOST.php";
var params = "lorem=ipsum&name=binny";
ajaxPOSTTestRequest.open("POST", url, true);
ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxPOSTTestRequest.send(params);
}
//Create a function that will receive data sent from the server
function ajaxCalled_POSTTest() {
if (ajaxPOSTTestRequest.readyState == 4) {
document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;
}
}
</script>
</head>
<body>
<button onclick="ajaxPOSTTest()">ajax POST Test</button>
<div id="output"></div>
</body>
</html>
ajaxPOST.php:
<?php
$lorem=$_POST['lorem'];
print $lorem.'<br>';
?>
I just sent over 12,000 characters without any problems.
myString.replace(/<br ?\/?>/g, "\n")
Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:
// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
.setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();
If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:
Process.Start("chrome.exe", "http://www.YourUrl.com");
This seem to work as expected for me, opening a new tab if Chrome is already open.
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
Use this snippet
import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)
All other answers are very helpful. I just went through the same problem and figure out an easy way with docker machine scp
.
Since Docker Machine v0.3.0, scp was introduced to copy files from one Docker machine to another. This is very convenient if you want copying a file from your local computer to a remote Docker machine such as AWS EC2 or Digital Ocean because Docker Machine is taking care of SSH credentials for you.
Save you images using docker save
like:
docker save -o docker-images.tar app-web
Copy images using docker-machine scp
docker-machine scp ./docker-images.tar remote-machine:/home/ubuntu
Assume your remote Docker machine is remote-machine
and the directory you want the tar file to be is /home/ubuntu
.
Load the Docker image
docker-machine ssh remote-machine sudo docker load -i docker-images.tar
And if anyone is wondering how to do this in swift
:
if let myDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
myDelegate.someMethod()
}
alternative way:
mail -N
d *
quit
-N
Inhibits the initial display of message headers when reading mail or editing a mail folder.
d *
delete all mails
this is trivially easy, why are so many people making such bad suggestions? @Bora was the closest, but this is the most robust
/***
* returns the month in words for a given month number
*/
date("F", strtotime(date("Y")."-".$month."-01"));
this is the way to do it
std::is_same()
is only available since C++11. For pre-C++11 you can use typeid()
:
template <typename T>
void foo()
{
if (typeid(T) == typeid(animal)) { /* ... */ }
}
Use a static Random or the numbers tend to repeat in tight/fast loops due to the system clock seeding them.
public static class RandomNumbers
{
private static Random random = new Random();
//=-------------------------------------------------------------------
// double between min and the max number
public static double RandomDouble(int min, int max)
{
return (random.NextDouble() * (max - min)) + min;
}
//=----------------------------------
// double between 0 and the max number
public static double RandomDouble(int max)
{
return (random.NextDouble() * max);
}
//=-------------------------------------------------------------------
// int between the min and the max number
public static int RandomInt(int min, int max)
{
return random.Next(min, max + 1);
}
//=----------------------------------
// int between 0 and the max number
public static int RandomInt(int max)
{
return random.Next(max + 1);
}
//=-------------------------------------------------------------------
}
See also : https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8
There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class DisplayImage {
public static void main(String avg[]) throws IOException
{
DisplayImage abc=new DisplayImage();
}
public DisplayImage() throws IOException
{
BufferedImage img=ImageIO.read(new File("f://images.jpg"));
ImageIcon icon=new ImageIcon(img);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(200,300);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:
>>> import shutil
>>> import sys
>>> with open("test.txt", "rb") as f:
... shutil.copyfileobj(f, sys.stdout.buffer)
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Before HTML5 we can use:
parent.location.hash = "hello";
and:
window.location.replace("http:www.example.com");
This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url)
that should not reload your page.
You can try something like this
stages {
stage('Build') {
environment {
AOEU= sh (returnStdout: true, script: 'echo aoeu').trim()
}
steps {
sh 'env'
sh 'echo $AOEU'
}
}
}
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.webpack entry.jsx ./output.js -p
works for me, with -p
flag.
This answer is a workaround for those who use "Theme.AppCompat.Dialog" or any other "Theme.AppCompat.Dialog" descendants like "Theme.AppCompat.Light.Dialog", "Theme.AppCompat.DayNight.Dialog", etc. I myself has to use AppCompat dialog because i use AppCompatActivity as extends for all my activities. There will be a problem that make the dialog has padding on every sides(top, right, bottom and left) if we use the accepted answer.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
On your Activity's style, add these code
<style name="DialogActivityTheme" parent="Theme.AppCompat.Dialog">
<item name="windowNoTitle">true</item>
<item name="android:windowBackground">@null</item>
</style>
As you may notice, the problem that generate padding to our dialog is "android:windowBackground", so here i make the window background to null.
This method seems to do what you want:
$('#email-field-only').valid();
It sounds like you might need to create and query linked database servers in SQL Server
At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable
but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable
, see this post on four part naming for more info
edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net
.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]
If you can't access the remote server then see if you can create a linked database server:
EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[database.windows.net].basecampdev.dbo.invoice;
GO
Then you can just query against MyEmployee
without needing the full four part name
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
Two options:
Do the division after the multiplication:
int n = 25;
int v = 100;
int percent = n * 100 / v;
Convert an int
to a float
before dividing
int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
// float percent = (float) n * 100 / v;
// float percent = n * 100 / (float) v;
Have you tried moving the reduction step outside the loop? Right now you have a data dependency that really isn't needed.
Try:
uint64_t subset_counts[4] = {};
for( unsigned k = 0; k < 10000; k++){
// Tight unrolled loop with unsigned
unsigned i=0;
while (i < size/8) {
subset_counts[0] += _mm_popcnt_u64(buffer[i]);
subset_counts[1] += _mm_popcnt_u64(buffer[i+1]);
subset_counts[2] += _mm_popcnt_u64(buffer[i+2]);
subset_counts[3] += _mm_popcnt_u64(buffer[i+3]);
i += 4;
}
}
count = subset_counts[0] + subset_counts[1] + subset_counts[2] + subset_counts[3];
You also have some weird aliasing going on, that I'm not sure is conformant to the strict aliasing rules.
If yes_ans > no_ans and yes_ans > na_ans
You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.
Abstraction - is the process (and result of this process) of identifying the common essential characteristics for a set of objects. One might say that Abstraction is the process of generalization: all objects under consideration are included in a superset of objects, all of which possess given properties (but are different in other respects).
Encapsulation - is the process of enclosing data and functions manipulating this data into a single unit, so that to hide the internal implementation from the outside world.
This is a general answer not related to a specific programming language (as was the question). So the answer is: abstraction and encapsulation have nothing in common. But their implementations might relate to each other (say, in Java: Encapsulation - details are hidden in a class, Abstraction - details are not present at all in a class or interface).
What's abaut this one:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.
VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.
Follow below steps..
ILDASM.EXE
press ENTER. ILDASM
window will open.Drag the .dll
file to window from your folder.Or click on File->New
.Then Add required .dll
file. .dll
file will appear. Double click on these files to see what it contains. I had to run my commands in the one and same terminal, not seperately.
nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"
I have been making a Chrome app called Postman for this type of stuff. All the other extensions seemed a bit dated so made my own. It also has a bunch of other features which have been helpful for documenting our own API here.
Postman now also has native apps (i.e. standalone) for Windows, Mac and Linux! It is more preferable now to use native apps, read more here.
I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.
The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).
New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/
(eg /opt/firefox31/
). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.
A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.
It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)
select
sone_field collate DATABASE_DEFAULT
from
table_1
inner join
table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever
It worked only after removing the eclipse folder and all related folders like .p2, .eclipse (in my case they are at different location where I have saved eclipse installer) etc. and after re-downloading the eclipse, it worked.
List is an interface. You need a specific class in the end so either try
List l = new ArrayList();
or
List l = new LinkedList();
Whichever suit your needs.
In my system (Ubuntu 12.04) I found RESET QUERY CACHE
and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
and then reset the query cache in mysql client:
RESET QUERY CACHE;
We implemented a solution, partly based off a comment from a user above, which works perfectly for us. We use it to hide a search box / results when clicking outside those elements, excluding the element that originally.
// HIDE SEARCH BOX IF CLICKING OUTSIDE
$(document).click(function(event){
// IF NOT CLICKING THE SEARCH BOX OR ITS CONTENTS OR SEARCH ICON
if ($("#search-holder").is(":visible") && !$(event.target).is("#search-holder *, #search")) {
$("#search-holder").fadeOut('fast');
$("#search").removeClass('active');
}
});
It checks if the search box is already visible first also, and in our case, it's also removing an active class on the hide/show search button.
if "my_data" in my_json_data:
print json.dumps(my_json_data["my_data"])
According to http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html the format "yyyy/mm/dd" solves the usual problems. He says: "Stick to "YYYY/MM/DD" for your date strings whenever possible. It's universally supported and unambiguous. With this format, all times are local." I've set tests: http://jsfiddle.net/jlanus/ND2Qg/432/ This format: + avoids the day and month order ambiguity by using y m d ordering and a 4-digit year + avoids the UTC vs. local issue not complying with ISO format by using slashes + danvk, the dygraphs guy, says that this format is good in all browsers.
The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null
, as that may cause unexpected behaviour.
var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
Or if you prefer, you can make it a function:
function clearOptions(id)
{
var select = document.getElementById(id);
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
}
clearOptions("myselect");
That error means your node's publish is low than the need. carefully to update the node of your computer.
Use this icons with bootstrap (glyphicon):
<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
I also had this issue with my Android app depending on some of my own Android libraries (using Android Studio 3.0 and 3.1.1).
Whenever I updated a lib and go back to the app, triggering a Gradle Sync, Android Studio was not able to detect the code changes I made to the lib. Compilation worked fine, but Android Studio showed red error lines on some code using the lib.
After investigating, I found that it's because gradle keeps pointing to an old compiled version of my libs. If you go to yourProject/.idea/libraries/ you'll see a list of xml files that contains the link to the compiled version of your libs. These files starts with Gradle__artifacts_*.xml (where * is the name of your libs).
So in order for Android Studio to take the latest version of your libs, you need to delete these Gradle__artifacts_*.xml files, and Android Studio will regenerate them, pointing to the latest compiled version of your libs.
If you don't want to do that manually every time you click on "Gradle sync" (who would want to do that...), you can add this small gradle task in the build.gradle file of your app.
task deleteArtifacts {
doFirst {
File librariesFolderPath = file(getProjectDir().absolutePath + "/../.idea/libraries/")
File[] files = librariesFolderPath.listFiles({ File file -> file.name.startsWith("Gradle__artifacts_") } as FileFilter)
for (int i = 0; i < files.length; i++) {
files[i].delete()
}
}
}
And in order for your app to always execute this task before doing a gradle sync, you just need to go to the Gradle window, then find the "deleteArtifacts" task under yourApp/Tasks/other/, right click on it and select "Execute Before Sync" (see below).
Now, every time you do a Gradle sync, Android Studio will be forced to use the latest version of your libs.
You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.
Or you can just use this:
<?
function TestHtml() {
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->
<? } ?>
to get content from this function , use this :
<?= file_get_contents(TestHtml()); ?>
That's it :)
You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.
You will probably also need the .classpath file in the project directory that contains the test class.
Like the run configurations, they're XML files (even if they don't have an xml extension).
PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.
So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.
I had to do this in that order:
Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD
For put method we have:
const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
Example for someData, we can have some input fields or whatever you need:
const someData = {
title: document.querySelector(TitleInput).value,
body: document.querySelector(BodyInput).value
}
And in our data base
will have this in json
format:
{
"posts": [
"id": 1,
"title": "Some Title", // what we typed in the title input field
"body": "Some Body", // what we typed in the body input field
]
}
For delete method we have:
const deleteMethod = {
method: 'DELETE', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
// No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
In the url we need to type the id of the of deletion: https://www.someapi/id
Similar to several answers like Alex V's and NDavis, but none of them are quite the same.
When already in the branch in question
Using:
git diff master...
Which combines several features:
Update:
This should probably be git diff master
, but also this shows the diff, not the commits as the question specified.
try this method
$("your id or class name").css({ 'margin-top': '18px' });
A curried function is applied to multiple argument lists, instead of just one.
Here is a regular, non-curried function, which adds two Int parameters, x and y:
scala> def plainOldSum(x: Int, y: Int) = x + y
plainOldSum: (x: Int,y: Int)Int
scala> plainOldSum(1, 2)
res4: Int = 3
Here is similar function that’s curried. Instead of one list of two Int parameters, you apply this function to two lists of one Int parameter each:
scala> def curriedSum(x: Int)(y: Int) = x + y
curriedSum: (x: Int)(y: Int)Intscala> second(2)
res6: Int = 3
scala> curriedSum(1)(2)
res5: Int = 3
What’s happening here is that when you invoke curriedSum
, you actually get two traditional function invocations back to back. The first function
invocation takes a single Int parameter named x
, and returns a function
value for the second function. This second function takes the Int parameter
y
.
Here’s a function named first
that does in spirit what the first traditional
function invocation of curriedSum
would do:
scala> def first(x: Int) = (y: Int) => x + y
first: (x: Int)(Int) => Int
Applying 1 to the first function—in other words, invoking the first function and passing in 1 —yields the second function:
scala> val second = first(1)
second: (Int) => Int = <function1>
Applying 2 to the second function yields the result:
scala> second(2)
res6: Int = 3
Here is the most concise solution so far:
function isArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.every(item => typeof item === "string");
}
Note that value.every
will return true
for an empty array. If you need to return false
for an empty array, you should add value.length
to the condition clause:
function isNonEmptyArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.length && value.every(item => typeof item === "string");
}
There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the type of an empty array. For a non-empty array all you can do is to check the type of its items, one by one.
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
The command mmv
seems to do this task very efficiently on a huge number of files (tens of thousands in a second). For example, to rename all .xml
files to .html
files, use this:
mmv ";*.xml" "#1#2.html"
the ;
will match the path, the *
will match the filename, and these are referred to as #1
and #2
in the replacement name.
Answers based on exec
or pipes were either too slow or failed on a very large number of files.
I'm not sure if you can detect whether it's loaded or not, but you can fire an event once it's done loading:
$(function(){
$('#myIframe').ready(function(){
//your code (will be called once iframe is done loading)
});
});
EDIT: As pointed out by Jesse Hallett, this will always fire when the iframe
has loaded, even if it already has. So essentially, if the iframe
has already loaded, the callback will execute immediately.
Run given below command on terminal ( for linux only )
ps aux | grep rails
and then
kill -9 [pid]
Another way
lsof -wni tcp:3000
and then
kill -9 [PID]
I added this to my package.json:
"build": "npm build",
"clean": "rm -rf node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && npm run build",
Seems to work well.
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
Depending on your needs, *ngIf
or [ngClass]="{hide_element: item.hidden}"
where CSS class hide_element
is { display: none; }
*ngIf
can cause issues if you're changing state variables *ngIf
is removing, in those cases using CSS display: none;
is required.
Can use map and lambda
lst = [1,1,1,1,1,1,1,1,1]
print all(map(lambda x: x == lst[0], lst[1:]))
Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter
statement exactly the way you originally had it works perfectly:
ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);
You only need to add parenthesis if you need to alter more than one column at once, such as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));
If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:
head -n 20 york.txt | tail -11
or
sed -n '10,20p' york.txt
p
in above command stands for printing.
For one-level flatten, if you care about speed, this is faster than any of the previous answers under all conditions I tried. (That is, if you need the result as a list. If you only need to iterate through it on the fly then the chain example is probably better.) It works by pre-allocating a list of the final size and copying the parts in by slice (which is a lower-level block copy than any of the iterator methods):
def join(a):
"""Joins a sequence of sequences into a single sequence. (One-level flattening.)
E.g., join([(1,2,3), [4, 5], [6, (7, 8, 9), 10]]) = [1,2,3,4,5,6,(7,8,9),10]
This is very efficient, especially when the subsequences are long.
"""
n = sum([len(b) for b in a])
l = [None]*n
i = 0
for b in a:
j = i+len(b)
l[i:j] = b
i = j
return l
Sorted times list with comments:
[(0.5391559600830078, 'flatten4b'), # join() above.
(0.5400412082672119, 'flatten4c'), # Same, with sum(len(b) for b in a)
(0.5419249534606934, 'flatten4a'), # Similar, using zip()
(0.7351131439208984, 'flatten1b'), # list(itertools.chain.from_iterable(a))
(0.7472689151763916, 'flatten1'), # list(itertools.chain(*a))
(1.5468521118164062, 'flatten3'), # [i for j in a for i in j]
(26.696547985076904, 'flatten2')] # sum(a, [])
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
Try this way.
var socket = io.connect('http://...');
console.log(socket.Socket.sessionid);
The problem could be that the thread calling your code from the hook hasn't been initialized by the runtime so calling runtime methods don't work.
Perhaps you could try doing an Invoke to marshal your code on to the UI thread to call your code that brings the window to the foreground.
By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command
genstrings MyCoolApp/Views/SomeView.swift -s localize -o .
extension:
import UIKit
extension String {
public static func localize(key: String, comment: String) -> String {
return NSLocalizedString(key, comment: comment)
}
}
usage:
String.localize("foo.bar", comment: "Foo Bar Comment :)")
Try to remove node_modules
rm -rf node_modules
and package-lock.json rm -rf package-lock.json
,
after that run npm install
.
The most recent way of overcoming the same-origin policy that I've found is http://anyorigin.com/
The site's made so that you just give it any url and it generates javascript/jquery code for you that lets you get the html/data, regardless of it's origin. In other words, it makes any url or webpage a JSONP request.
I've found it pretty useful :)
Here's some example javascript code from anyorigin:
$.getJSON('http://anyorigin.com/get?url=google.com&callback=?', function(data){
$('#output').html(data.contents);
});
Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)
Not an exact solution but a great alternative to consider
this CSS ONLY Top of screen scroll bar. Solved all the problem with ONLY CSS, NO JavaScript, NO JQuery, No Brain work (lol).
Enjoy my fiddle :D all the codes are included in there :)
CSS
#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}
.w {
width: 900px;
margin: 0 auto;
margin-bottom: 40px;
}<br type="_moz">
Put the content long enough so you can see the effect here :) Oh, and the reference is in there as well, for the fact he deserve his credit
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change
event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
click()
methodSome day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click()
method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true
or false
. Remember that the change
event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop
or attr
, does not fire the change
event.
checked
to a specific valueYou could test the checked
attribute, before calling the click()
method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<Contacts>
<Node>
<ID>123</ID>
<Name>ABC</Name>
</Node>
<Node>
<ID>124</ID>
<Name>DEF</Name>
</Node>
</Contacts>
Select a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected
XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Console.WriteLine(Contact.ToString());
Delete a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";
var Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Contact.Remove();
XMLDoc.Save("test.xml");
Add new node:
XDocument XMLDoc = XDocument.Load("test.xml");
XElement newNode = new XElement("Node",
new XElement("ID", "500"),
new XElement("Name", "Whatever")
);
XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
yes_js_login = function() {
// Your code here
return false;
}
If you return false it should prevent the default action (going to the href).
Edit: Sorry that doesn't seem to work, you can do the following instead:
<a href="http://example.com/no-js-login" onclick="yes_js_login(); return false;">Link</a>
in ViewGroup
you can add some other View
s as child. ViewGroup
is the base class for layouts and view containers.
you can use below directive that get a bool value in html input for focus on it...
//js file
angular.module("appName").directive("ngFocus", function () {
return function (scope, elem, attrs, ctrl) {
if (attrs.ngFocus === "true") {
$(elem).focus();
}
if (!ctrl) {
return;
}
elem.on("focus", function () {
elem.addClass("has-focus");
scope.$apply(function () {
ctrl.hasFocus = true;
});
});
};
});
<!-- html file -->
<input type="text" ng-focus="boolValue" />
You can even set a function in your controller to ngFocus directive value pay attention to below code...
<!-- html file -->
<input type="text" ng-focus="myFunc()" />
//controller file
$scope.myFunc=function(){
if(condition){
return true;
}else{
return false;
}
}
this directive to happen when html page render.
Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery
As a result of a deep code analysis, I've created a function: function callPlayer
requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.
On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.
/**
* @author Rob W <[email protected]>
* @website https://stackoverflow.com/a/7513356/938089
* @version 20190409
* @description Executes function on a framed YouTube video (see website link)
* For a full list of possible functions, see:
* https://developers.google.com/youtube/js_api_reference
* @param String frame_id The id of (the div containing) the frame
* @param String func Desired function to call, eg. "playVideo"
* (Function) Function to call when the player is ready.
* @param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / .ready=true = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if ((!queue || !queue.ready) && (
!domReady ||
iframe && !iframe.contentWindow ||
typeof func === 'function')) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
Usage:
callPlayer("whateverID", function() {
// This function runs once the player is ready ("onYouTubePlayerReady")
callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");
Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.
Q: playVideo
does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay"
on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
but the function doesn't execute any function!
A: You have to add ?enablejsapi=1
at the end of your URL: /embed/vid_id?enablejsapi=1
.
Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://
). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.
Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage
method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.
Q: What browsers are supported?
A: Every browser which supports JSON and postMessage
.
document.readyState
was implemented in 3.6)Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference
onYouTubePlayerReady
: callPlayer('frame_id', function() { ... })
.callPlayer
forces a check of readiness. This is needed, because when callPlayer
is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage
, which was ignored.&origin=*
in the URL.&origin=*
to the URL.I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
If you are using asset catalogs, go to the LaunchImages asset catalog and add the new launch images for the two new iPhones. You may need to right-click and choose "Add New Launch Image" to see a place to add the new images.
The iPhone 6 (Retina HD 4.7) requires a portrait launch image of 750 x 1334.
The iPhone 6 Plus (Retina HD 5.5) requires both portrait and landscape images sized as 1242 x 2208 and 2208 x 1242 respectively.
I'm not sure that you're creating a set with this ([1, 2])
syntax, rather a list. To create a set, you should use set([1, 2])
.
These brackets are just envelopping your expression, as if you would have written:
if (condition1
and condition2 == 3):
print something
There're not really ignored, but do nothing to your expression.
Note: (something, something_else)
will create a tuple (but still no list).
just in case someone looks for this, the path to the file on Sourav answer (httpd.conf) in linux is /opt/lampp/etc/httpd.conf
print(*names)
this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Hopefully someone else is saved by reading this.
We encountered an issue with webkit based browsers doing:
window.open("webpage.htm", "_self");
The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:
location.href = "webpage.html";
all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.
You are using setTimeout
wrong way. The (one of) function signature is setTimeout(callback, delay)
. So you can easily specify what code should be run after what delay.
var codeAddress = (function() {
var index = 0;
var delay = 100;
function GeocodeCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
console.log(results);
}
else alert("Geocode was not successful for the following reason: " + status);
};
return function(vPostCode) {
if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
index++;
};
})();
This way, every codeAddress()
call will result in geocoder.geocode()
being called 100ms later after previous call.
I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay
variable.
Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)
Kind of old question, but with the latest XCode, codesign
is easy:
$ codesign -s my_certificate example.ipa
$ codesign -vv example.ipa
example.ipa: valid on disk
example.ipa: satisfies its Designated Requirement
To solve the problem of not being able to start mongodb on ubuntu 16.04 1) look at mongodb log file
2) we find that the error is due to "Failed to unlink socket file /tmp/mongodb-27017"
3) Look at the permission of file /tmp/mongdb-27017.lock and find that the owner is root instead of mongodb
4) Delete the /tmp/mongodb-27017.sock file manually and use the command "sudo chown mongodb:mongodb /tmp/mongodb*"
5) Start the service with systemcl and use netstat to check whther mongdob has been started on port 27017
Credit: https://www.mkyong.com/mongodb/mongodb-failed-to-unlink-socket-file-tmpmongodb-27017/ https://hevodata.com/blog/install-mongodb-on-ubuntu/
you need to add it to Foo's prototype:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
If non of above works for you, make sure tomcat has access to manager folder under webapps (chown ...). The message is the exact same message, and It took me 2 hours to figure out the problem. :-)
just for someone else who came here for the same issue as me.
Unfortunately, the most common use of <a href="#">
is by lazy programmers who want clickable non-hyperlink javascript-coded elements that behave like anchors, but they can't be arsed to add cursor: pointer;
or :hover
styles to a class for their non-hyperlink elements, and are additionally too lazy to set href
to javascript:void(0);
.
The problem with this is that one <a href="#" onclick="some_function();">
or another inevitably ends up with a javascript error, and an anchor with an onclick javascript error always ends up following its href
. Normally this ends up being an annoying jump to the top of the page, but in the case of sites using <base>
, <a href="#">
is handled as <a href="[base href]/#">
, resulting in an unexpected navigation. If any logable errors are being generated, you won't see them in the latter case unless you enable persistent logs.
If an anchor element is used as a non-anchor it should have its href
set to javascript:void(0);
for the sake of graceful degradation.
I just wasted two days debugging a random unexpected page redirect that should have simply refreshed the page, and finally tracked it down to a function raising the click event of an <a href="#">
. Replacing the #
with javascript:void(0);
fixed it.
The first thing I'm doing Monday is purging the project of all instances of <a href="#">
.
Follow below steps:
Open the file .bashrc
which is found in location C:\Users\USERNAME\.bashrc
If file .bashrc
not exist then create it using below steps:
C:\Users\USERNAME\
.notepad ~/.bashrc
.bashrc
file.Add below sample commands of WP CLI, Git, Grunt & PHPCS etc.
# ----------------------
# Git Command Aliases
# ----------------------
alias ga='git add'
alias gaa='git add .'
alias gaaa='git add --all'
# ----------------------
# WP CLI
# ----------------------
alias wpthl='wp theme list'
alias wppll='wp plugin list'
Now you can use the commands:
ga
instead of git add .
wpthl
instead of wp theme list
Eg. I have used wpthl
for the WP CLI command wp theme list
.
Yum@M MINGW64 /c/xampp/htdocs/dev.test
$ wpthl
+------------------------+----------+-----------+----------+
| name | status | update | version |
+------------------------+----------+-----------+----------+
| twentyeleven | inactive | none | 2.8 |
| twentyfifteen | inactive | none | 2.0 |
| twentyfourteen | inactive | none | 2.2 |
| twentyseventeen | inactive | available | 1.6 |
| twentysixteen | inactive | none | 1.5 |
| twentyten | inactive | none | 2.5 |
| twentythirteen | inactive | none | 2.4 |
| twentytwelve | inactive | none | 2.5 |
For more details read the article Keyboard shortcut/aliases for the WP CLI, Git, Grunt & PHPCS commands for windows
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
You can create a usercontrol with the grid definition and define 'child' controls with varied column definitions in xaml. The parent needs a dependency property for columns and a method for loading the columns:
Parent:
public ObservableCollection<DataGridColumn> gridColumns
{
get
{
return (ObservableCollection<DataGridColumn>)GetValue(ColumnsProperty);
}
set
{
SetValue(ColumnsProperty, value);
}
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("gridColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(parentControl),
new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
public void LoadGrid()
{
if (gridColumns.Count > 0)
myGrid.Columns.Clear();
foreach (DataGridColumn c in gridColumns)
{
myGrid.Columns.Add(c);
}
}
Child Xaml:
<local:parentControl x:Name="deGrid">
<local:parentControl.gridColumns>
<toolkit:DataGridTextColumn Width="Auto" Header="1" Binding="{Binding Path=.}" />
<toolkit:DataGridTextColumn Width="Auto" Header="2" Binding="{Binding Path=.}" />
</local:parentControl.gridColumns>
</local:parentControl>
And finally, the tricky part is finding where to call 'LoadGrid'.
I am struggling with this but got things to work by calling after InitalizeComponent
in my window constructor (childGrid is x:name in window.xaml):
childGrid.deGrid.LoadGrid();
I think this will do:
$('#'+div_id+' .widget-head > span').text("new dialog title");
How about:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
Here is what I did
private void myEvent_Handler(object sender, SomeEvent e)
{
// I dont know how many times this event will fire
Task t = new Task(() =>
{
if (something == true)
{
DoSomething(e);
}
});
t.RunSynchronously();
}
working great and not blocking UI thread
//default locale
System.DateTime.Now.DayOfWeek.ToString();
//localized version
System.DateTime.Now.ToString("dddd");
To make the answer more complete:
If localization is important, you should use the "dddd" string format as Fredrik pointed out - MSDN "dddd" format article
It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...
Demo: http://bootply.com/91632
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="center-block" style="width:200px;background-color:#ccc;">...</div>_x000D_
</div>
_x000D_
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
from itertools import chain, repeat
prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number: a
Not a number! Try again: b
Not a number! Try again: 1
1
or if you want to have a "bad input" message separated from an input prompt as in other answers:
prompt_msg = "Enter a number: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number: a
Sorry, I didn't understand that.
Enter a number: b
Sorry, I didn't understand that.
Enter a number: 1
1
prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
This combination of itertools.chain
and itertools.repeat
will create an iterator
which will yield strings "Enter a number: "
once, and "Not a number! Try again: "
an infinite number of times:
for prompt in prompts:
print(prompt)
Enter a number:
Not a number! Try again:
Not a number! Try again:
Not a number! Try again:
# ... and so on
replies = map(input, prompts)
- here map
will apply all the prompts
strings from the previous step to the input
function. E.g.:
for reply in replies:
print(reply)
Enter a number: a
a
Not a number! Try again: 1
1
Not a number! Try again: it doesn't care now
it doesn't care now
# and so on...
filter
and str.isdigit
to filter out those strings that contain only digits:
only_digits = filter(str.isdigit, replies)
for reply in only_digits:
print(reply)
Enter a number: a
Not a number! Try again: 1
1
Not a number! Try again: 2
2
Not a number! Try again: b
Not a number! Try again: # and so on...
And to get only the first digits-only string we use next
.String methods: Of course you can use other string methods like str.isalpha
to get only alphabetic strings, or str.isupper
to get only uppercase. See docs for the full list.
Membership testing:
There are several different ways to perform it. One of them is by using __contains__
method:
from itertools import chain, repeat
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(fruits.__contains__, replies))
print(valid_response)
Enter a fruit: 1
I don't know this one! Try again: foo
I don't know this one! Try again: apple
apple
Numbers comparison:
There are useful comparison methods which we can use here. For example, for __lt__
(<
):
from itertools import chain, repeat
prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:"))
replies = map(input, prompts)
numeric_strings = filter(str.isnumeric, replies)
numbers = map(float, numeric_strings)
is_positive = (0.).__lt__
valid_response = next(filter(is_positive, numbers))
print(valid_response)
Enter a positive number: a
I need a positive number! Try again: -5
I need a positive number! Try again: 0
I need a positive number! Try again: 5
5.0
Or, if you don't like using dunder methods (dunder = double-underscore), you can always define your own function, or use the ones from the operator
module.
Path existance:
Here one can use pathlib
library and its Path.exists
method:
from itertools import chain, repeat
from pathlib import Path
prompts = chain(["Enter a path: "], repeat("This path doesn't exist! Try again: "))
replies = map(input, prompts)
paths = map(Path, replies)
valid_response = next(filter(Path.exists, paths))
print(valid_response)
Enter a path: a b c
This path doesn't exist! Try again: 1
This path doesn't exist! Try again: existing_file.txt
existing_file.txt
If you don't want to torture a user by asking him something an infinite number of times, you can specify a limit in a call of itertools.repeat
. This can be combined with providing a default value to the next
function:
from itertools import chain, repeat
prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies), None)
print("You've failed miserably!" if valid_response is None else 'Well done!')
Enter a number: a
Not a number! Try again: b
Not a number! Try again: c
You've failed miserably!
Sometimes we don't want to reject an input if the user accidentally supplied it IN CAPS or with a space in the beginning or an end of the string. To take these simple mistakes into account we can preprocess the input data by applying str.lower
and str.strip
methods. For example, for the case of membership testing the code will look like this:
from itertools import chain, repeat
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
lowercased_replies = map(str.lower, replies)
stripped_replies = map(str.strip, lowercased_replies)
valid_response = next(filter(fruits.__contains__, stripped_replies))
print(valid_response)
Enter a fruit: duck
I don't know this one! Try again: Orange
orange
In the case when you have many functions to use for preprocessing, it might be easier to use a function performing a function composition. For example, using the one from here:
from itertools import chain, repeat
from lz.functional import compose
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
process = compose(str.strip, str.lower) # you can add more functions here
processed_replies = map(process, replies)
valid_response = next(filter(fruits.__contains__, processed_replies))
print(valid_response)
Enter a fruit: potato
I don't know this one! Try again: PEACH
peach
For a simple case, for example, when the program asks for age between 1 and 120, one can just add another filter
:
from itertools import chain, repeat
prompt_msg = "Enter your age (1-120): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
numeric_replies = filter(str.isdigit, replies)
ages = map(int, numeric_replies)
positive_ages = filter((0).__lt__, ages)
not_too_big_ages = filter((120).__ge__, positive_ages)
valid_response = next(not_too_big_ages)
print(valid_response)
But in the case when there are many rules, it's better to implement a function performing a logical conjunction. In the following example I will use a ready one from here:
from functools import partial
from itertools import chain, repeat
from lz.logical import conjoin
def is_one_letter(string: str) -> bool:
return len(string) == 1
rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__]
prompt_msg = "Enter a letter (C-P): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(conjoin(*rules), replies))
print(valid_response)
Enter a letter (C-P): 5
Wrong input.
Enter a letter (C-P): f
Wrong input.
Enter a letter (C-P): CDE
Wrong input.
Enter a letter (C-P): Q
Wrong input.
Enter a letter (C-P): N
N
Unfortunately, if someone needs a custom message for each failed case, then, I'm afraid, there is no pretty functional way. Or, at least, I couldn't find one.
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
Let me post a solution here for C++03 that I consider the cleanest possible.*
#define DECLARE_LAMBDA(NAME, RETURN_TYPE, FUNCTION) \
struct { RETURN_TYPE operator () FUNCTION } NAME;
...
int main(){
DECLARE_LAMBDA(demoLambda, void, (){ cout<<"I'm a lambda!"<<endl; });
demoLambda();
DECLARE_LAMBDA(plus, int, (int i, int j){
return i+j;
});
cout << "plus(1,2)=" << plus(1,2) << endl;
return 0;
}
(*) in the C++ world using macros is never considered clean.
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
string a = @"a\\b";
a = a.Replace(@"\\",@"\");
should work. Remember that in the watch Visual STudio show the "\" escaped so you see "\" in place of a single one.
I had the same problem after I used the .gitignore file from https://github.com/github/gitignore/blob/master/Rails.gitignore
Everything worked out fine after I commented the following lines in the .gitignore file.
config/initializers/secret_token.rb
config/secrets.yml
I had this problem. I somehow registered the device for generic team on apple. I don't remember how I did it now. Then I was able to overcome this error.
The syntax of the query is as follows:
Alter table <table name> rename column <column name> to <new column name>;
Example:
Alter table employee rename column eName to empName;
To rename a column name without space to a column name with space:
Alter table employee rename column empName to "Emp Name";
To rename a column with space to a column name without space:
Alter table employee rename column "emp name" to empName;
Adding the "x_ua_compatible" tag to the page didn't work for me. Instead I added it as an HTTP Respone Header via IIS and that worked fine.
In IIS Manager select the site then open HTTP Response Headers and click Add:
The site didn't need restarting, but I did need to Ctrl+F5 to force the page to reload.
I know this does not really fit the specifics of the questions ("one liner"), but since none of the answers above went into this direction while lots and lots of answers addressed the performance issue, I felt I should contribute my thoughts.
Depending on the use case it might not be necessary to create a "real" merged dictionary of the given input dictionaries. A view which does this might be sufficient in many cases, i. e. an object which acts like the merged dictionary would without computing it completely. A lazy version of the merged dictionary, so to speak.
In Python, this is rather simple and can be done with the code shown at the end of my post. This given, the answer to the original question would be:
z = MergeDict(x, y)
When using this new object, it will behave like a merged dictionary but it will have constant creation time and constant memory footprint while leaving the original dictionaries untouched. Creating it is way cheaper than in the other solutions proposed.
Of course, if you use the result a lot, then you will at some point reach the limit where creating a real merged dictionary would have been the faster solution. As I said, it depends on your use case.
If you ever felt you would prefer to have a real merged dict
, then calling dict(z)
would produce it (but way more costly than the other solutions of course, so this is just worth mentioning).
You can also use this class to make a kind of copy-on-write dictionary:
a = { 'x': 3, 'y': 4 }
b = MergeDict(a) # we merge just one dict
b['x'] = 5
print b # will print {'x': 5, 'y': 4}
print a # will print {'y': 4, 'x': 3}
Here's the straight-forward code of MergeDict
:
class MergeDict(object):
def __init__(self, *originals):
self.originals = ({},) + originals[::-1] # reversed
def __getitem__(self, key):
for original in self.originals:
try:
return original[key]
except KeyError:
pass
raise KeyError(key)
def __setitem__(self, key, value):
self.originals[0][key] = value
def __iter__(self):
return iter(self.keys())
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join(repr(original)
for original in reversed(self.originals)))
def __str__(self):
return '{%s}' % ', '.join(
'%r: %r' % i for i in self.iteritems())
def iteritems(self):
found = set()
for original in self.originals:
for k, v in original.iteritems():
if k not in found:
yield k, v
found.add(k)
def items(self):
return list(self.iteritems())
def keys(self):
return list(k for k, _ in self.iteritems())
def values(self):
return list(v for _, v in self.iteritems())
(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)
How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.
For instance, if you don't mind the value being a shallow clone:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
If you've already constrained T to implement ICloneable:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => (T) entry.Value.Clone());
(Those are untested, but should work.)
Basic difference between various options of git reset command are as below.
It was recently identified that Composer consumes high CPU + memory on packages that have a lot of historical tags. See composer/composer#7577
A workaround to this problem is using symfony/flex
or https://github.com/rubenrua/symfony-clean-tags-composer-plugin
composer global require rubenrua/symfony-clean-tags-composer-plugin
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
As of Java 7 (and Android API level 19):
System.lineSeparator()
Documentation: Java Platform SE 7
For older versions of Java, use:
System.getProperty("line.separator");
See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.
Teja Kumar Bethina's code changed for Swift 3:
let urlStr = "http://url_to_manage_post_requests"
let url = URL(string: urlStr)
var request: URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.timeoutInterval = 60.0
//additional headers
request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")
let bodyStr = "string or data to add to body of request"
let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
request.httpBody = bodyData
let task = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in
if let httpResponse = response as? HTTPURLResponse {
print("responseCode \(httpResponse.statusCode)")
}
if error != nil {
// You can handle error response here
print("\(error)")
} else {
//Converting response to collection formate (array or dictionary)
do {
let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
JSONSerialization.ReadingOptions.mutableContainers))
//success code
} catch {
//failure code
}
}
}
task.resume()
Remove the public
keyword from int[] locations={1,2,3};
. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.
If your goal is to use this reference in many a method, you might want to move the declaration outside the method.
Tested On Ubuntu 20, sudo chown -R $USER:$USER /var/www
Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.
Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.
Abstraction is like using a computer.
You have absolutely no idea what's going on with it beyond what you see with the GUI (graphical user interface) and external hardware (e.g. screen). All those pretty colors and such. You're only presented the details relevant to you as a generic consumer.
Encapsulation is the actual act of hiding the irrelevant details.
You use your computer, but you don't see what its CPU (central processing unit) looks like (unless you try to break into it). It's hidden (or encapsulated) behind all that chrome and plastic.
In the context of OOP (object-oriented programming) languages, you usually have this kind of setup:
CLASS {
METHOD {
*the actual code*
}
}
An example of "encapsulation" would be having a METHOD that the regular user can't see (private). "Abstraction" is the regular user using the METHOD that they can (public) in order to use the private one.
To fix this, open the SQL Server Management Studio and click New Query. Then type:
USE mydatabase
exec sp_changedbowner 'sa', 'true'
To update and/or enhance the answer by @Hans Passant I would separate the retrieval of the property into an extension method. This has the added benefit of removing the nasty magic string in the method GetProperty()
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
Your test is then reduced to two lines
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));