BlobBuilder has long been deprecated by the Blob object. Compare the code in Dennis' answer — where BlobBuilder is used — with the code below:
function arrayBufferGen(str, cb) {
var b = new Blob([str]);
var f = new FileReader();
f.onload = function(e) {
cb(e.target.result);
}
f.readAsArrayBuffer(b);
}
Note how much cleaner and less bloated this is compared to the deprecated method... Yeah, this is definitely something to consider here.
There is only one reason when one needs to pass props
to super()
:
When you want to access this.props
in constructor.
Passing:
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props)
// -> { icon: 'home', … }
}
}
Not passing:
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props)
// -> undefined
// Props parameter is still available
console.log(props)
// -> { icon: 'home', … }
}
render() {
// No difference outside constructor
console.log(this.props)
// -> { icon: 'home', … }
}
}
Note that passing or not passing props
to super
has no effect on later uses of this.props
outside constructor
. That is render
, shouldComponentUpdate
, or event handlers always have access to it.
This is explicitly said in one Sophie Alpert's answer to a similar question.
The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:
Class components should always call the base constructor with
props
.
However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.
(Thanks @MattBrowne for the link)
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
If the git bash is not working properly due to recently changed password.
You could open the Git GUI, and clone from there. It will ask for password, once entered, you can close the GIT GUI window.
Now the git bash will work perfectly.
You can use any selector with not
p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
This is safer than using eval
. As its own docs say:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
For example:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
Easiest way: change the Windows Display Properties main window background color. I went to Appearance tab, changed to Silver scheme, clicked Advanced, clicked on "Active Window" and changed Color 1 to a light gray. All Eclipse views softened.
Since Luna (4.4) there seems to be a full Dark
them in
Window -> Preferences -> General -> Appearance -> Theme -> Dark
Use this, two<anything any number of times><end of line>
's/two.*$/BLAH/g'
You can try Wolfram Alpha as in this example based on your input:
Use Dock and Anchor properties. Here is a good article. Note that these will handle changes when maximizing/minimizing. That is a little different that if the screen resolution changes, but it will be along the same idea.
If WWW-Authenticate header is removed, then you wont get the caching of credentials and wont get back the Authorization header in request. That means now you will have to enter the credentials for every new request you generate.
If you don't want to remove/change dataType: json
, you can override jQuery's strict parsing by defining a custom converter
:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()
/success
will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
The problem is that simple console can't edit the registry. No need to edit the registry by hand, just launch the groovysh
once with administrative priveleges. All subsequent launches work without error.
Do it in 2 steps. First, create a dictionary.
>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...
Then, convert that dictionary into the expected format.
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]
It is also possible with itertools.groupby but it requires the input to be sorted first.
>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]
Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.
>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
... if k in res: res[k].append(v)
... else: res[k] = [v]
...
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]
You can have the @Transactional in the child class, but you have to override each of the methods and call the super method in order to get it to work.
Example:
@Transactional(readOnly = true)
public class Bob<SomeClass> {
@Override
public SomeClass getValue() {
return super.getValue();
}
}
This allows it to set it up for each of the methods it's needed for.
Send a Location
header to redirect. Keep in mind this only works before any other output is sent.
header('Location: index.php'); // redirect to index.php
Take a look at my answer Maven and dependent modules.
The Maven Reactor plugin is designed to deal with building part of a project.
The particular goal you'll want to use it reactor:make
.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
If you use a fullscreen transparent activity, there is no need to specify the orientation lock on the activity. It will take the configuration settings of the parent activity. So if the parent activity has in the manifest:
android:screenOrientation="portrait"
your translucent activity will have the same orientation lock: portrait.
You don't need to use a second repository - you can do commands like git checkout
and git commit
on a bare repository, if only you supply a dummy work directory using the --work-tree
option.
Prepare a dummy directory:
$ rm -rf /tmp/empty_directory
$ mkdir /tmp/empty_directory
Create the master
branch without a parent (works even on a completely empty repo):
$ cd your-bare-repository.git
$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master' <--- abort if "master" already exists
Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):
$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory
$ git branch
* master
Clean up the directory, it is still empty.
$ rmdir /tmp/empty_directory
Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.
As a lot of people have said, if you're looking for an actual 1 line if then:
if (Boolean_expression) do.something();
is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):
(Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();
ALSO:
var something = (Boolean_expression) ? trueValueHardware : falseATRON;
However, I saw one very cool example. Shouts to @Peter-Oslson for &&
(Boolean_expression) && do.something();
Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan
It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')
(Of course you will need to specify separator, header, etc. if they are different from the defaults.)
If you are using reactiveFormModule and have formGroup defined like this:
public exampleForm = new FormGroup({
name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});
than you are able to add a new validator (and keep old ones) to FormControl with this approach:
this.exampleForm.get('age').setValidators([
Validators.pattern('^[0-9]*$'),
this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
Validators.email,
this.exampleForm.get('email').validator
]);
FormControl.validator returns a compose validator containing all previously defined validators.
For all those whose issue was from the ajax call, here is a full example :
Ajax call : the key here is to use a dict
and then JSON.stringify
var dict = {username : "username" , password:"password"};
$.ajax({
type: "POST",
url: "http://127.0.0.1:5000/", //localhost Flask
data : JSON.stringify(dict),
contentType: "application/json",
});
And on server side :
from flask import Flask
from flask import request
import json
app = Flask(__name__)
@app.route("/", methods = ['POST'])
def hello():
print(request.get_json())
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
if __name__ == "__main__":
app.run()
The pop
method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}
, here) takes two arguments -- see the docs
The second argument, default
, is what pop
returns if the first argument, key
, is absent.
(If you call pop
with just one argument, key
, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'})
, this is irrelevant because 'a'
is a key in b.data
. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop
removes the 'a'
key, so in the second pop
the default
argument is actually returned (since 'a'
is now absent from b.data
).
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
});
}
}
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
A nice code for the push_back and emplace_back is shown here.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
You can see the move operation on push_back and not on emplace_back.
I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.
angular.module('myModule').service('browserDetectionService', function() {
return {
isCompatible: function () {
var browserInfo = navigator.userAgent;
var browserFlags = {};
browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;
browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here
browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;
return !browserFlags.ISOLD;
}
};
});
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
I believe that is just how the browser renders their standard input. If you set a border on the input:
<input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
<div style="width: 10px; border: solid 1px black; padding: 2px"> </div>
Then both are the same width, at least in FF.
As part of your jvm arguments you can set -Dlog4j.configuration=file:"<FILE_PATH>"
. Where FILE_PATH is the path of your log4j.properties file.
Please note that as of log4j2, the new system variable to use is log4j.configurationFile
and you put in the actual path to the file (i.e. without the file:
prefix) and it will automatically load the factory based on the extension of the configuration file:
-Dlog4j.configurationFile=/path/to/log4jconfig.{ext}
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
Something like this would work for reading:
String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try
{
input = new BufferedReader(new FileReader(filename));
String line = null;
while (( line = input.readLine()) != null)
{
String[] data = line.split(",");
csvData.add(Arrays.toList(data));
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if(input != null)
{
input.close();
}
}
In zsh you can use
=time ...
In bash or zsh you can use
command time ...
These (by different mechanisms) force an external command to be used.
As best I can tell, it is not possible to update the select2 options without refreshing the entire list or entering some search text and using a query function.
What are those buttons supposed to do? If they are used to determine the select options, why not put them outside of the select box, and have them programmatically set the select box data and then open it? I don't understand why you would want to put them on top of the search box. If the user is not supposed to search, you can use the minimumResultsForSearch option to hide the search feature.
Edit: How about this...
HTML:
<input type="hidden" id="select2" class="select" />
Javascript
var data = [{id: 0, text: "Zero"}],
select = $('#select2');
select.select2({
query: function(query) {
query.callback({results: data});
},
width: '150px'
});
console.log('Opening select2...');
select.select2('open');
setTimeout(function() {
console.log('Updating data...');
data = [{id: 1, text: 'One'}];
}, 1500);
setTimeout(function() {
console.log('Fake keyup-change...');
select.data().select2.search.trigger('keyup-change');
}, 3000);
Example: Plunker
Edit 2: That will at least get it to update the list, however there is still some weirdness if you have entered search text before triggering the keyup-change
event.
***LOGIN script that doesnt link to a database or external file. Good for a global password -
Place on Login form page - place this at the top of the login page - above everything else***
<?php
if(isset($_POST['Login'])){
if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");
}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>
*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *
<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){
header("Location: ./YourLoginPage.php");
}
?>
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
Try:
Use NOPASSWD
line for all commands, I mean:
jenkins ALL=(ALL) NOPASSWD: ALL
Put the line after all other lines in the sudoers
file.
That worked for me (Ubuntu 14.04).
The reason I like Rcpp so much is that I don't always get how R Core thinks, and with Rcpp, more often than not, I don't have to.
Speaking philosophically, you're in a state of sin with regards to the functional paradigm, which tries to ensure that every value appears independent of every other value; changing one value should never cause a visible change in another value, the way you get with pointers sharing representation in C.
The problems arise when functional programming signals the small craft to move out of the way, and the small craft replies "I'm a lighthouse". Making a long series of small changes to a large object which you want to process on in the meantime puts you square into lighthouse territory.
In the C++ STL, push_back()
is a way of life. It doesn't try to be functional, but it does try to accommodate common programming idioms efficiently.
With some cleverness behind the scenes, you can sometimes arrange to have one foot in each world. Snapshot based file systems are a good example (which evolved from concepts such as union mounts, which also ply both sides).
If R Core wanted to do this, underlying vector storage could function like a union mount. One reference to the vector storage might be valid for subscripts 1:N
, while another reference to the same storage is valid for subscripts 1:(N+1)
. There could be reserved storage not yet validly referenced by anything but convenient for a quick push_back()
. You don't violate the functional concept when appending outside the range that any existing reference considers valid.
Eventually appending rows incrementally, you run out of reserved storage. You'll need to create new copies of everything, with the storage multiplied by some increment. The STL implementations I've use tend to multiply storage by 2 when extending allocation. I thought I read in R Internals that there is a memory structure where the storage increments by 20%. Either way, growth operations occur with logarithmic frequency relative to the total number of elements appended. On an amortized basis, this is usually acceptable.
As tricks behind the scenes go, I've seen worse. Every time you push_back()
a new row onto the dataframe, a top level index structure would need to be copied. The new row could append onto shared representation without impacting any old functional values. I don't even think it would complicate the garbage collector much; since I'm not proposing push_front()
all references are prefix references to the front of the allocated vector storage.
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:
cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)
from typing import Dict, Any, Tuple
def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b
If you want to compare the dictionary values:
values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
See http://msdn.microsoft.com/en-us/library/ms187928.aspx
You can concatenate it:
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
i set my bind-address correctly as above but forgot to restart the mysql server (or reboot) :) face palm - so that's the source of this error for me!
The only difference in behaviour (not the intended usage) based on my limited research and testing so far (using Hive 1.1.0 -cdh5.12.0) seems to be that when a table is dropped
(NOTE: See Section 'Managed and External Tables' in https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL which list some other difference which I did not completely understand)
I believe Hive chooses the location where it needs to create the table based on the following precedence from top to bottom
When the "Location" option is not used during the "creation of a hive table", the above precedence rule is used. This is applicable for both Internal and External tables. This means an Internal table does not necessarily have to reside in the Warehouse directory and can reside anywhere else.
Note: I might have missed some scenarios, but based on my limited exploration, the behaviour of both Internal and Extenal table seems to be the same except for the one difference (data deletion) described above. I tried the following scenarios for both Internal and External tables.
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
Well, I got it. One way is to override the QWidget::closeEvent
(QCloseEvent *event)
method in your class definition and add your code into that function. Example:
class foo : public QMainWindow
{
Q_OBJECT
private:
void closeEvent(QCloseEvent *bar);
// ...
};
void foo::closeEvent(QCloseEvent *bar)
{
// Do something
bar->accept();
}
I was looking for a similar functionality some days back and came across a good tutorial on tutorialzine. Here is an working example. Complete tutorial can be found here.
Simple form to hold the file upload dialogue:
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadctl" multiple />
<ul id="fileList">
<!-- The file list will be shown here -->
</ul>
</form>
And here is the jQuery code to upload the files:
$('#upload').fileupload({
// This function is called when a file is added to the queue
add: function (e, data) {
//This area will contain file list and progress information.
var tpl = $('<li class="working">'+
'<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
'<p></p><span></span></li>' );
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
}
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
And here is the PHP code sample to process the data:
if($_POST) {
$allowed = array('jpg', 'jpeg');
if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){
$extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
echo '{"status":"success"}';
exit;
}
echo '{"status":"error"}';
}
exit();
}
The above code can be added to any existing form. This program automatically uploads images, once they are added. This functionality can be changed and you can submit the image, while you are submitting your existing form.
Updated my answer with actual code. All credits to original author of the code.
Source: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():
PS > $a.GetType().fullname
System.DayOfWeek
PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject
in Javascript.
var myObject = { "name" : "john" };
// { "name" : "john" };
myObject.gender = "male";
// { "name" : "john", "gender":"male"};
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
On Mac, use the command git credential-osxkeychain erase
.
OR remove manually from keychain from Applications ? Utilities ? Keychain Access. Then remove the github.com keychain. Then use push; it will ask for the keychain access; then deny.
It will ask for the new username and password, add it then pushes a file for that.
After git push
I found this error. Then I use the upper case-
issue:
remote: Permission to user1/file.git denied to user2(previously exist user ). fatal: unable to access 'https://github.com/xxxxxxxxxxxx/': The requested URL returned error: 403
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
In Python 3.2 a new html
module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function escape()
:
>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x > 2 && x < 7 single quote: ' double quote: "'
Point your JAVA_HOME
variable to C:\Program Files\Java\jdk1.8.0_xx\
where "xx" is the update number (make sure this matches your actual directory name). Do not include bin\javaw.exe
in the pathname.
NOTE: You can access the Environment Variables GUI from the CLI by entering rundll32 sysdm.cpl,EditEnvironmentVariables
. Be sure to put the 'JAVA_HOME' path variable in the System variables
rather than the user variables. If the path variable is in User
the Android Studio will not find the path.
Instead of including your js
file extension in index.html
, you can include it in .angular-cli-json
file.
These are the steps I followed to get this working:
js
file in assets/js
.angular-cli.json
- add the file path under scripts:
[../app/assets/js/test.js]
js
file.Declare at the top where you want to import the files as
declare const Test:any;
After this you can access its functions as for example Test.add()
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
Another way starting from c# 7.0 would be using local functions. You could name the local function with a meaningful name, and call it directly before declaring it (for clarity). Here is your example rewritten:
public void Method()
{
// Some code here
bool something = true, something2 = true;
DoSomething();
void DoSomething()
{
if (something)
{
//some code
if (something2)
{
// now I should break from ifs and go to te code outside ifs
return;
}
return;
}
}
// The code i want to go if the second if is true
// More code here
}
Install any UNIX interpreter for windows (Cygwin or Git Bash) and run the cmd:
find /path/to/directory -empty -type d
To find them
find /path/to/directory -empty -type d -delete
To delete them
(not really using the windows cmd prompt but it's easy and took few seconds to run)
an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it
Example:
abstract class twodshape
{
public abstract void area(); // no body in base class
}
class twodshape2 : twodshape
{
public virtual double area()
{
Console.WriteLine("AREA() may be or may not be override");
}
}
Additionally, you can change the keys view window -> preferences then type: 'keys' and when the key preference page opens you can type 'toggle block selection' and voila!
You can use dynamic variable names and let the variables names work like the keys of a hashmap.
For example, if you have an input file with two columns, name, credit, as the example bellow, and you want to sum the income of each user:
Mary 100
John 200
Mary 50
John 300
Paul 100
Paul 400
David 100
The command bellow will sum everything, using dynamic variables as keys, in the form of map_${person}:
while read -r person money; ((map_$person+=$money)); done < <(cat INCOME_REPORT.log)
To read the results:
set | grep map
The output will be:
map_David=100
map_John=500
map_Mary=150
map_Paul=500
Elaborating on these techniques, I'm developing on GitHub a function that works just like a HashMap Object, shell_map.
In order to create "HashMap instances" the shell_map function is able create copies of itself under different names. Each new function copy will have a different $FUNCNAME variable. $FUNCNAME then is used to create a namespace for each Map instance.
The map keys are global variables, in the form $FUNCNAME_DATA_$KEY, where $KEY is the key added to the Map. These variables are dynamic variables.
Bellow I'll put a simplified version of it so you can use as example.
#!/bin/bash
shell_map () {
local METHOD="$1"
case $METHOD in
new)
local NEW_MAP="$2"
# loads shell_map function declaration
test -n "$(declare -f shell_map)" || return
# declares in the Global Scope a copy of shell_map, under a new name.
eval "${_/shell_map/$2}"
;;
put)
local KEY="$2"
local VALUE="$3"
# declares a variable in the global scope
eval ${FUNCNAME}_DATA_${KEY}='$VALUE'
;;
get)
local KEY="$2"
local VALUE="${FUNCNAME}_DATA_${KEY}"
echo "${!VALUE}"
;;
keys)
declare | grep -Po "(?<=${FUNCNAME}_DATA_)\w+((?=\=))"
;;
name)
echo $FUNCNAME
;;
contains_key)
local KEY="$2"
compgen -v ${FUNCNAME}_DATA_${KEY} > /dev/null && return 0 || return 1
;;
clear_all)
while read var; do
unset $var
done < <(compgen -v ${FUNCNAME}_DATA_)
;;
remove)
local KEY="$2"
unset ${FUNCNAME}_DATA_${KEY}
;;
size)
compgen -v ${FUNCNAME}_DATA_${KEY} | wc -l
;;
*)
echo "unsupported operation '$1'."
return 1
;;
esac
}
Usage:
shell_map new credit
credit put Mary 100
credit put John 200
for customer in `credit keys`; do
value=`credit get $customer`
echo "customer $customer has $value"
done
credit contains_key "Mary" && echo "Mary has credit!"
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
Syntax:
$(selector).text()
returns the text content.
$(selector).text(content)
sets the text content.
$(selector).text(function(index, curContent))
sets text content using a function.
kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/
<form>
<label for="company">
<span>Company Name</span>
<input type="text" id="company" />
</label>
<label for="contact">
<span>Contact Name</span>
<input type="text" id="contact" />
</label>
</form>
label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }
Illustrated at http://jsfiddle.net/H3y8j/
$('textarea#message')
cannot be undefined (if by $
you mean jQuery of course).
$('textarea#message')
may be of length 0 and then $('textarea#message').val()
would be empty that's all
I came up with this function which works for me, hope this will help somebody
$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';
function checkStringAgainstList($str, $word_list)
{
$word_list = explode(', ', $word_list);
$str = explode(' ', $str);
foreach ($str as $word):
if (in_array(strtolower($word), $word_list)) {
return TRUE;
}
endforeach;
return false;
}
Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true
Try this. There shouldn't be any warning...
Activity thisActivity = getActivity();
if (thisActivity != null) {
startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
thisActivity.finish();
}
Why not keep track of the state of through a class without CSS rules on the clickable anchor itself
$(function() {
$("#show-background").click(function () {
$("#content-area").animate({opacity: 'toggle'}, 'slow');
$("#show-background").toggleClass("clicked");
if ( $("#show-background").hasClass("clicked") ) {
$(this).text("Show Text");
}
else {
$(this).text("Show Background");
}
});
});
You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.
public class MySingleton {
private static final MySingleton instance;
static {
instance = new MySingleton();
}
private MySingleton() {
}
public static MySingleton getInstance() {
return instance;
}
}
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.
The most reliable, simplest answer is:
body {_x000D_
/* for demo */_x000D_
background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
/* anything or nothing, it doesn't matter */_x000D_
width: 60%;_x000D_
/* only need if other rulesets give this padding */_x000D_
padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
height: 0;_x000D_
/* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
padding: 0 0 56.25%;_x000D_
position: relative;_x000D_
/* only need next 2 rules if other rulesets change these */_x000D_
margin: 0;_x000D_
width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
/* for demo */_x000D_
border: 0;_x000D_
background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
<div class="fixed-aspect-padder">_x000D_
<iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
</div>_x000D_
</div>
_x000D_
I settled for the limitation (to some people a benefit) of having my rows only one line of text high. The CSS to contain long strings then becomes:
.datatable td {
overflow: hidden; /* this is what fixes the expansion */
text-overflow: ellipsis; /* not supported in all browsers, but I accepted the tradeoff */
white-space: nowrap;
}
[edit to add:] After using my own code and initially failing, I recognized a second requirement that might help people. The table itself needs to have a fixed layout or the cells will just keep trying to expand to accomodate contents no matter what. If DataTables styles or your own styles don't already do so, you need to set it:
table.someTableClass {
table-layout: fixed
}
Now that text is truncated with ellipses, to actually "see" the text that is potentially hidden you can implement a tooltip plugin or a details button or something. But a quick and dirty solution is to use JavaScript to set each cell's title to be identical to its contents. I used jQuery, but you don't have to:
$('.datatable tbody td').each(function(index){
$this = $(this);
var titleVal = $this.text();
if (typeof titleVal === "string" && titleVal !== '') {
$this.attr('title', titleVal);
}
});
DataTables also provides callbacks at the row and cell rendering levels, so you could provide logic to set the titles at that point instead of with a jQuery.each
iterator. But if you have other listeners that modify cell text, you might just be better off hitting them with the jQuery.each
at the end.
This entire truncation method will ALSO have a limitation you've indicated you're not a fan of: by default columns will have the same width. I identify columns that are going to be consistently wide or consistently narrow, and explicitly set a percentage-based width on them (you could do it in your markup or with sWidth). Any columns without an explicit width get even distribution of the remaining space.
That might seem like a lot of compromises, but the end result was worth it for me.
Note a similar error such as:
standard_init_linux.go:211: exec user process caused "no such file or directory"
can happen if the architecture an image was built for does not match the one of your system. For instance, trying to run an image built for arm64
on a x86_64
machine can generate this error.
In any situation, if you have to bind a value with a checkbox which is not boolean then you can try the below options
In the Html file:
<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'"
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>
in the componentischeckedWithOutBoolean: any = 'Y';
See in the stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html
Adding following to ansible config worked while using ansible ad-hoc commands:
[ssh_connection]
# ssh arguments to use
ssh_args = -o StrictHostKeyChecking=no
Ansible Version
ansible 2.1.6.0
config file = /etc/ansible/ansible.cfg
Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
From the docs:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
Also:
Lexicographical ordering for strings uses the Unicode code point number to order individual characters.
or on Python 2:
Lexicographical ordering for strings uses the ASCII ordering for individual characters.
As an example:
>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)
The result False
is returned as soon as a
is found to be less than b
. The further items are not compared (as you can see for the second items: b
> a
is True
).
Be aware of lower and uppercase:
>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]
Give a try to .bringToFront()
:
http://developer.android.com/reference/android/view/View.html#bringToFront%28%29
Wrap it in double quotes
alter user "dell-sys" with password 'Pass@133';
Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys"
then you will have to issue exact the same whenever you refer to that user.
I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
you can simply do like this -
public void FullScreen() {
if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
final View v = this.activity.getWindow().getDecorView();
v.setSystemUiVisibility(8);
}
else if (Build.VERSION.SDK_INT >= 19) {
final View decorView = this.activity.getWindow().getDecorView();
final int uiOptions = 4102;
decorView.setSystemUiVisibility(uiOptions);
}
}
Basically, you can't. At least not in a reliable way. However, you shouldn't need to.
To restart a Java program, you need to restart the JVM. To restart the JVM you need to
Locate the java
launcher that was used. You may try with System.getProperty("java.home")
but there's no guarantee that this will actually point to the launcher that was used to launch your application. (The value returned may not point to the JRE used to launch the application or it could have been overridden by -Djava.home
.)
You would presumably want to honor the original memory settings etc (-Xmx
, -Xms
, …) so you need to figure out which settings where used to start the first JVM. You could try using ManagementFactory.getRuntimeMXBean().getInputArguments()
but there's no guarantee that this will reflect the settings used. This is even spelled out in the documentation of that method:
Typically, not all command-line options to the 'java' command are passed to the Java virtual machine. Thus, the returned input arguments may not include all command-line options.
If your program reads input from Standard.in
the original stdin will be lost in the restart.
Lots of these tricks and hacks will fail in the presence of a SecurityManager
.
I recommend you to design your application so that it is easy to clean every thing up and after that create a new instance of your "main" class.
Many applications are designed to do nothing but create an instance in the main-method:
public class MainClass {
...
public static void main(String[] args) {
new MainClass().launch();
}
...
}
By using this pattern, it should be easy enough to do something like:
public class MainClass {
...
public static void main(String[] args) {
boolean restart;
do {
restart = new MainClass().launch();
} while (restart);
}
...
}
and let launch()
return true if and only if the application was shut down in a way that it needs to be restarted.
There are more ways to kill a dog than hanging. [1]
awk '{key=$0; getline; print key ", " $0;}'
Put whatever delimiter you like inside the quotes.
References:
Run this command:
react-native run-android --variant=release
Note that
--variant=release
is only available if you've set up signing withcd android && ./gradlew assembleRelease
.
Here is an elegant library that records video in all supported browsers and supports uploading:
Following query will give you the exact table names of the database having field name like '%myName'.
SELECT distinct(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myName%'
Give another go at force removing the brewed version of git
brew uninstall --force git
Then cleanup any older versions and clear the brew cache
brew cleanup -s git
Remove any dead symlinks
brew cleanup --prune-prefix
Then try reinstalling git
brew install git
If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix
directory (/usr/local
by default), you can simply rm -rf $(brew --prefix)
. Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh
I suggest using concat()
if you are using nodeJS. In all other cases, I have found that slice(0)
works fine.
Try this:
jQuery('#main').css('opacity', '0.6');
or
jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});
if you want to support IE7, IE8 and so on.
Flushing the Session gets the data that is currently in the session synchronized with what is in the database.
More on the Hibernate website:
flush()
is useful, because there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed - except you use flush()
.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.
eg:
import java.util.LinkedList;
public class ForEachDemonstrater {
public static void main(String args[]) {
LinkedList<Character> pl = new LinkedList<Character>();
pl.add('j');
pl.add('a');
pl.add('v');
pl.add('a');
for (char s : pl)
System.out.print(s+"->");
}
}
<div ng-bind-html="myText"></div>
No need to put into html {{}} interpolation tags like you did {{myText}}.
and don't forget to use ngSanitize in module like e.g.
var app = angular.module("myApp", ['ngSanitize']);
and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize
Try this:
System.Reflection.Assembly.GetExecutingAssembly()
This returns you a System.Reflection.Assembly
instance that has all the data you could ever want to know about the current application. I think that the Location
property might get what you are after specifically.
The body-parser
module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
For multipart, you'd need to use something like connect-busboy
or multer
or connect-multiparty
(multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed
. It comes with an Express middleware and can also be used separately.
You need to configre this parameter by running the following in the administrative command prompt:
netsh http add iplisten ipaddress=::
Easiest way to check if a row exists:
$lectureName = mysql_real_escape_string($lectureName); // SECURITY!
$result = mysql_query("SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if (mysql_fetch_row($result)) {
return 'Assigned';
} else {
return 'Available';
}
No need to mess with arrays and field names.
I have worked with a factory integrated with google maps autocomplete and promises made??, I hope you serve.
http://jsfiddle.net/the_pianist2/vL9nkfe3/1/
you only need to replace the autocompleteService by this request with $ http incuida being before the factory.
app.factory('Autocomplete', function($q, $http) {
and $ http request with
var deferred = $q.defer();
$http.get('urlExample').
success(function(data, status, headers, config) {
deferred.resolve(data);
}).
error(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
<div ng-app="myApp">
<div ng-controller="myController">
<input type="text" ng-model="search"></input>
<div class="bs-example">
<table class="table" >
<thead>
<tr>
<th>#</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="direction in directions">
<td>{{$index}}</td>
<td>{{direction.description}}</td>
</tr>
</tbody>
</table>
</div>
'use strict';
var app = angular.module('myApp', []);
app.factory('Autocomplete', function($q) {
var get = function(search) {
var deferred = $q.defer();
var autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
input: search,
types: ['geocode'],
componentRestrictions: {
country: 'ES'
}
}, function(predictions, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
deferred.resolve(predictions);
} else {
deferred.reject(status);
}
});
return deferred.promise;
};
return {
get: get
};
});
app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
var promesa = Autocomplete.get(newValue);
promesa.then(function(value) {
$scope.directions = value;
}, function(reason) {
$scope.error = reason;
});
});
});
the question itself is to be made on:
deferred.resolve(varResult);
when you have done well and the request:
deferred.reject(error);
when there is an error, and then:
return deferred.promise;
select * from table where column_date > now()- INTERVAL '6 hours';
For my case, I didn't have htdocs
folder in xampp folder. It seems that it requires htdocs
folder to run so you can create an empty htdocs
folder in the xampp
folder.
Suppose you have df
with columns A
B
C
.
The most simple way is:
df = df.reindex(['B','C','A'], axis=1)
I have executed the code in my machine its working for IE and FF also.
function closeSelf(){
// do something
if(condition satisfied){
alert("conditions satisfied, submiting the form.");
document.forms['certform'].submit();
window.close();
}else{
alert("conditions not satisfied, returning to form");
}
}
<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
// change the submit button to normal button
<div><input type="button" value="Upload" onclick="closeSelf();"/></div>
</form>
After doing extensive research on all the options around "enumerations" in Scala, I posted a much more complete overview of this domain on another StackOverflow thread. It includes a solution to the "sealed trait + case object" pattern where I have solved the JVM class/object initialization ordering problem.
If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.
See Option 2 – Hosting Windows PowerShell yourself
First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
Then use the following code:
using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
namespace PSHostCLRv4
{
class Program
{
static int Main(string[] args)
{
var config = RunspaceConfiguration.Create();
return ConsoleShell.Start(
config,
"Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
"",
args
);
}
}
}
Try the above which will run with any list type.
public DataTable ListToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
1.Create AlertDialog set message,title and Positive,Negative Button:
final AlertDialog alertDialog = new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Confirmation")
.setMessage("Do you want to remove this Picture?")
.setPositiveButton("Yes",null)
.setNegativeButton("No",null)
.create();
2.Now find both buttons on DialogInterface Click then setOnClickListener():
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button yesButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_POSITIVE);
Button noButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
yesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Now Background Class To Update Operator State
alertDialog.dismiss();
Toast.makeText(GroundEditActivity.this, "Click on Yes", Toast.LENGTH_SHORT).show();
//Do Something here
}
});
noButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
Toast.makeText(GroundEditActivity.this, "Click on No", Toast.LENGTH_SHORT).show();
//Do Some Thing Here
}
});
}
});
3.To Show Alertdialog:
alertDialog.show();
Note: Don't forget Final Keyword with AlertDialog.
SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.
The keyboard height depends on the model, the QuickType bar, user settings... The best approach is calculate dinamically:
Swift 3.0
var heightKeyboard : CGFloat?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}
func keyboardShown(notification: NSNotification) {
if let infoKey = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
let rawFrame = (infoKey as AnyObject).cgRectValue {
let keyboardFrame = view.convert(rawFrame, from: nil)
self.heightKeyboard = keyboardFrame.size.height
// Now is stored in your heightKeyboard variable
}
}
As it is already explained in other answers, const
in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum
as a real constant in C:
enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};
Probably a maximized Form helps, or you can do this manually upon form load:
Code Block
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.
Hope this helps,
IO manipulators are what you need. setw, in particular. Here's an example from the reference page:
// setw example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw (10);
cout << 77 << endl;
return 0;
}
Justifying the field to the left and right is done with the left
and right
manipulators.
Also take a look at setfill. Here's a more complete tutorial on formatting C++ output with io manipulators.
Use the HTML5 "download" attribute
<a href="iphone_user_guide.pdf" download="iPhone User's Guide.PDF">click me</a>
Warning: as of this writing, does not work in IE/Safari, see: caniuse.com/#search=download
Edit: If you're looking for an actual javascript solution please see lajarre's answer
The simplest way to install setuptools when it isn't already there and you can't use a package manager is to download ez_setup.py and run it with the appropriate Python interpreter. This works even if you have multiple versions of Python around: just run ez_setup.py once with each Python.
Edit: note that recent versions of Python 3 include setuptools in the distribution so you no longer need to install separately. The script mentioned here is only relevant for old versions of Python.
In my case, I had replaced math library files from a previous Game Engine Graphics course with GLM. The problem was that I didn't add them to the project within Visual Studio's Solution Explorer (even though they were in the project repository).
Use strcmp()
to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char*
to a char*
using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp()
will iterate through both strings, checking their bytes to see if they are equal. strcmp()
will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
Since this is a login div, shouldn't the default be to NOT display it. I am going to go ahead and assume then you want to display it then via javascript.
<div id="login" style="display:none;">Content</div>
Then using jQuery:
<script type="javascript">$('#login').show();</script>
Another method you might consider is something like this:
<div id="login" style="display:<%=SetDisplay() %>">Content</div>
And the SetDisplay() method output "none" or "block"
sleep
already returns 0
. As such, I'm using:
while sleep 3 ; do ls -l ; done
This is a tiny bit shorter than mikhail's solution. A minor drawback is that it sleeps before running the target command for the first time.
Here's a slightly more flexible approach using the match
method. With this, you can extract more than one string:
s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)
# Use 'captures' to get an array of the captures
matchdata.captures # ["ants","pants"]
# Or use raw indices
matchdata[0] # whole regex match: "<ants> <pants>"
matchdata[1] # first capture: "ants"
matchdata[2] # second capture: "pants"
We can use Carbon
$time = '09:15 PM';
$s=Carbon::parse($time);
echo $military_time =$s->format('G:i');
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
I made a library called manual-promise
that functions as a drop in replacement for Promise
. None of the other answers here will work as drop in replacements for Promise
, as they use proxies or wrappers.
yarn add manual-promise
npn install manual-promise
import { ManualPromise } from "manual-promise";
const prom = new ManualPromise();
prom.resolve(2);
// actions can still be run inside the promise
const prom2 = new ManualPromise((resolve, reject) => {
// ... code
});
new ManualPromise() instanceof Promise === true
mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// do something, e.g. set your TextView here via .setText()
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
}
return false;
}
});
and in xml
android:imeOptions="actionDone"
A soft git reset will put committed changes back into your index. Next, checkout the branch you had intended to commit on. Then git commit with a new commit message.
git reset --soft <commit>
git checkout <branch>
git commit -m "Commit message goes here"
From git docs:
git reset [<mode>] [<commit>]
This form resets the current branch head to and possibly updates the index (resetting it to the tree of ) and the working tree depending on . If is omitted, defaults to --mixed. The must be one of the following:
--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
I follow the PEP8, it is a great piece of coding style.
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
I wonder if it might be worth using PHP (or another server-side scripting language) or Javascript to truncate the strings to the right length (although calculating the right length is tricky, unless you use a fixed-width font)?
Two options:
Install Oracle client on the PC you want to run your program on
Use Oracle.ManagedDataAccess.dll
You can get it on NuGet (search 'oracle managed') or download ODP.NET_Managed.zip (link is to a beta version, but points you in the right direction)
I use this so that the computers I deploy onto don't need Oracle client installed.
N.B. in my opinion this is good for console apps but annoying if you intend to install your application, so I install the client in that case.
My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..
A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:
public class Variables {
List<Object> listVariable; // declared but not assigned
final int aFinalVariableExample = 5; // declared, assigned and said to be final!
Integer foo(List<Object> someOtherObjectListVariable) {
// declare..
Object iAmAlsoAVariable;
// assign a value..
iAmAlsoAVariable = 5;
// change its value..
iAmAlsoAVariable = 8;
someOtherObjectListVariable.add(iAmAlsoAVariable);
return new Integer();
}
}
So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:
A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.
A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.
I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
you can write in your console:
git pull origin
then press TAB and write your "master" repository
Your question "what are they" is already answered above.
As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:
_isnan(), _isfinite(), and _fpclass()
On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
More "gentle" mode from the documentation:
docker run -dit --restart unless-stopped <image_name>
You could make use of expect (man expect comes with examples).
function sequentialSizes(val) {
var answer = "";
switch (val){
case 1:
case 2:
case 3:
case 4:
answer="Less than five";
break;
case 5:
case 6:
case 7:
case 8:
answer="less than 9";
break;
case 8:
case 10:
case 11:
answer="More than 10";
break;
}
return answer;
}
// Change this value to test you code to confirm ;)
sequentialSizes(1);
you can use position(text in text) in order by for ordering the sequence
I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:
foreach(object element in listbox.SelectedItems) {
DataRowView row = (DataRowView)element;
MessageBox.Show(row[0]);
}
____________________________________________________________________
| highest precedence <---------> lowest precedence
*———————————————+———————————————+———————————+———————————————+———————
\ xCanBeSeenBy | this | any class | this subclass | any
\__________ | class | in same | in another | class
\ | nonsubbed | package | package |
Modifier of x \ | | | |
————————————————*———————————————+———————————+———————————————+———————
public | ? | ? | ? | ?
————————————————+———————————————+———————————+———————————————+———————
protected | ? | ? | ? | ?
————————————————+———————————————+———————————+———————————————+———————
package-private | | | |
(no modifier) | ? | ? | ? | ?
————————————————+———————————————+———————————+———————————————+———————
private | ? | ? | ? | ?
____________________________________________________________________
You can replace nan
with None
in your numpy array:
>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>
In case anyone was a tired and silly as I was the other night whereupon I came across many threads espousing the different methods to get a javascript redirect, all of which were failing...
You can't use window.location.replace
or document.location.href
or any of your favourite vanilla javascript methods to redirect a page to itself.
So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:
if(window.location.href == linkout)
{
location.reload();
}
else
{
window.location.href = linkout;
}
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
This is because require()
does not exist in the browser/client-side JavaScript.
Now you're going to have to make some choices about your client-side JavaScript script management.
You have three options:
<script>
tag.CommonJS client side-implementations include (most of them require a build step before you deploy):
You can read more about my comparison of Browserify vs (deprecated) Component.
AMD implementations include:
Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.
Use FindIndex
and lambda to find and replace your values:
int j = listofelements.FindIndex(i => i.Contains(valueFieldValue.ToString())); //Finds the item index
lstString[j] = lstString[j].Replace(valueFieldValue.ToString(), value.ToString()); //Replaces the item by new value
If you learn how to use virtualenv (which is pretty dead-simple), you will have less of these issues. You'll just source the virtualenv and then you will be using local (to the project) packages.
It solves a lot of headache for me with paths, versions, etc.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
Update: See the top-voted answer please.
My own is currently obsolete. Only kept here for historical reasons.
Distinct in HQL is usually needed in Joins and not in simple examples like your own.
In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
You should disable Power Save Mode
For me I clicked over this button
then disable Power Save Mode
You can use the text
method and pass a function that returns the modified text, using the native String.prototype.replace
method to perform the replacement:
?$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});?????
Here's a working example.
There is a really informative article in the actual Oracle Java magazine about using Docker in combination with Vagrant (and Puppet):
Conclusion
Docker’s lightweight containers are faster compared with classic VMs and have become popular among developers and as part of CD and DevOps initiatives. If your purpose is isolation, Docker is an excellent choice. Vagrant is a VM manager that enables you to script configurations of individual VMs as well as do the provisioning. However, it is sill a VM dependent on VirtualBox (or another VM manager) with relatively large overhead. It requires you to have a hard drive idle that can be huge, it takes a lot of RAM, and performance can be suboptimal. Docker uses kernel cgroups and namespace isolation via LXC. This means that you are using the same kernel as the host and the same ile system. Vagrant is a level above Docker in terms of abstraction, so they are not really comparable. Configuration management tools such as Puppet are widely used for provisioning target environments. Reusing existing Puppet-based solutions is easy with Docker. You can also slice your solution, so the infrastructure is provisioned with Puppet; the middleware, the business application itself, or both are provisioned with Docker; and Docker is wrapped by Vagrant. With this range of tools, you can do what’s best for your scenario.
How to build, use and orchestrate Docker containers in DevOps http://www.javamagazine.mozaicreader.com/JulyAug2015#&pageSet=34&page=0
You can use the Media Library Folders plugin. It allows you to create folders, move or copy images to a folder and even includes a sync function to bulk add images uploaded by FTP to the server to the Wordpress media library.
There are problems with all the above approaches. At Google i/o Reto Meier released a robust answer to how to approach this which should meet most developers needs to track users across installations.
This approach will give you an anonymous, secure user ID which will be persistent for the user across different devices (including tablets, based on primary Google account) and across installs on the same device. The basic approach is to generate a random user ID and to store this in the apps shared preferences. You then use Google's backup agent to store the shared preferences linked to the Google account in the cloud.
Lets go through the full approach. First we need to create a backup for our SharedPreferences using the Android Backup Service. Start by registering your app via this link: http://developer.android.com/google/backup/signup.html
Google will give you a backup service key which you need to add to the manifest. You also need to tell the application to use the BackupAgent as follows:
<application android:label="MyApplication"
android:backupAgent="MyBackupAgent">
...
<meta-data android:name="com.google.android.backup.api_key"
android:value="your_backup_service_key" />
</application>
Then you need to create the backup agent and tell it to use the helper agent for sharedpreferences:
public class MyBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "user_preferences";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
To complete the backup you need to create an instance of BackupManager in your main Activity:
BackupManager backupManager = new BackupManager(context);
Finally create a user ID, if it doesn't already exist, and store it in the SharedPreferences:
public static String getUserID(Context context) {
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(
MyBackupAgent.PREFS, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
//backup the changes
BackupManager mBackupManager = new BackupManager(context);
mBackupManager.dataChanged();
}
}
return uniqueID;
}
This User_ID will now be persistent across installations, even if the user switches devices.
For more information on this approach see Reto's talk here http://www.google.com/events/io/2011/sessions/android-protips-advanced-topics-for-expert-android-app-developers.html
And for full details of how to implement the backup agent see the developer site here: http://developer.android.com/guide/topics/data/backup.html I particularly recommend the section at the bottom on testing as the backup does not happen instantaneously and so to test you have to force the backup.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
It means that trackDAO
should not be serialized.
you can set it in .bashrc
PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;
You can use
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"
These are attached property of wpf. For more information
http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html
In my case it was just caused because there was not enough space on the disk for cvtres.exe
to write the files it had to.
The error was preceded by this line
CVTRES : fatal error CVT1106: cannot write to file
The kind of array definition seems the key: In my case it is a one dimension array of 17 items which have to convert to a two dimension array
Defintion for columns: object[,] Array = new object[17, 1];
Defintion for rows object[,] Array= new object[1,17];
The code for value2 is in both cases the same Excel.Range cell = activeWorksheet.get_Range(Range); cell.Value2 = Array;
LG Georg
For angular material you should use fontSet input to change the font family:
<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />
<mat-icon>edit</mat-icon>
<mat-icon fontSet="material-icons-outlined">edit</mat-icon>
<mat-icon fontSet="material-icons-two-tone">edit</mat-icon>
...
this solution from here worked for me:
This is a Windows specific answer, so I'm aware that it's not relevant to you... I'm just including it for the benefit of future searchers.
In my case, it was because I was running Git from a non-elevated command line. "Run as Administrator" fixed it for me.
Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.
can't you just subset the columns in either df first?
[i for i in df.columns if i not in df2.columns]
dfNew = merge(df **[i for i in df.columns if i not in df2.columns]**, df2, left_index=True, right_index=True, how='outer')
I actually tried to implement connection pooling on the django end using:
https://github.com/gmcguire/django-db-pool
but I still received this error, despite lowering the number of connections available to below the standard development DB quota of 20 open connections.
There is an article here about how to move your postgresql database to the free/cheap tier of Amazon RDS. This would allow you to set max_connections
higher. This will also allow you to pool connections at the database level using PGBouncer.
https://www.lewagon.com/blog/how-to-migrate-heroku-postgres-database-to-amazon-rds
UPDATE:
Heroku responded to my open ticket and stated that my database was improperly load balanced in their network. They said that improvements to their system should prevent similar problems in the future. Nonetheless, support manually relocated my database and performance is noticeably improved.
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
Incase you're running some command with sudo, it won't allow it. Sudo needs a tty.
You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:
Why do I need to write
"$foo"
? What happens without the quotes?
$foo
does not mean “take the value of the variablefoo
”. It means something much more complex:
- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar ?
then the result of this step is the 3-element listfoo
,*
,bar
.- Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo
, following by the list of files in the current directory, and finallybar
. If the current directory is empty, the result isfoo
,*
,bar
.Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"
to expand to the list of positional parameters, e.g."$@"
is equivalent to"$1" "$2" "$3"
if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)
or with`foo`
. On a side note, don't use`foo`
: its quoting rules are weird and non-portable, and all modern shells support$(foo)
which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFS
doesn't contain digits or-
).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.
setVertical* helped to make vertical scrollbar always visible programmatically
scrollView.setScrollbarFadingEnabled(false);
scrollView.setVerticalScrollBarEnabled(true);
scrollView.setVerticalFadingEdgeEnabled(false);
A simple way to think about it is using even plainer English
If Bool1 And Bool2 Then
If [both are true] Then
If Bool1 AndAlso Bool2 Then
If [first is true then evaluate the second] Then
static_cast
is the first cast you should attempt to use. It does things like implicit conversions between types (such as int
to float
, or pointer to void*
), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating static_cast
isn't necessary, but it's important to note that the T(something)
syntax is equivalent to (T)something
and should be avoided (more on that later). A T(something, something_else)
is safe, however, and guaranteed to call the constructor.
static_cast
can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through virtual
inheritance. It does not do checking, however, and it is undefined behavior to static_cast
down a hierarchy to a type that isn't actually the type of the object.
const_cast
can be used to remove or add const
to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast
). It is important to note that modifying a formerly const
value is only undefined if the original variable is const
; if you use it to take the const
off a reference to something that wasn't declared with const
, it is safe. This can be useful when overloading member functions based on const
, for instance. It can also be used to add const
to an object, such as to call a member function overload.
const_cast
also works similarly on volatile
, though that's less common.
dynamic_cast
is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast
will seek out the desired object and return it if possible. If it can't, it will return nullptr
in the case of a pointer, or throw std::bad_cast
in the case of a reference.
dynamic_cast
has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using virtual
inheritance. It also can only go through public inheritance - it will always fail to travel through protected
or private
inheritance. This is rarely an issue, however, as such forms of inheritance are rare.
reinterpret_cast
is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int
, or all sorts of other nasty things. Largely, the only guarantee you get with reinterpret_cast
is that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast
cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.
C-style cast and function-style cast are casts using (type)object
or type(object)
, respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:
const_cast
static_cast
(though ignoring access restrictions)static_cast
(see above), then const_cast
reinterpret_cast
reinterpret_cast
, then const_cast
It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a reinterpret_cast
, and the latter should be preferred when explicit casting is needed, unless you are sure static_cast
will succeed or reinterpret_cast
will fail. Even then, consider the longer, more explicit option.
C-style casts also ignore access control when performing a static_cast
, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.
It's very simple.
Create a new empty repository in GitHub (without readme or license, you can add them later) and the following screen will show.
In the import code option, paste your Bitbucket repo's URL and voilà!!
Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.
astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')
which results in
[1] "Abcdeacoauu"
You can also use below code
$request->request->set(key, value).
Fits better for me.
The easiest thing is if you can make the WPF bitmap from a file directly.
Otherwise you will have to use System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap.
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
A shorter solution (which doesn't force you to repeat the vector name 4 times) would be to use Boost:
#include <boost/range/algorithm_ext/erase.hpp>
// ...
boost::remove_erase(vec, int_to_remove);
Option Explicit
Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook
TitleId = 4
Resultid = 0
Dim FileName1, FileName2 As String
Dim Difference As Long
'TestPassCount = 0
'TestFailCount = 0
'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count
If (TestDataRowCount <= 2) Then
MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
For RecordId = 3 To TestDataRowCount
RefreshResultSheet
'Source File row count
SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
Set sourcewb = Workbooks.Open(SrceFile)
With sourcewb.Worksheets(1)
SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
sourcewb.Close
End With
'Target File row count
TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
Set targetwb = Workbooks.Open(TrgtFile)
With targetwb.Worksheets(1)
TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
targetwb.Close
End With
' Set Row Count Result Test data value
TitleId = TitleId + 3
Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value
'Compare Source and Target Row count
Resultid = TitleId + 1
Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
If (SourceRowCount = TargetRowCount) Then
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestPassCount = TestPassCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestFailCount = TestFailCount + 1
End If
'For comparison of two files
FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
FileName2 = Worksheets("TestData").Range("E" & RecordId).Value
Set myWorkbook1 = Workbooks.Open(FileName1)
Set myWorkbook2 = Workbooks.Open(FileName2)
Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
myWorkbook1.Close
myWorkbook2.Close
'MsgBox Difference
'Set Result of data validation in result sheet
Resultid = Resultid + 1
Worksheets("Result").Activate
Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"
If Difference > 0 Then
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestFailCount = TestFailCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestPassCount = TestPassCount + 1
End If
Next RecordId
End If
UpdateTestExecData TestPassCount, TestFailCount
End Sub
Sub RefreshResultSheet()
Worksheets("Result").Activate
Worksheets("Result").Range("B1:B4").Select
Selection.ClearContents
Worksheets("Result").Range("D1:D4").Select
Selection.ClearContents
Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub
Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
Worksheets("Result").Range("D2").Value = TestPassCount
Worksheets("Result").Range("D3").Value = TestFailCount
Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub
Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:
foo.h:
namespace foo {
void bar();
}
foo.cc:
namespace foo {
namespace { // wrong
void bar() { cout << "hello"; };
}
}
other.cc file:
#include "foo.h"
void baz() {
foo::bar();
}
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
Based on your newly-added backstory with the question, why not just return an integer from 1 to 12 for the month, and let the main() function use a switch statement or if-else ladder to decide what to print? It's certainly not the best way to go - char* would be - but in the context of a class like this I imagine it's probably the most elegant.
I don't think you can give a path to curl, but you can CD to the location, download and CD back.
cd target/path && { curl -O URL ; cd -; }
Or using subshell.
(cd target/path && curl -O URL)
Both ways will only download if path exists. -O
keeps remote file name. After download it will return to original location.
If you need to set filename explicitly, you can use small -o
option:
curl -o target/path/filename URL
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range
you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2
not being found in the searched range Sheet1!A1:A65536
. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet
is Sheet1
, then using Range("D2")
without qualifying it will be searching for Sheet1!D2
, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup
(although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP
as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A
in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...
).
Using =VLOOKUP...
is fundamentally different from Application.WorksheetFunction.VLookup
: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).