All package managers have many downsides. You just have to pick which you can live with.
npm started out managing node.js modules (that's why packages go into node_modules
by default), but it works for the front-end too when combined with Browserify or webpack.
Bower is created solely for the front-end and is optimized with that in mind.
npm is much, much larger than bower, including general purpose JavaScript (like country-data
for country information or sorts
for sorting functions that is usable on the front end or the back end).
Bower has a much smaller amount of packages.
Bower includes styles etc.
npm is focused on JavaScript. Styles are either downloaded separately or required by something like npm-sass
or sass-npm
.
The biggest difference is that npm does nested dependencies (but is flat by default) while Bower requires a flat dependency tree (puts the burden of dependency resolution on the user).
A nested dependency tree means that your dependencies can have their own dependencies which can have their own, and so on. This allows for two modules to require different versions of the same dependency and still work. Note since npm v3, the dependency tree will be flat by default (saving space) and only nest where needed, e.g., if two dependencies need their own version of Underscore.
Some projects use both: they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.
Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:
/pages/en/faqs/faq-page1.html
Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them
index.html
is:
/pages/en/faqs/index.html
if called from /pages/en/faqs/faq-page1.html
/pages/index.html
if called from /pages/example.html
There are also two special directory names: .
and ..
:
.
means "current directory"..
means "parent directory"You can use them to build relative paths:
../index.html
is /pages/en/index.html
if called from /pages/en/faqs/faq-page1.html
../../index.html
is /pages/index.html
if called from /pages/en/faqs/faq-page1.html
Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:
fun hasPermission(permission: String): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
For me I do this to find,
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in ...}
Can't use
"let url = NSURL(string: urlString)
I think that ucfagls found why your loop is not working.
In case you still don't want use a loop here is solution with lapply
:
factorToNumeric <- function(f) as.numeric(levels(f))[as.integer(f)]
cols <- c(1, 3:ncol(stats))
stats[cols] <- lapply(stats[cols], factorToNumeric)
Edit. I found simpler solution. It seems that as.matrix
convert to character. So
stats[cols] <- as.numeric(as.matrix(stats[cols]))
should do what you want.
SELECT SCOPE_IDENTITY()
after the insert statement
Please refer the following links
$(document).ready(function(){
$('#mySelect').append("<option>BMW</option>")
})
Synchronized Vs Atomic Vs Volatile:
Please correct me if anything i missed.
Edit the tty configuration in /etc/init/tty*.conf
with a shellscript as a parameter :
(...)
exec /sbin/getty -n -l theInputScript.sh -8 38400 tty1
(...)
This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.
A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.
Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.
You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");
If you are using qmake, the standard Qt build system, just add a line to the .pro
file as documented in the qmake Variable Reference:
INCLUDEPATH += <your path>
If you are using your own build system, you create a project by selecting "Import of Makefile-based project". This will create some files in your project directory including a file named <your project name>.includes
. In that file, simply list the paths you want to include, one per line. Really all this does is tell Qt Creator where to look for files to index for auto completion. Your own build system will have to handle the include paths in its own way.
As explained in the Qt Creator Manual, <your path>
must be an absolute path, but you can avoid OS-, host- or user-specific entries in your .pro
file by using $$PWD
which refers to the folder that contains your .pro
file, e.g.
INCLUDEPATH += $$PWD/code/include
You don't actually need select_db
. You can send a query to two databases at the same time. First, give a grant to DB1
to select from DB2
by GRANT select ON DB2.* TO DB1@localhost;
. Then, FLUSH PRIVILEGES;
. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2
etc. (Don't forget that you need 'root' access to use grant command)
I got similar error while using in-app-purchase in android. My mistake is I used wrong purchase id while instantiating the purchases.
public static final String PRODUCT_ID_ASTRO_Match = "android.test.product";//wrong id not in play store dev console
Replaced it with:
public static final String PRODUCT_ID_ASTRO_Match = "android.test.purchased";
and it worked.
Check this link
get distinct rows from datatable using Linq (distinct with mulitiple columns)
Or try this
var distinctRows = (from DataRow dRow in dTable.Rows
select new { col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();
EDIT: Placed the missing first curly brace.
For me it happened when I forgot to write extends React.Component
at the end.
I know it's not exactly what YOU had, but others reading this answer can benefit from this, hopefully.
Another way to do this is to use the copy constructor:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);
Or create an empty set and add the elements:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);
Unlike clone
these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.
Note that the result of copying a Set
is a new Set
containing references to the objects that are elements if the original Set
. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection
APIs are designed to work: they don't copy the element objects.
public void getDatabaseMetaData()
{
try {
DatabaseMetaData dbmd = conn.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", types);
while (rs.next()) {
System.out.println(rs.getString("TABLE_NAME"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
Here is what I did: I check the body y position , then make the body fixed and adjust the top to the negative of that position. On reverse, I make the body static and set the scroll to the value I recorded before.
var body_x_position = 0;
function disable_bk_scrl(){
var elb = document.querySelector('body');
body_x_position = elb.scrollTop;
// get scroll position in px
var body_x_position_m = body_x_position*(-1);
console.log(body_x_position);
document.body.style.position = "fixed";
$('body').css({ top: body_x_position_m });
}
function enable_bk_scrl(){
document.body.style.position = "static";
document.body.scrollTo(0, body_x_position);
console.log(body_x_position);
}
As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush()
, but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:
set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href
attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href
attributes blank.
<a href="" data-router="article" ng-click="changeListName('metro')">
Also I don't know what data-router
is doing but if you still aren't getting the proper result, that could be why.
You can concat origin
and pathname
, if theres present a port such as example.com:80
, that will be included as well.
location.origin + location.pathname
They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.
Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.
Then you can use exit() and catch that later on. Die() however doesn't support that.
Die() always exists with code 0. So essentially a die() command does the following:
<?php
echo "I am going to die";
exit(0);
?>
Which is the same as:
<?php
die("I am going to die");
?>
If you are using maven in the jersey project add below in pom.xml and update project dependencies so that Jaxb is able to detect model class and convert list to Media type application XML:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
You need
@ManagedBean(name="userBean")
Make sure you have getUser()
method.
Type of setUser()
method should be void
.
Make sure that User
class has proper setters
and getters
as well.
This probably isn't exactly the answer you're looking for, but having struggled with this myself and having issues with suggested answers, I decided to make it uncontrolled instead.
When editable
prop is false
, I use text
prop as is, but when it is true
, I switch to editing mode in which text
has no effect (but at least browser doesn't freak out). During this time onChange
are fired by the control. Finally, when I change editable
back to false
, it fills HTML with whatever was passed in text
:
/** @jsx React.DOM */
'use strict';
var React = require('react'),
escapeTextForBrowser = require('react/lib/escapeTextForBrowser'),
{ PropTypes } = React;
var UncontrolledContentEditable = React.createClass({
propTypes: {
component: PropTypes.func,
onChange: PropTypes.func.isRequired,
text: PropTypes.string,
placeholder: PropTypes.string,
editable: PropTypes.bool
},
getDefaultProps() {
return {
component: React.DOM.div,
editable: false
};
},
getInitialState() {
return {
initialText: this.props.text
};
},
componentWillReceiveProps(nextProps) {
if (nextProps.editable && !this.props.editable) {
this.setState({
initialText: nextProps.text
});
}
},
componentWillUpdate(nextProps) {
if (!nextProps.editable && this.props.editable) {
this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText);
}
},
render() {
var html = escapeTextForBrowser(this.props.editable ?
this.state.initialText :
this.props.text
);
return (
<this.props.component onInput={this.handleChange}
onBlur={this.handleChange}
contentEditable={this.props.editable}
dangerouslySetInnerHTML={{__html: html}} />
);
},
handleChange(e) {
if (!e.target.textContent.trim().length) {
e.target.innerHTML = '';
}
this.props.onChange(e);
}
});
module.exports = UncontrolledContentEditable;
I could not made your code to do the desired query, the AS is an alias only for the table abc
, not for the derived table.
Laravel Query Builder does not implicitly support derived table aliases, DB::raw is most likely needed for this.
The most straight solution I could came up with is almost identical to yours, however produces the query as you asked for:
$sql = Abc::groupBy('col1')->toSql();
$count = DB::table(DB::raw("($sql) AS a"))->count();
The produced query is
select count(*) as aggregate from (select * from `abc` group by `col1`) AS a;
Total online memory
Calculate the total online memory using the sys-fs.
totalmem=0;
for mem in /sys/devices/system/memory/memory*; do
[[ "$(cat ${mem}/online)" == "1" ]] \
&& totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes)))));
done
#one-line code
totalmem=0; for mem in /sys/devices/system/memory/memory*; do [[ "$(cat ${mem}/online)" == "1" ]] && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes))))); done
echo ${totalmem} bytes
echo $((totalmem/1024**3)) GB
Example output for 4 GB system:
4294967296 bytes
4 GB
Explanation
/sys/devices/system/memory/block_size_bytes
Number of bytes in a memory block (hex value). Using 0x in front of the value makes sure it's properly handled during the calculation.
/sys/devices/system/memory/memory*
Iterating over all available memory blocks to verify they are online and add the calculated block size to totalmem if they are.
[[ "$(cat ${mem}/online)" == "1" ]] &&
You can change or remove this if you prefer another memory state.
Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.
However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
Restart computer solved it for me.
Git version: 2.27.0.windows.1
OS version: Windows 10 v1909
It can be done with simple Makefile:
sleep%:
sleep $(subst sleep,,$@)
@echo $@ done.
Use -j
option.
$ make -j sleep3 sleep2 sleep1
sleep 3
sleep 2
sleep 1
sleep1 done.
sleep2 done.
sleep3 done.
Without -j
option it executes in serial.
$ make -j sleep3 sleep2 sleep1
sleep 3
sleep3 done.
sleep 2
sleep2 done.
sleep 1
sleep1 done.
You can also do dry run with `-n' option.
$ make -j -n sleep3 sleep2 sleep1
sleep 3
sleep 2
sleep 1
L is a prefix used for wide strings. Each character uses several bytes (depending on the size of wchar_t
). The encoding used is independent from this prefix. I mean it must not be necessarily UTF-16 unlike stated in other answers here.
If it is two IEnumerable lists you can't use AddRange
, but you can use Concat
.
IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};
var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
I did that with helping from this question
jquery get querystring from URL
so let see how we will use this function
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
and now just use it in Ajax call
"ajax": {
url: '/Departments/GetAllDepartments/',
type: 'GET',
dataType: 'json',
data: getUrlVars()// here is the tricky part
},
thats all, but if you want know how to use this function
or not send all the query string parameters
back to actual answer
Ok this this seems late and I was testing the app with internet connection off to test my app for some functionality. As I turned off the internet it gave me such error. After I turned on the internet I can install again. I know this is silly but this might be helpful to someone
This data is JSON! You can deserialize it using the built-in json
module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson
module.
import json # or `import simplejson as json` if on Python < 2.6
json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string) # obj now contains a dict of the data
Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.
You can use format like here,
public static double getDoubleValue(String value,int digit){
if(value==null){
value="0";
}
double i=0;
try {
DecimalFormat digitformat = new DecimalFormat("#.##");
digitformat.setMaximumFractionDigits(digit);
return Double.valueOf(digitformat.format(Double.parseDouble(value)));
} catch (NumberFormatException numberFormatExp) {
return i;
}
}
There's an easier way.
Install cliget/CURLWGET from firefox/chrome extension.
Download the file from browser. This creates a curl/wget link that remembers the cookies and headers used while downloading the file. Use this command from any shell to download
Using the request library can help minimize the cruft:
var request = require('request')
request({ uri: 'http://api.com/1' }, function(err, response, body){
// use body
request({ uri: 'http://api.com/2' }, function(err, response, body){
// use body
request({ uri: 'http://api.com/3' }, function(err, response, body){
// use body
})
})
})
But for maximum awesomeness you should try some control-flow library like Step - it will also allow you to parallelize requests, assuming that it's acceptable:
var request = require('request')
var Step = require('step')
// request returns body as 3rd argument
// we have to move it so it works with Step :(
request.getBody = function(o, cb){
request(o, function(err, resp, body){
cb(err, body)
})
}
Step(
function getData(){
request.getBody({ uri: 'http://api.com/?method=1' }, this.parallel())
request.getBody({ uri: 'http://api.com/?method=2' }, this.parallel())
request.getBody({ uri: 'http://api.com/?method=3' }, this.parallel())
},
function doStuff(err, r1, r2, r3){
console.log(r1,r2,r3)
}
)
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
you can also skip creating dictionary altogether. i used below approach to same problem .
mappedItems: {};
items.forEach(item => {
if (mappedItems[item.key]) {
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
} else {
mappedItems[item.key] = [];
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
}
});
this works for me:
SELECT datefield
FROM myTable
ORDER BY CONVERT(DATE, datefield) ASC
You have to return
from the onbeforeunload
:
window.onbeforeunload = function() {
saveFormData();
return null;
}
function saveFormData() {
console.log('saved');
}
UPDATE
as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)
FROM MDN
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog()
,window.alert()
,window.confirm()
, andwindow.prompt()
methods may be ignored during this event.
It is also suggested to use this through the addEventListener
interface:
You can and should handle this event through
window.addEventListener()
and thebeforeunload
event.
The updated code will now look like this:
window.addEventListener("beforeunload", function (e) {
saveFormData();
(e || window.event).returnValue = null;
return null;
});
I believe GUIDs are constrained to 16-byte lengths (or 32 bytes for an ASCII hex equivalent).
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:
var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
A bit late to the party but, should you have root access, you can do the following directly:
Log into your mysql as root,
$ mysql -u root -p
Show databases;
mysql>SHOW DATABASES;
Select mysql database, which is where all privileges info is located
mysql>USE mysql;
Show tables.
mysql>SHOW TABLES;
The table concerning privileges for your case is 'db', so let's see what columns it has:
mysql>DESC db;
In order to list the users privileges, type the following command, for example:
mysql>SELECT user, host, db, Select_priv, Insert_priv, Update_priv, Delete_priv FROM db ORDER BY user, db;
If you can't find that user or if you see that that user has a 'N' in the Select_priv column, then you have to either INSERT or UPDATE accordingly:
INSERT:
INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv) VALUES ('localhost','DBname','UserName','Y' ,'N','N','N');
UPDATE:
UPDATE db SET Select_priv = 'Y' WHERE User = 'UserName' AND Db = 'DBname' AND Host='localhost';
Finally, type the following command:
mysql>FLUSH PRIVILEGES;
Ciao.
An explicit default initialization can help:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Behavior bool a {}
is same as bool b = bool();
and return false
.
If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE
function instead of SUBTOTAL
.
I just tested this and it works in Access 2010.
Say you have a SELECT query with parameters:
PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));
You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].
Now you create an UPDATE query based on that query:
UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));
You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].
You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:
Sub paramTest()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
qdf!startID = 1 ' specify
qdf!endID = 2 ' parameters
qdf.Execute
Set qdf = Nothing
End Sub
Forward declare class B
and swap order of A
and B
definitions: 1st B
and 2nd A
. You can not call methods of forward declared B
class.
//xn=list of parent nodes......
foreach (XmlNode xn in xnList)
{
foreach (XmlNode child in xn.ChildNodes)
{
if (child.Name.Equals("name"))
{
name = child.InnerText;
}
if (child.Name.Equals("age"))
{
age = child.InnerText;
}
}
}
As "there are tens of thousands of cells in the page" binding the click-event to every single cell will cause a terrible performance problem. There's a better way to do this, that is binding a click event to the body & then finding out if the cell element was the target of the click. Like this:
$('body').click(function(e){
var Elem = e.target;
if (Elem.nodeName=='td'){
//.... your business goes here....
// remember to replace $(this) with $(Elem)
}
})
This method will not only do your task with native "td" tag but also with later appended "td". I think you'll be interested in this article about event binding & delegate
Or you can simply use the ".on()" method of jQuery with the same effect:
$('body').on('click', 'td', function(){
...
});
I don't think there is any difference, one is a shortcut for the other. Although your exact implementation might deal with them differently.
The combined parallel worksharing constructs are a shortcut for specifying a parallel construct containing one worksharing construct and no other statements. Permitted clauses are the union of the clauses allowed for the parallel and worksharing contructs.
Taken from http://www.openmp.org/mp-documents/OpenMP3.0-SummarySpec.pdf
The specs for OpenMP are here:
You can use the function outer()
to generate it.
Have a look at the demo for the function persp()
, which is a base graphics function to draw perspective plots for surfaces.
Here is their first example:
x <- seq(-10, 10, length.out = 50)
y <- x
rotsinc <- function(x,y) {
sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
10 * sinc( sqrt(x^2+y^2) )
}
z <- outer(x, y, rotsinc)
persp(x, y, z)
The same applies to surface3d()
:
require(rgl)
surface3d(x, y, z)
import string, itertools
#password = input("Enter password: ")
password = "abc"
characters = string.printable
def iter_all_strings():
length = 1
while True:
for s in itertools.product(characters, repeat=length):
yield "".join(s)
length +=1
for s in iter_all_strings():
print(s)
if s == password:
print('Password is {}'.format(s))
break
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
There is also argparse
stdlib module (an "impovement" on stdlib's optparse
module). Example from the introduction to argparse:
# script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'integers', metavar='int', type=int, choices=range(10),
nargs='+', help='an integer in the range 0..9')
parser.add_argument(
'--sum', dest='accumulate', action='store_const', const=sum,
default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Usage:
$ script.py 1 2 3 4
4
$ script.py --sum 1 2 3 4
10
/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting
Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get
Try:
move files\*.txt \
Edit: Try:
move \files\*.txt \
Edit 2:
move C:\files\*.txt C:\txt
If you have a radio button with same id, then you can clear the selection
Radio Button definition :
<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD
Clearing all values of radio button:
document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...
While the other answers have not worked for me in all situations, the best solution I could find (working with POST
as well), taken from here:
curl -vs 'https://some-site.com' 1> /dev/null
it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.
Hope this helps to someone.
Also consider using an .editorconfig file: https://marketplace.eclipse.org/content/editorconfig-eclipse. Someone not using Eclipse may also benefit from this, in the worst case it can serve as a guideline. NOTE: I will not enter the tabs vs space wars but use spaces FTW :-)
Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Relative answer: Deploying website: 500 - Internal server error
By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.
Try this.... Replace body with parent selector
$('body').on('click', '#my-button', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Give the same name in urls.py
path('detail/<int:id>', views.detail, name="detail"),
For simplicity and well structured sake, use SpringMVC. It's just so simple.
@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
return carService.getAllCars();
}
Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs
import re
my_string = """Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the
same as double quotes."""
# if we need to count the word python that ends with or without ',' or '.' at end
count = 0
for i in text:
if i.endswith("."):
text[count] = re.sub("^([a-z]+)(.)?$", r"\1", i)
count += 1
print("The count of Python : ", text.count("python"))
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")
tv_nsec
is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:
nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();
For the simple case of just copying the last commit from branch wss to v2.1, you can simply grab the commit id (git log --oneline | head -n 1
) and do:
git checkout v2.1
git merge <commit>
Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.
Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.
TLDR; Here's why:
The reason this works is because
gulp
tries to run yourgulpfile.js
using your locally installed version ofgulp
, see here. Hence the reason for a global and local install of gulp.
Essentially, when you install gulp
locally the script isn't in your PATH
and so you can't just type gulp
and expect the shell to find the command. By installing it globally the gulp
script gets into your PATH
because the global node/bin/
directory is most likely on your path.
To respect your local dependencies though, gulp
will use your locally installed version of itself to run the gulpfile.js
.
Creating a virtual environment for Jupyter Notebooks
A minimal Python install is
sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip
Then you can create and use the environment
/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate
You can make a kernel for Jupyter with
ipython3 kernel install --user --name=test
Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.
I understand that your main problem is that you need to calculate d=b-a
but your arrays have different sizes. There is no need for an intermediate padded c
You can solve this without padding:
import numpy as np
a = np.array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
b = np.array([[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.]])
d = b.copy()
d[:a.shape[0],:a.shape[1]] -= a
print d
Output:
[[ 2. 2. 2. 2. 2. 3.]
[ 2. 2. 2. 2. 2. 3.]
[ 2. 2. 2. 2. 2. 3.]
[ 3. 3. 3. 3. 3. 3.]]
After heavy testing we came to the conclusion that GROUP BY is faster
SELECT sql_no_cache
opnamegroep_intern
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13) group by opnamegroep_intern
635 totaal 0.0944 seconds Weergave van records 0 - 29 ( 635 totaal, query duurde 0.0484 sec)
SELECT sql_no_cache
distinct (opnamegroep_intern)
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13)
635 totaal 0.2117 seconds ( almost 100% slower ) Weergave van records 0 - 29 ( 635 totaal, query duurde 0.3468 sec)
I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
$('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
<div class="imgs" data-image-id='1'>1</div>_x000D_
<div class="imgs" data-image-id='2'>2</div>_x000D_
<div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/ruys9ksg/
I had a need to request permission for WRITE_EXTERNAL_STORAGE
but was not getting a pop-up despite trying all of the different suggestions mentioned.
The culprit in the end was HockeyApp. It uses manifest merging to include its own permission for WRITE_EXTERNAL_STORAGE
except it applies a max sdk version onto it.
The way to get around this problem is to include it in your Manifest file but with a replace against it, to override the HockeyApp's version and success!
4.7.2 Other dependencies requesting the external storage permission (SDK version 5.0.0 and later) To be ready for Android O, HockeySDK-Android 5.0.0 and later limit the
WRITE_EXTERNAL_STORAGE
permission with the maxSdkVersion filter. In some use cases, e.g. where an app contains a dependency that requires this permission, maxSdkVersion makes it impossible for those dependencies to grant or request the permission. The solution for those cases is as follows:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>
It will cause that other attributes from low priority manifests will be replaced instead of being merged.
My explanation is in the code. :)
DECLARE @TestConvert VARCHAR(MAX) = '123456789.1234567'
BEGIN TRY
SELECT CAST(@TestConvert AS DECIMAL(10, 4))
END TRY
BEGIN CATCH
SELECT 'The reason you get the message "' + ERROR_MESSAGE() + '" is because DECIMAL(10, 4) only allows for 4 numbers after the decimal.'
END CATCH
-- Here's one way to truncate the string to a castable value.
SELECT CAST(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)) AS DECIMAL(14, 4))
-- If you noticed, I changed it to DECIMAL(14, 4) instead of DECIMAL(10, 4) That's because this number has 14 digits, as proven below.
-- Read this for a better explanation as to what precision, scale and length mean: http://msdn.microsoft.com/en-us/library/ms190476(v=sql.105).aspx
SELECT LEN(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)))
It's /public_html/stats/*
.
$ ~/myrepo> ls public_html/stats/
bar baz foo
$ ~/myrepo> cat .gitignore
public_html/stats/*
$ ~/myrepo> git status
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ ~/myrepo>
If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :
date("Y-m-d H:i:s", $myTimestamp)
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
Parameter names are normally not accessible by the Java code at runtime (because it's drop by the compiler), so if you want that functionality you need to either use Java 8's built-in functionality or use a library such as ParaNamer in order to gain access to it.
So in order to not having to utilize annotations for the constructor arguments when using Jackson, you can make use of either of these 2 Jackson modules:
This module allows you to get annotation-free constructor arguments when using Java 8. In order to use it you first need to register the module:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule());
Then compile your code using the -parameters flag:
javac -parameters ...
Link: https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names
This other one simply requires you to register the module or configure an annotation introspection (but not both as pointed out by the comments). It allows you to use annotation-free constructor arguments on versions of Java prior to 1.8.
ObjectMapper mapper = new ObjectMapper();
// either via module
mapper.registerModule(new ParanamerModule());
// or by directly assigning annotation introspector (but not both!)
mapper.setAnnotationIntrospector(new ParanamerOnJacksonAnnotationIntrospector());
Link: https://github.com/FasterXML/jackson-modules-base/tree/master/paranamer
I had same Issue and i solve it following way:
The xml file which is using for create a Row inside createViewholder, just add below line:
android:clickable="true"
android:focusableInTouchMode="true"
android:background="?attr/selectableItemBackgroundBorderless"
OR If you using frameLayout as a parent of row item then:
android:clickable="true"
android:focusableInTouchMode="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
In java code inside view holder where you added on click listener:
@Override
public void onClick(View v) {
//ur other code here
v.setPressed(true);
}
To Send bold,italic,fixed width code you can use this :
# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname,
text="*boldtext* _italictext_ `fixed width font` [link] (http://google.com).",
parse_mode=telegram.ParseMode.MARKDOWN)
make sure you have enabled the bot as your admin .Then only it can send message
int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();
Hope this works. You can convert your output to string in the above manner.
gender.getCheckedRadioButtonId();
- gender is the id of RadioGroup.
this is a simple code I just wrote to solve this, without removing the header row (first one).
var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}
Hope it works for you!!.
Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);
A word of caution:
In my experience, omitting the href
attribute causes problems for accessibility as the keyboard navigation will ignore it and never give it focus like it will when href is present. Manually including your element in the tabindex is a way around that.
This will work:
select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp
$ php artisan route:list
+--------+--------------------------------+----------------------------+-- -----------------+----------------------------------------------------+--------- ---+
| Domain | Method | URI | Name | Action | Middleware |
+--------+--------------------------------+----------------------------+-------------------+----------------------------------------------------+------------+
| | GET|HEAD | / |
| | GET | campaign/showtakeup/{id} | showtakeup | App\Http\Controllers\campaignController@showtakeup | auth | |
routes.php
Route::get('campaign/showtakeup/{id}', ['uses' =>'campaignController@showtakeup'])->name('showtakeup');
campaign.showtakeup.blade.php
@foreach($campaign as $campaigns)
//route parameters; you may pass them as the second argument to the method:
<a href="{{route('showtakeup', ['id' => $campaigns->id])}}">{{ $campaigns->name }}</a>
@endforeach
Hope this solves your problem. Thanks
If you just use rm
, you will need to follow it up with git add <fileRemoved>
. git rm
does this in one step.
You can also use git rm --cached
which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.
Consider:
class Bike(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100), # <--
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165), # <--
}
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin
print(profit)
Output:
33.0 20.0
The difference is that in your bikes
dictionary, you're initializing the values as lists [...]
. Instead, it looks like the rest of your code wants Bike
instances. So create Bike
instances: Bike(...)
.
As for your error
AttributeError: 'list' object has no attribute 'cost'
this will occur when you try to call .cost
on a list
object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost
-- in this line:
profit = bike.cost * margin
This indicates that at least one bike
(that is, a member of bikes.values()
is a list). If you look at where you defined bikes
you can see that the values were, in fact, lists. So this error makes sense.
But since your class has a cost attribute, it looked like you were trying to use Bike
instances as values, so I made that little change:
[...] -> Bike(...)
and you're all set.
You can use NSNotification
Add a post method in your custom class:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
Please note that if you have multiple application.properties
files throughout your codebase, then try adding your value to the parent project's property file.
You can check your project's pom.xml
file to identify what the parent project of your current project is.
Alternatively, try using environment.getProperty()
instead of @Value
.
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
PHP is likely the easiest.
Just make a file script.php
that contains <?php shell_exec("yourscript.sh"); ?>
and send anybody who clicks the button to that destination. You can return the user to the original page with header:
<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>
Unfortunately PL/SQL doesn't have IF EXISTS
operator like SQL Server. But you can do something like this:
begin
for x in ( select count(*) cnt
from dual
where exists (
select 1 from courseoffering co
join co_enrolment ce on ce.co_id = co.co_id
where ce.s_regno = 403
and ce.coe_completionstatus = 'C'
and co.c_id = 803 ) )
loop
if ( x.cnt = 1 )
then
dbms_output.put_line('exists');
else
dbms_output.put_line('does not exist');
end if;
end loop;
end;
/
Why not use a filter?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use
if(exists){
// it is in the dropdown
}
Or combine it:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
You can use zip
with *
to get transpose of a matrix:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
try this. http://jsfiddle.net/fVpkm/
Html:-
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
JS:-
$('button').click(function(){ //you can give id or class name here for $('button')
$(this).text(function(i,old){
return old=='+' ? '-' : '+';
});
});
Update With pure Css, pseudo elements
button.btn.collapsed:before
{
content:'+' ;
display:block;
width:15px;
}
button.btn:before
{
content:'-' ;
display:block;
width:15px;
}
Update 2 With pure Javascript
function handleClick()
{
this.value = (this.value == '+' ? '-' : '+');
}
document.getElementById('collapsible').onclick=handleClick;
I just got the same situation, Factory data reset worked well for me.
Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH)
should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY)
.
I got the same error message. In my case, it was due to not using quotes.
Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.
So I was doing this:
select * from mytable where myid = 1234
While I should be doing this:
select * from mytable where myid = '1234'
If the column had all numbers, the conversion would have worked, but not in this case.
install PIL using the command "sudo apt-get install python-imaging" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values
import PIL
import Image
FILENAME='fn.gif' #image can be in gif jpeg or png format
im=Image.open(FILENAME).convert('RGB')
pix=im.load()
w=im.size[0]
h=im.size[1]
for i in range(w):
for j in range(h):
print pix[i,j]
Java supports* covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.
For example:
class ShapeBuilder {
...
public Shape build() {
....
}
class CircleBuilder extends ShapeBuilder{
...
@Override
public Circle build() {
....
}
This is specified in section 8.4.5 of the Java Language Specification:
Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
If R1 is void then R2 is void.
If R1 is a primitive type, then R2 is identical to R1.
If R1 is a reference type then:
R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or
R1 = |R2|
("|R2|" refers to the erasure of R2, as defined in §4.6 of the JLS.)
* Prior to Java 5, Java had invariant return types, which meant the return type of a method override needed to exactly match the method being overridden.
You have two options:
OPTION 1:
You can use removeProperty method. It will remove a style from an element.
el.style.removeProperty('zoom');
OPTION 2:
You can set it to the default value:
el.style.zoom = "";
The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.
This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache
user has read/write access to your entire repository. To do that, chown -R apache:apache *
, chmod -R 664 *
for everything under your svn repository.
Also, see here and here if you're still stuck.
The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.
Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:
For example, 764 on a file would mean that:
Hope that clears things up!
You can copy an iterator to a new list like this:
Iterator<String> iter = list.iterator();
List<String> copy = new ArrayList<String>();
while (iter.hasNext())
copy.add(iter.next());
That's assuming that the list contains strings. There really isn't a faster way to recreate a list from an iterator, you're stuck with traversing it by hand and copying each element to a new list of the appropriate type.
EDIT :
Here's a generic method for copying an iterator to a new list in a type-safe way:
public static <T> List<T> copyIterator(Iterator<T> iter) {
List<T> copy = new ArrayList<T>();
while (iter.hasNext())
copy.add(iter.next());
return copy;
}
Use it like this:
List<String> list = Arrays.asList("1", "2", "3");
Iterator<String> iter = list.iterator();
List<String> copy = copyIterator(iter);
System.out.println(copy);
> [1, 2, 3]
I solved this problem to add a public setter for all properties, which should be deserialized.
you want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?
You can do this by simple adding attribute required = "required" in the select tag. you can see it in below code
<select id="select" required="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
It worked fine for me at chorme, firefox and internet explorer. Thanks
As of Chrome 46, a simple onclick=window.close()
does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.
It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.
In that case, it might be that you program exits before the writing can be finished.
If your program uses an event loop (like with a GUI application, e.g. QMainWindow
) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).
stream << "something" << endl;
stream.flush();
This guarantees that the changes are committed to the file before the program continues from this instruction.
The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
does already return a dataframe, so you cannot loop over the groups anymore.
In general:
df.groupby(...)
returns a GroupBy
object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:
grouped = df.groupby('A')
for name, group in grouped:
...
When you apply a function on the groupby, in your example df.groupby(...).agg(...)
(but this can also be transform
, apply
, mean
, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).
@Html.TextBoxFor(m => m.PositiveNumber,
new { @type = "number", @class = "span4", @min = "0" })
in MVC 5 with Razor you can add any html input attribute in the anonymous object as per above example to allow only positive numbers into the input field.
You can save the search results in a common service which can use from anywhere and doesn't clear when navigate to another page, and then you can set the search results with the saved data for the click of back button
function search(searchTerm) {
// retrieve the data here;
RetrievedData = CallService();
CommonFunctionalityService.saveSerachResults(RetrievedData);
}
For your backbutton
function Backbutton() {
RetrievedData = CommonFunctionalityService.retrieveResults();
}
Following is a code snippet which splits a sentense to word and give its count too.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class StringToword {
public static void main(String[] args) {
String s="a a a A A";
String[] splitedString=s.split(" ");
Map m=new HashMap();
int count=1;
for(String s1 :splitedString){
count=m.containsKey(s1)?count+1:1;
m.put(s1, count);
}
Iterator<StringToword> itr=m.entrySet().iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
You can just run the command
git parent
to find the parent of the branch, if you add the @Joe Chrysler's answer as a git alias. It will simplify the usage.
Open gitconfig file located at "~/.gitconfig"
by using any text editor. ( For linux). And for Windows the ".gitconfig" path is generally located at c:\users\your-user\.gitconfig
vim ~/.gitconfig
Add the following alias command in the file:
[alias]
parent = "!git show-branch | grep '*' | grep -v \"$(git rev-parse --abbrev-ref HEAD)\" | head -n1 | sed 's/.*\\[\\(.*\\)\\].*/\\1/' | sed 's/[\\^~].*//' #"
Save and exit the editor.
Run the command git parent
That's it!
i also have the same problem while parsing schema definition files(XSD) using XSOM library,
i was able to increase Stack memory upto 208Mb then it showed heap_out_of_memory_error
for which i was able to increase only upto 320mb.
the final configuration was -Xmx320m -Xss208m
but then again it ran for some time and failed.
My function prints recursively the entire tree of the schema definition,amazingly the output file crossed 820Mb for a definition file of 4 Mb(Aixm library) which in turn uses 50 Mb of schema definition library(ISO gml).
with that I am convinced I have to avoid Recursion and then start iteration and some other way of representing the output, but I am having little trouble converting all that recursion to iteration.
Set the buildToolsVersion '26.0.2'
then change classpath 'com.android.tools.build:gradle:3.0.1'
.
Make sure you set compileSdkVersion
to 26
whiles targetSdkVersion
is also set 26
.
It is also appropriate to sent set compile 'com.android.support:appcompat-v7:26.0.2'
.
In Python 3+, print
is a function. When you call
print('hello world')
Python translates it to
print('hello world', end='\n')
You can change end
to whatever you want.
print('hello world', end='')
print('hello world', end=' ')
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute()
it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
I found this problem in the book "Illustrated Guide to Python 3". It was in a very early chapter that only discussed the math operations, no loops, no comparisons, no conditionals. How can you tell if a given year is a leap year?
Below is what I came up with:
y = y % 400
a = y % 4
b = y % 100
c = y // 100
ly = (0**a) * ((1-(0**b)) + 0**c) # ly is not zero for leap years, else 0
The difference between link
and controller
comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.
From the docs:
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
Say you want to have two directives my-form
and my-text-input
and you want my-text-input
directive to appear only inside my-form
and nowhere else.
In that case, you will say while defining the directive my-text-input
that it requires a controller from the parent
DOM element using the require argument, like this: require: '^myForm'
. Now the controller from the parent element will be injected
into the link
function as the fourth argument, following $scope, element, attributes
. You can call functions on that controller and communicate with the parent directive.
Moreover, if such a controller is not found, an error will be raised.
There is no real need to use the link
function if one is defining the controller
since the $scope
is available on the controller
. Moreover, while defining both link
and controller
, one does need to be careful about the order of invocation of the two (controller
is executed before).
However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers
is usually done in the link
function while the API for children and $scope
manipulation is done in the controller
. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive
state and link
function will maintain the DOM
+ outside bindings).
I think this would do it...
def validIP(address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
if not 0 <= int(item) <= 255:
return False
return True
On the CREATE TABLE,
The AUTO_INCREMENT of abuse_id is set to 2. MySQL now thinks 1 already exists.
With the INSERT statement you are trying to insert abuse_id with record 1. Please set AUTO_INCREMENT on CREATE_TABLE to 1 and try again.
Otherwise set the abuse_id in the INSERT statement to 'NULL'.
How can i resolve this?
I see there are a lot of great answers, incredibly detailed and extensive. In my case, I always understand things better if I follow along the reasoning from almost scratch, step by step. I would recommend you check this link out and whenever you have similar doubts, search for any codelabs that address the issue.
https://developer.android.com/codelabs/kotlin-android-training-headers#0
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.
If you have more files in your folder, you can use the below piped command I found in unix stackexchange.
find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/
Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp
.
arr = np.array([1,2,3,4])
arr[-1] # last element
There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
You'll then have the image data in baos
, from which you can get a byte array by calling baos.toByteArray()
.
This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}
function stopTimer () {
timer.stop();
}
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;
function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}
function stopTimer () {
timer.stop;
}
Now you simply need to add a trigger for startTimer()
, such as onchange
.
One more approach would be to apply n() function which is counting the number of observations
library(dplyr)
library(magrittr)
data %>%
group_by(columnName) %>%
summarise(Count = n())
For varchars, you may need to do something like this:
select convert(varchar(25), NULL) as abc_column into xyz_table
If you try
select '' as abc_column into xyz_table
you may get errors related to truncation, or an issue with null values, once you populate.
Use the StringUtils class, it also includes null check
StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)
Simple:
let objCopy = JSON.parse(JSON.stringify(obj));
This Also Works (Only for Arrays)
let objCopy2 = obj.slice()
Ternjs is a new alternative for getting JS autocompletion. http://ternjs.net/
Sublime Plugin
The most well-maintained Tern plugin for Sublime Text is called 'tern_for_sublime'
There is also an older plugin called 'TernJS'. It is unmaintained and contains several performance related bugs, that cause Sublime Text to crash, so avoid that.
Grateful for the other answers which inspired but didn't work for me.
After spending hours trying to figure out how it works, I came up with the implementation below with the newest PyCryptodomex library (it is another story how I managed to set it up behind proxy, on Windows, in a virtualenv.. phew)
Working on your implementation, remember to write down padding, encoding, encrypting steps (and vice versa). You have to pack and unpack keeping in mind the order.
import base64 import hashlib from Cryptodome.Cipher import AES from Cryptodome.Random import get_random_bytes __key__ = hashlib.sha256(b'16-character key').digest() def encrypt(raw): BS = AES.block_size pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) raw = base64.b64encode(pad(raw).encode('utf8')) iv = get_random_bytes(AES.block_size) cipher = AES.new(key= __key__, mode= AES.MODE_CFB,iv= iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decrypt(enc): unpad = lambda s: s[:-ord(s[-1:])] enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(__key__, AES.MODE_CFB, iv) return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))
If you are using kotlin then the context will be already defined in the fragment. So just use that context. Try the following code to show a toast message.
Toast.makeText(context , "your_text", Toast.LENGTH_SHORT).show()
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
To avoid linter errors, I use it like this:
render() {
const props = {
dangerouslySetInnerHTML: { __html: '<br/>' },
};
return (
<div {...props}></div>
);
}
this will open the file with the default windows program (notepad if you haven't changed it);
Process.Start(@"c:\myfile.txt")
It's because there is no long
in javascript.
Minimal runnable example
For this to make sense, you have to understand the basics of paging: How does x86 paging work? and in particular that the OS can allocate virtual memory via page tables / its internal memory book keeping (VSZ virtual memory) before it actually has a backing storage on RAM or disk (RSS resident memory).
Now to observe this in action, let's create a program that:
mmap
main.c
#define _GNU_SOURCE
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
typedef struct {
unsigned long size,resident,share,text,lib,data,dt;
} ProcStatm;
/* https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c/7212248#7212248 */
void ProcStat_init(ProcStatm *result) {
const char* statm_path = "/proc/self/statm";
FILE *f = fopen(statm_path, "r");
if(!f) {
perror(statm_path);
abort();
}
if(7 != fscanf(
f,
"%lu %lu %lu %lu %lu %lu %lu",
&(result->size),
&(result->resident),
&(result->share),
&(result->text),
&(result->lib),
&(result->data),
&(result->dt)
)) {
perror(statm_path);
abort();
}
fclose(f);
}
int main(int argc, char **argv) {
ProcStatm proc_statm;
char *base, *p;
char system_cmd[1024];
long page_size;
size_t i, nbytes, print_interval, bytes_since_last_print;
int snprintf_return;
/* Decide how many ints to allocate. */
if (argc < 2) {
nbytes = 0x10000;
} else {
nbytes = strtoull(argv[1], NULL, 0);
}
if (argc < 3) {
print_interval = 0x1000;
} else {
print_interval = strtoull(argv[2], NULL, 0);
}
page_size = sysconf(_SC_PAGESIZE);
/* Allocate the memory. */
base = mmap(
NULL,
nbytes,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
-1,
0
);
if (base == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
/* Write to all the allocated pages. */
i = 0;
p = base;
bytes_since_last_print = 0;
/* Produce the ps command that lists only our VSZ and RSS. */
snprintf_return = snprintf(
system_cmd,
sizeof(system_cmd),
"ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == \"%ju\") print}'",
(uintmax_t)getpid()
);
assert(snprintf_return >= 0);
assert((size_t)snprintf_return < sizeof(system_cmd));
bytes_since_last_print = print_interval;
do {
/* Modify a byte in the page. */
*p = i;
p += page_size;
bytes_since_last_print += page_size;
/* Print process memory usage every print_interval bytes.
* We count memory using a few techniques from:
* https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c */
if (bytes_since_last_print > print_interval) {
bytes_since_last_print -= print_interval;
printf("extra_memory_committed %lu KiB\n", (i * page_size) / 1024);
ProcStat_init(&proc_statm);
/* Check /proc/self/statm */
printf(
"/proc/self/statm size resident %lu %lu KiB\n",
(proc_statm.size * page_size) / 1024,
(proc_statm.resident * page_size) / 1024
);
/* Check ps. */
puts(system_cmd);
system(system_cmd);
puts("");
}
i++;
} while (p < base + nbytes);
/* Cleanup. */
munmap(base, nbytes);
return EXIT_SUCCESS;
}
Compile and run:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
echo 1 | sudo tee /proc/sys/vm/overcommit_memory
sudo dmesg -c
./main.out 0x1000000000 0x200000000
echo $?
sudo dmesg
where:
echo 1 | sudo tee /proc/sys/vm/overcommit_memory
: required for Linux to allow us to make a mmap call larger than physical RAM: maximum memory which malloc can allocateProgram output:
extra_memory_committed 0 KiB
/proc/self/statm size resident 67111332 768 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
PID VSZ RSS
29827 67111332 1648
extra_memory_committed 8388608 KiB
/proc/self/statm size resident 67111332 8390244 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
PID VSZ RSS
29827 67111332 8390256
extra_memory_committed 16777216 KiB
/proc/self/statm size resident 67111332 16778852 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
PID VSZ RSS
29827 67111332 16778864
extra_memory_committed 25165824 KiB
/proc/self/statm size resident 67111332 25167460 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
PID VSZ RSS
29827 67111332 25167472
Killed
Exit status:
137
which by the 128 + signal number rule means we got signal number 9
, which man 7 signal
says is SIGKILL, which is sent by the Linux out-of-memory killer.
Output interpretation:
printf '0x%X\n' 0x40009A4 KiB ~= 64GiB
(ps
values are in KiB) after the mmap.extra_memory_committed 0
, which means we haven't yet touched any pages. RSS is a small 1648 KiB
which has been allocated for normal program startup like text area, globals, etc.8388608 KiB == 8GiB
worth of pages. As a result, RSS increased by exactly 8GIB to 8390256 KiB == 8388608 KiB + 1648 KiB
See also: https://unix.stackexchange.com/questions/35129/need-explanation-on-resident-set-size-virtual-size
OOM killer logs
Our dmesg
commands have shown the OOM killer logs.
An exact interpretation of those has been asked at:
The very first line of the log was:
[ 7283.479087] mongod invoked oom-killer: gfp_mask=0x6200ca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0
So we see that interestingly it was the MongoDB daemon that always runs in my laptop on the background that first triggered the OOM killer, presumably when the poor thing was trying to allocate some memory.
However, the OOM killer does not necessarily kill the one who awoke it.
After the invocation, the kernel prints a table or processes including the oom_score
:
[ 7283.479292] [ pid ] uid tgid total_vm rss pgtables_bytes swapents oom_score_adj name
[ 7283.479303] [ 496] 0 496 16126 6 172032 484 0 systemd-journal
[ 7283.479306] [ 505] 0 505 1309 0 45056 52 0 blkmapd
[ 7283.479309] [ 513] 0 513 19757 0 57344 55 0 lvmetad
[ 7283.479312] [ 516] 0 516 4681 1 61440 444 -1000 systemd-udevd
and further ahead we see that our own little main.out
actually got killed on the previous invocation:
[ 7283.479871] Out of memory: Kill process 15665 (main.out) score 865 or sacrifice child
[ 7283.479879] Killed process 15665 (main.out) total-vm:67111332kB, anon-rss:92kB, file-rss:4kB, shmem-rss:30080832kB
[ 7283.479951] oom_reaper: reaped process 15665 (main.out), now anon-rss:0kB, file-rss:0kB, shmem-rss:30080832kB
This log mentions the score 865
which that process had, presumably the highest (worst) OOM killer score as mentioned at: https://unix.stackexchange.com/questions/153585/how-does-the-oom-killer-decide-which-process-to-kill-first
Also interestingly, everything apparently happened so fast that before the freed memory was accounted, the oom
was awoken again by the DeadlineMonitor
process:
[ 7283.481043] DeadlineMonitor invoked oom-killer: gfp_mask=0x6200ca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0
and this time that killed some Chromium process, which is usually my computers normal memory hog:
[ 7283.481773] Out of memory: Kill process 11786 (chromium-browse) score 306 or sacrifice child
[ 7283.481833] Killed process 11786 (chromium-browse) total-vm:1813576kB, anon-rss:208804kB, file-rss:0kB, shmem-rss:8380kB
[ 7283.497847] oom_reaper: reaped process 11786 (chromium-browse), now anon-rss:0kB, file-rss:0kB, shmem-rss:8044kB
Tested in Ubuntu 19.04, Linux kernel 5.0.0.
The following tools can be useful during development:
Access Token Debugger: Paste in an access token for details
https://developers.facebook.com/tools/debug/accesstoken/
Graph API Explorer: Test requests to the graph api after pasting in your access token
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
Another possible way are namespaces:
#include <iostream>
namespace mySpace {
static const int T = 100;
}
using namespace std;
class T1
{
public:
T1()
{
cout << "T1 constructor: " << mySpace::T << endl;
}
};
The disadvantage is that other classes can also use the constants if they include the header file.
Another alternative is to set the root_path
which fixes the problem both for templates and static folders.
root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)
If you render templates directly via Jinja2
, then you write:
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
This happens when you update from Chrome 55 to Chrome 56 (56.0.2924.87).
This is an increase in security enforcement.
It doesn't go away by restarting the browser, and it's not a bug.
Mountain View says it's hoping you don't ever encounter the message, because Certificate Authorities are required to stop issuing SHA-1 certificates in 2016. Just in case, Google plans to continue issuing warnings until Chrome completely stops supporting SHA-1 on January 1st, 2017. When that day comes, a website that still uses the function will trigger a fatal network error. (Source: Engadget.com)
If this happens, the most-likely cause is that your (or the website's) SSL-certificate uses SHA1.
SHA1 is broken, and SSL certificates using SHA1 are not secure anymore (it's now been a long time that Chrome showed this to you - now it blocks NET::ERR_CERT_WEAK_SIGNATURE_ALGORITHM
).
Another likely cause is that your SSL-certificate expired
Also, you should disable backwards-compatiblity with SSL2 & SSL3 (Poodle Attack).
You should only be using TLS (SSL 3.1+).
To test your domain's SSL-certificate, you can use SSL labs SSL test.
To find out what exactly the issue is: Open the chrome developer console (CTRL + SHIFT + J OR F12) And change to the security tab
For more information:
https://support.google.com/chrome/answer/95617?visit_id=1-636221396724527190-3454695657&p=ui_security_indicator&rd=1
FYI:
SHA-1 has been growing weaker and more insecure everyday for a decade now, which is dangerous considering we tend to trust websites with "https://" in their URLs. Other browsers like Mozilla Firefox and Microsoft Edge also plan to stop supporting it in an effort to encourage website owners to switch to more secure SHA-2 certificates as soon as possible.
If you urgently need to get around it (you need to close all running instances of Chrome first - otherwise it won't work):
chrome --args --ignore-certificate-errors
Please note: don't go online-banking or gmail'ing with those command-line settings active in your Chrome instance.
It is a very simple and effective utility build in jquery to implement pagination on html table http://tablesorter.com/docs/example-pager.html
Download the plugin from http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js
After adding this plugin add following code in head script
$(document).ready(function() {
$("table")
.tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")});
});
Using jdk7-u221, I was need to install the Java Cryptography Extension (JCE)
This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.
$results = @()
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation
If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.
This is why I create a new object first.
Try the following:
write-output "test" | convertto-csv -NoTypeInformation
This will give you:
"Length"
"4"
If you use the Get-Member on Write-Output as follows:
write-output "test" | Get-Member -MemberType Property
You will see that it has one property - 'length':
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property System.Int32 Length {get;}
This is why Length will be written to the csv file.
Update: Appending a CSV Not the most efficient way if the file gets large...
$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
$results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path $csvFileName -NoTypeInformation
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
Highlight your block with: ShiftV
Comment the selected block out with: :norm i#
(lower case i)
To uncomment, highlight your block again, and uncomment with: :norm ^x
The :norm
command performs an action for every selected line. Commenting will insert a #
at the start of every line, and uncommenting will delete that #
.
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
Write Following Code to set padding, it may help you.
TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();
layoutparams.setPadding(50,50,50,50);
ApplyPaddingTextView.setLayoutParams(layoutparams);
Use LinearLayout.LayoutParams
or RelativeLayout.LayoutParams
according to parent layout of the child view
To expand on @Cradle 's answer: you could also write a multi-purpose function that will get you the same result per the OP's question:
Function Get-AbsolutePath {
[CmdletBinding()]
Param(
[parameter(
Mandatory=$false,
ValueFromPipeline=$true
)]
[String]$relativePath=".\"
)
if (Test-Path -Path $relativePath) {
return (Get-Item -Path $relativePath).FullName -replace "\\$", ""
} else {
Write-Error -Message "'$relativePath' is not a valid path" -ErrorId 1 -ErrorAction Stop
}
}
I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default]
? Replace by space:
Segmentation is more hierarchal and "pretty" but can be limiting.
For example, if you have a url with three segments, each one passing different parameters to search for a car via make, model and color:
www.example.com/search/honda/civic/blue
This is a very pretty url and more easily remembered by the end user, but now your kind of stuck with this structure. Say you want to make it so that in the search the user could search for ALL blue cars, or ALL Honda Civics? A query parameter solves this because it give a key value pair. So you could pass:
www.example.com/search?color=blue
www.example.com/search?make=civic
Now you have a way to reference the value via it's key - either "color" or "make" in your query code.
You could get around this by possibly using more segments to create a kind of key value structure like:
www.example.com/search/make/honda/model/civic/color/blue
Hope that makes sense..
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1();
- here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
Using Vim, it shouldn't be more involved than hitting Esc, and then typing...
:%s/\t/ /g
...on the file you want to change. That will convert all tabs to four spaces. If you have inconsistent spacing as well, then that will be more difficult.
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
In binary, 0xE9 looks like 1110 1001
. If you read about UTF-8 on Wikipedia, you’ll see that such a byte must be followed by two of the form 10xx xxxx
. So, for example:
>>> b'\xe9\x80\x80'.decode('utf-8')
u'\u9000'
But that’s just the mechanical cause of the exception. In this case, you have a string that is almost certainly encoded in latin 1. You can see how UTF-8 and latin 1 look different:
>>> u'\xe9'.encode('utf-8')
b'\xc3\xa9'
>>> u'\xe9'.encode('latin-1')
b'\xe9'
(Note, I'm using a mix of Python 2 and 3 representation here. The input is valid in any version of Python, but your Python interpreter is unlikely to actually show both unicode and byte strings in this way.)
Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:
window.onbeforeunload=function(e){
// only take action (iterate) if my SCHEDULED_REQUEST object contains data
for (var key in SCHEDULED_REQUEST){
postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
for (var i=0;i<1000;i++){
// do something unnoticable but time consuming like writing a lot to console
console.log('buying some time to finish saving data');
};
break;
};
}; // no return string --> user will leave as normal but data is send to server
Edit: See also Synchronous_AJAX and how to do that with jquery
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
You can not access the docker's IP from outside of that host machine.
If your browser is on another machine better to map the host port to container port by passing -p 8080:8080
to run command.
Passing -p
you can map host port to container port and a proxy is set to forward all traffix for said host port to designated container port.
This worked for me perfectly.
Add this class navbar-fixed-bottom to your footer.
<div class="footer navbar-fixed-bottom">
I used it like this:
<div class="container-fluid footer navbar-fixed-bottom">
<!-- start footer -->
</div>
And it sets to bottom over the the full width.
Edit: This will set footer to always visible, it's something you need to take in consideration.
here is code to get device country. Compatible with all versions of android even oreo.
Solution: if user does not have sim card than get country he is used during phone setup , or current language selection.
public static String getDeviceCountry(Context context) {
String deviceCountryCode = null;
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm != null) {
deviceCountryCode = tm.getNetworkCountryIso();
}
if (deviceCountryCode != null && deviceCountryCode.length() <=3) {
deviceCountryCode = deviceCountryCode.toUpperCase();
}
else {
deviceCountryCode = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getCountry().toUpperCase();
}
// Log.d("countryCode"," : " + deviceCountryCode );
return deviceCountryCode;
}
For jquery users, how about $.trim(s)
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
another solution will be to grab the text inside the title
tag & then use .html()
method of jQuery to construct the content of the tooltip.
$(function() {
$(document).tooltip({
position: {
using: function(position, feedback) {
$(this).css(position);
var txt = $(this).text();
$(this).html(txt);
$("<div>")
.addClass("arrow")
.addClass(feedback.vertical)
.addClass(feedback.horizontal)
.appendTo(this);
}
}
});
});
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
In the unit test
@Spy
on it@Mock
all of the other class/service/database (i.e. external dependencies) In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue
So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;
public class URLEncodeSample {
public static void main( String [] args ) throws Throwable {
System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
}
}
C:\oreyes\samples\java\URL>javac URLEncodeSample.java
C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
As expected.
What would be the problem with this?
Go to:
Settings -> Preferences You will see a dialog box. There click the Auto-completion tab where you can set the auto complete option.See image below:
If your code not detected automatically then you choose your coding language form Language menu
Available as standard in Java 7, path.copyTo: http://openjdk.java.net/projects/nio/javadoc/java/nio/file/Path.html http://java.sun.com/docs/books/tutorial/essential/io/copy.html
I can't believe it took them so long to standardise something so common and simple as file copying :(
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
Like as @folone, but correct
private static List<Date> getDatesBetween(final Date date1, final Date date2) {
List<Date> dates = new ArrayList<>();
Calendar c1 = new GregorianCalendar();
c1.setTime(date1);
Calendar c2 = new GregorianCalendar();
c2.setTime(date2);
int a = c1.get(Calendar.DATE);
int b = c2.get(Calendar.DATE);
while ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) || (c1.get(Calendar.DATE) != c2.get(Calendar.DATE))) {
c1.add(Calendar.DATE, 1);
dates.add(new Date(c1.getTimeInMillis()));
}
return dates;
}
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
Consider
var x = document.getElementById("age");
Here x
is the element with id="age"
.
Now look at the following line
var age = document.getElementById("age").value;
this means you are getting the value of the element which has id="age"
Many thanks to Dorian and Phrogz for reminding me about the array (and hash) method #replace, which can "replace the contents of an array or hash."
The notion that a CONSTANT's value can be changed, but with an annoying warning, is one of Ruby's few conceptual mis-steps -- these should either be fully immutable, or dump the constant idea altogether. From a coder's perspective, a constant is declarative and intentional, a signal to other that "this value is truly unchangeable once declared/assigned."
But sometimes an "obvious declaration" actually forecloses other, future useful opportunities. For example...
There are legitimate use cases where a "constant's" value might really need to be changed: for example, re-loading ARGV from a REPL-like prompt-loop, then rerunning ARGV thru more (subsequent) OptionParser.parse! calls -- voila! Gives "command line args" a whole new dynamic utility.
The practical problem is either with the presumptive assumption that "ARGV must be a constant", or in optparse's own initialize method, which hard-codes the assignment of ARGV to the instance var @default_argv for subsequent processing -- that array (ARGV) really should be a parameter, encouraging re-parse and re-use, where appropriate. Proper parameterization, with an appropriate default (say, ARGV) would avoid the need to ever change the "constant" ARGV. Just some 2¢-worth of thoughts...
This should work.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: green;
}
#container {
width: inherit;
height: inherit;
margin: 0;
padding: 0;
background-color: pink;
}
h1 {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container">
<h1>Hello World</h1>
</div>
</body>
</html>
The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.
The width: inherit; height: inherit;
pulls the width and height from the parent element. This should be the default and is not truly necessary.
Try removing the h1 { ... }
CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1
element is influencing the layout of its container. You could prevent this by declaring overflow: hidden;
on the container or the body.
I'd also suggest you do some reading on the CSS Box Model.
You must put a FrameLayout as Main view then put inside a RelativeLayout with ScrollView and at least your RecyclerView, it works for me.
The real trick here is the RelativeLayout...
Happy to help.
The default behavior of Commit PL/SQL block:
You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.
For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.
https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105
It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like:
class MyList(list):
def __getitem__(self, index):
if isinstance(index, tuple):
return [self[i] for i in index]
return super(MyList, self).__getitem__(index)
seq = MyList("foo bar baaz quux mumble".split())
print seq[0]
print seq[2,4]
print seq[1::2]
printing
foo
['baaz', 'mumble']
['bar', 'quux']
You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines: