litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);
You print Float here
, that has no format at all.
To print formatted float, just use
String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);
Try out with the Smarty Session:
{$smarty.session|@debug_print_var}
or
{$smarty.session|@print_r}
To beautify your output, use it between <pre> </pre>
tags
While the answers with List<T>.ForEach
are very good.
I found String.Join<T>(string separator, IEnumerable<T> values)
method more useful.
Example :
List<string> numbersStrLst = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
Remarks :
If separator is null, an empty string (String.Empty
) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>)
is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.
This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])
Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx
You can check if you got your remote setup right and have the proper permissions with
git ls-remote origin
if you called your remote "origin". If you get an error you probably don't have your security set up correctly such as uploading your public key to github for example. If things are setup correctly, you will get a list of the remote references. Now
git fetch origin
will work barring any other issues like an unplugged network cable.
Once you have that done, you can get any branch you want that the above command listed with
git checkout some-branch
this will create a local branch of the same name as the remote branch and check it out.
You have a few options:
You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!
I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.
module.directive('boundModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
if(newValue != oldValue) {
ngModel.$setViewValue(newValue);
ngModel.$render();
}
});
// When $destroy is fired stop watching the change.
// If you don't, and you come back on your state
// you'll have two watcher watching the same properties
scope.$on('$destroy', function() {
boundModel$watcher();
});
}
});
You can use it in your templates like this:
<li>Total<input type="text" ng-model="total" bound-model="one * two"></li>
You can try calling this method in you program:
static double string_double(string s)
{
double temp = 0;
double dtemp = 0;
int b = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
i++;
while (i < s.Length)
{
dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
i++;
b++;
}
temp = temp + (dtemp * Math.Pow(10, -b));
return temp;
}
else
{
temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
}
}
return -1; //if somehow failed
}
Example:
string s = "12.3";
double d = string_double (s); //d = 12.3
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
There are multiple hit & trial solutions for this error. One of them will surely work for you. Below are the solutions:
1.
Tools -> Android -> Sync Project with Gradle Files (Android Studio 3.0.1)
2.
Go to build.gradle and click sync now
3.
Click this icon to sync gradle enter image description here
or edit any of your module gradle and then sync
4.
File -> Settings -> Android SDK -> Android SDK Location Edit -> Android SDK
5.
Open build.gradle file, just add a space or press enter. Then sync project.
6.
File -> Invalidate Caches / Restart
Easiest way is to customize bootstrap
find variable:
@grid-float-breakpoint
which is set to @screen-sm, you can change it according to your needs. Hope it helps!
The way I do it is I have a bare Git repository on my deployment server where I push changes. Then I log in to the deployment server, change to the actual web server docs directory, and do a git pull. I don't use any hooks to try to do this automatically, that seems like more trouble than it's worth.
If you return a FileResult
from your action method, and use the File()
extension method on the controller, doing what you want is pretty easy. There are overrides on the File()
method that will take the binary contents of the file, the path to the file, or a Stream
.
public FileResult DownloadFile()
{
return File("path\\to\\pdf.pdf", "application/pdf");
}
You could do so by using the attribute accept
and adding allowed mime-types to it. But not all browsers do respect that attribute and it could easily be removed via some code inspector. So in either case you need to check the file type on the server side (your second question).
Example:
<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
To your third question "And when I click the files (PDF/XLS) on webpage it automatically should open.":
You can't achieve that. How a PDF or XLS is opened on the client machine is set by the user.
I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:
CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)
IF (LEN(@PhoneNo) <> 10)
SET @Formatted = @PhoneNo
ELSE
SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)
RETURN @Formatted
END
GO
Which you can then use like this:
SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable
It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.
EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)
Can use either json or ast python modules:
Using json :
=============
import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")
Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2
Using ast:
==========
import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")
Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2
Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:
You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.
Transactions shouldn't be a problem if you use them correctly.
Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.
See other answers for Oracle comparison.
I know this is an old thread, but I feel the need to post the proper answer. The actual answer to this question is that you need to create a new stacking context on the parent of the element with the pseudo element (and you actually have to give it a z-index, not just a position).
Like this:
#parent {
position: relative;
z-index: 1;
}
#pseudo-parent {
position: absolute;
/* no z-index allowed */
}
#pseudo-parent:after {
position: absolute;
top:0;
z-index: -1;
}
It has nothing to do with using :before or :after pseudo elements.
#parent { position: relative; z-index: 1; }_x000D_
#pseudo-parent { position: absolute; } /* no z-index required */_x000D_
#pseudo-parent:after { position: absolute; z-index: -1; }_x000D_
_x000D_
/* Example styling to illustrate */_x000D_
#pseudo-parent { background: #d1d1d1; }_x000D_
#pseudo-parent:after { margin-left: -3px; content: "M" }
_x000D_
<div id="parent">_x000D_
<div id="pseudo-parent">_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
If you have the classes separated in a data frame or a matrix, then you can use matplot
. For example, if we have
dat<-as.data.frame(cbind(c(1,2,5,7),c(2.1,4.2,-0.5,1),c(9,3,6,2.718)))
plot.new()
plot.window(c(0,nrow(dat)),range(dat))
matplot(dat,col=c("red","blue","yellow"),pch=20)
Then you'll get a scatterplot where the first column of dat
is plotted in red, the second in blue, and the third in yellow. Of course, if you want separate x and y values for your color classes, then you can have datx
and daty
, etc.
An alternate approach would be to tack on an extra column specifying what color you want (or keeping an extra vector of colors, filling it iteratively with a for
loop and some if
branches). For example, this will get you the same plot:
dat<-as.data.frame(
cbind(c(1,2,5,7,2.1,4.2,-0.5,1,9,3,6,2.718)
,c(rep("red",4),rep("blue",4),rep("yellow",4))))
dat[,1]=as.numeric(dat[,1]) #This is necessary because
#the second column consisting of strings confuses R
#into thinking that the first column must consist of strings, too
plot(dat[,1],pch=20,col=dat[,2])
Probably you have this:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()
but you can close the connection after you use it.
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});
The Unicode code blocks that the others answers gave certainly cover most of the Chinese Unicode characters, but check out some of these other code blocks, too.
CJK_UNIFIED_IDEOGRAPHS
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
CJK_COMPATIBILITY
CJK_COMPATIBILITY_FORMS
CJK_COMPATIBILITY_IDEOGRAPHS
CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
CJK_RADICALS_SUPPLEMENT
CJK_STROKES
CJK_SYMBOLS_AND_PUNCTUATION
ENCLOSED_CJK_LETTERS_AND_MONTHS
ENCLOSED_IDEOGRAPHIC_SUPPLEMENT
KANGXI_RADICALS
IDEOGRAPHIC_DESCRIPTION_CHARACTERS
See my fuller discussion here. And this site is convenient for browsing Unicode.
I needed this command to make it work on El Capitan:
sudo security add-trust -d -r trustRoot -p basic -p codeSign -k /Library/Keychains/System.keychain ~/Desktop/gdb-cert.cer
I was trying to run this from within the Visual Studio 2017 Package Manager Console. None of the above suggestions worked.
See this link where Microsoft states "The solution is not to use package manager for angular development, but instead use powershell command line. ".
The current state of a socket is determined by 'keep-alive' activity. In your case, this is possible that when you are issuing the send
call, the keep-alive
activity tells that the socket is active and so the send
call will write the required data (40 bytes) in to the buffer and returns without giving any error.
When you are sending a bigger chunk, the send call goes in to blocking state.
The send man page also confirms this:
When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case
So, while blocking for the free available buffer, if the caller is notified (by keep-alive mechanism) that the other end is no more present, the send call will fail.
Predicting the exact scenario is difficult with the mentioned info, but I believe, this should be the reason for you problem.
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was : 1) It was giving message on all navigations I want it only for close click. 2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
There is a bug introduced in 2.6, and affects to 2.7 as well
The upsert used to work correctly on 2.4
https://groups.google.com/forum/#!topic/mongodb-user/UcKvx4p4hnY https://jira.mongodb.org/browse/SERVER-13843
Take a look, it contains some important info
It doesnt mean upsert does not work. Here is a nice example of how to use it:
User.findByIdAndUpdate(userId, {online: true, $setOnInsert: {username: username, friends: []}}, {upsert: true})
.populate('friends')
.exec(function (err, user) {
if (err) throw err;
console.log(user);
// Emit load event
socket.emit('load', user);
});
As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub
. The simplest way is to change location
to str(location)
when using re.sub
. It wouldn't hurt to do it anyways even if it's already a str
.
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
str(location))
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
After spent a lot of hours on Google search, I found the below solution as when I locally give date time, no exception while from other server, there was Error......... Date is not in proper format.. Before saving/ searching Text box date time in C#, just checking either the outer Serer Culture is same like database server culture.. Ex both should be "en-US" or must be both "en-GB" asp below snap shot.
Even with different date format like (dd/mm/yyyy) or (yyyy/mm/dd), it will save or search accurately.
Not sure if this is what you're referring to, but this is the list of HTML entities you can use:
List of XML and HTML character entity references
Using the content within the 'Name' column you can just wrap these in an &
and ;
E.g.
,  
, etc.
This solution reads in an input file line by line, writing each line out to a StringBuilder variable. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. Then it deletes file content and put the StringBuilder variable content.
public void removeLineFromFile(String lineToRemove, File f) throws FileNotFoundException, IOException{
//Reading File Content and storing it to a StringBuilder variable ( skips lineToRemove)
StringBuilder sb = new StringBuilder();
try (Scanner sc = new Scanner(f)) {
String currentLine;
while(sc.hasNext()){
currentLine = sc.nextLine();
if(currentLine.equals(lineToRemove)){
continue; //skips lineToRemove
}
sb.append(currentLine).append("\n");
}
}
//Delete File Content
PrintWriter pw = new PrintWriter(f);
pw.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(f, true));
writer.append(sb.toString());
writer.close();
}
My 'Map' implementation, derived from Christoph's example:
Example usage:
var map = new Map(); // Creates an "in-memory" map
var map = new Map("storageId"); // Creates a map that is loaded/persisted using html5 storage
function Map(storageId) {
this.current = undefined;
this.size = 0;
this.storageId = storageId;
if (this.storageId) {
this.keys = new Array();
this.disableLinking();
}
}
Map.noop = function() {
return this;
};
Map.illegal = function() {
throw new Error("illegal operation for maps without linking");
};
// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
var map = new Map;
for(var prop in obj) {
if(foreignKeys || obj.hasOwnProperty(prop))
map.put(prop, obj[prop]);
}
return map;
};
Map.prototype.disableLinking = function() {
this.link = Map.noop;
this.unlink = Map.noop;
this.disableLinking = Map.noop;
this.next = Map.illegal;
this.key = Map.illegal;
this.value = Map.illegal;
// this.removeAll = Map.illegal;
return this;
};
// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
return (typeof value) + ' ' + (value instanceof Object ?
(value.__hash || (value.__hash = ++arguments.callee.current)) :
value.toString());
};
Map.prototype.hash.current = 0;
// --- Mapping functions
Map.prototype.get = function(key) {
var item = this[this.hash(key)];
if (item === undefined) {
if (this.storageId) {
try {
var itemStr = localStorage.getItem(this.storageId + key);
if (itemStr && itemStr !== 'undefined') {
item = JSON.parse(itemStr);
this[this.hash(key)] = item;
this.keys.push(key);
++this.size;
}
} catch (e) {
console.log(e);
}
}
}
return item === undefined ? undefined : item.value;
};
Map.prototype.put = function(key, value) {
var hash = this.hash(key);
if(this[hash] === undefined) {
var item = { key : key, value : value };
this[hash] = item;
this.link(item);
++this.size;
}
else this[hash].value = value;
if (this.storageId) {
this.keys.push(key);
try {
localStorage.setItem(this.storageId + key, JSON.stringify(this[hash]));
} catch (e) {
console.log(e);
}
}
return this;
};
Map.prototype.remove = function(key) {
var hash = this.hash(key);
var item = this[hash];
if(item !== undefined) {
--this.size;
this.unlink(item);
delete this[hash];
}
if (this.storageId) {
try {
localStorage.setItem(this.storageId + key, undefined);
} catch (e) {
console.log(e);
}
}
return this;
};
// Only works if linked
Map.prototype.removeAll = function() {
if (this.storageId) {
for (var i=0; i<this.keys.length; i++) {
this.remove(this.keys[i]);
}
this.keys.length = 0;
} else {
while(this.size)
this.remove(this.key());
}
return this;
};
// --- Linked list helper functions
Map.prototype.link = function(item) {
if (this.storageId) {
return;
}
if(this.size == 0) {
item.prev = item;
item.next = item;
this.current = item;
}
else {
item.prev = this.current.prev;
item.prev.next = item;
item.next = this.current;
this.current.prev = item;
}
};
Map.prototype.unlink = function(item) {
if (this.storageId) {
return;
}
if(this.size == 0)
this.current = undefined;
else {
item.prev.next = item.next;
item.next.prev = item.prev;
if(item === this.current)
this.current = item.next;
}
};
// --- Iterator functions - only work if map is linked
Map.prototype.next = function() {
this.current = this.current.next;
};
Map.prototype.key = function() {
if (this.storageId) {
return undefined;
} else {
return this.current.key;
}
};
Map.prototype.value = function() {
if (this.storageId) {
return undefined;
}
return this.current.value;
};
I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>
. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>
.
However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:
List<Object> list = new ArrayList<Object>();
list.add("some value");
list.add(3);
for(Object obj : list)
{
Class<?> clazz = obj.getClass();
Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
org.springframework.util.ReflectionUtils.makeAccessible(field);
System.out.println("value=" + field.get(obj));
}
Running this has an output of:
value=[C@1b67f74
value=3
I only ever use _GET or _POST. I prefer to have control.
What I don't like about either code fragment in the OP is that they discard the information on which HTTP method was used. And that information is important for input sanitization.
For example, if a script accepts data from a form that's going to be entered into the DB then the form had better use POST (use GET only for idempotent actions). But if the script receives the input data via the GET method then it should (normally) be rejected. For me, such a situation might warrant writing a security violation to the error log since it's a sign somebody is trying something on.
With either code fragment in the OP, this sanitization wouldn't be possible.
I was simply trying to Bind IP with IIS but ended up messing with IIS config files I literally tried 20+ solutions for this, which includes
but what worked which may work for someone else as well was to REPAIR
IIS from
Control Panel\Programs\Programs and Features
Else you can refer to this answer as well
0 */1 * * * “At minute 0 past every hour.”
0 */2 * * * “At minute 0 past every 2nd hour.”
This is the proper way to set cronjobs for every hr.
Multiprocessing and pickling is broken and limited unless you jump outside the standard library.
If you use a fork of multiprocessing
called pathos.multiprocesssing
, you can directly use classes and class methods in multiprocessing's map
functions. This is because dill
is used instead of pickle
or cPickle
, and dill
can serialize almost anything in python.
pathos.multiprocessing
also provides an asynchronous map function… and it can map
functions with multiple arguments (e.g. map(math.pow, [1,2,3], [4,5,6])
)
See discussions: What can multiprocessing and dill do together?
and: http://matthewrocklin.com/blog/work/2013/12/05/Parallelism-and-Serialization
It even handles the code you wrote initially, without modification, and from the interpreter. Why do anything else that's more fragile and specific to a single case?
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> class calculate(object):
... def run(self):
... def f(x):
... return x*x
... p = Pool()
... return p.map(f, [1,2,3])
...
>>> cl = calculate()
>>> print cl.run()
[1, 4, 9]
Get the code here: https://github.com/uqfoundation/pathos
And, just to show off a little more of what it can do:
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> p = Pool(4)
>>>
>>> def add(x,y):
... return x+y
...
>>> x = [0,1,2,3]
>>> y = [4,5,6,7]
>>>
>>> p.map(add, x, y)
[4, 6, 8, 10]
>>>
>>> class Test(object):
... def plus(self, x, y):
... return x+y
...
>>> t = Test()
>>>
>>> p.map(Test.plus, [t]*4, x, y)
[4, 6, 8, 10]
>>>
>>> res = p.amap(t.plus, x, y)
>>> res.get()
[4, 6, 8, 10]
Works for me. How log all php errors to a log fiie?
Just add following line to /etc/php.ini to log errors to specified file – /var/log/php-scripts.log
vi /etc/php.ini
Modify error_log directive
error_log = /var/log/php-scripts.log
Make sure display_errors set to Off (no errors to end users)
display_errors = Off
Save and close the file. Restart web server:
/etc/init.d/httpd restart
How do I log errors to syslog or Windows Server Event Log?
Modify error_log as follows :
error_log = syslog
How see logs?
Login using ssh or download a log file /var/log/php-scripts.log using sftp:
$ sudo tail -f /var/log/php-scripts.log
There's a lot of answers already, but here's another contribution:
Taken directly from the URL
polyfill validity check, use an input
element with type="url"
to take advantage of the browser's built-in validity check:
var inputElement = doc.createElement('input');
inputElement.type = 'url';
inputElement.value = url;
if (!inputElement.checkValidity()) {
throw new TypeError('Invalid URL');
}
To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid>
, which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed).
To move the active process to background, you can press ctrl z. The process is sent to background and you get back to the shell prompt. Use the fg
command to do the opposite.
In lodash you can use _.includes (which also aliases to _.contains)
You can search the whole array:
_.includes([1, 2, 3], 1); // true
You can search the array from a starting index:
_.includes([1, 2, 3], 1, 1); // false (begins search at index 1)
Search a string:
_.includes('pebbles', 'eb'); // true (string contains eb)
Also works for checking simple arrays of objects:
_.includes({ 'user': 'fred', 'age': 40 }, 'fred'); // true
_.includes({ 'user': 'fred', 'age': false }, false); // true
One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects
_.includes({ 'user': 'fred', 'age': {} }, {}); // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3); // false
Javascript is base of jQuery.
jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.
If the size of the string is fixed, you might find easier to use an array of chars. If you have to do this a lot, it will be a tiny bit faster too.
char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);
Also, I noticed in your original question, you use the Char class. If your chars are not nullable, it is better to use the lowercase char type.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
Most drivers support forward only resultset - so method like last, beforeFirst etc are not supported.
The first approach is suitable if you are also getting the data in the same loop - otherwise the resultSet has already been iterated and can not be used again.
In most cases the requirement is to get the number of rows a query would return without fetching the rows. Iterating through the result set to find the row count is almost same as processing the data. It is better to do another count(*) query instead.
If you need the "week ending" date this will work as well. This will count the number of records for each week. Example: If three work orders were created between (inclusive) 1/2/2010 and 1/8/2010 and 5 were created between (inclusive) 1/9/2010 and 1/16/2010 this would return:
3 1/8/2010
5 1/16/2010
I had to use the extra DATE() function to truncate my datetime field.
SELECT COUNT(*), DATE_ADD( DATE(wo.date_created), INTERVAL (7 - DAYOFWEEK( wo.date_created )) DAY) week_ending
FROM work_order wo
GROUP BY week_ending;
Try this out..
string[] things = new string[] { "paul", "bob", "lauren", "007", "90", "-10" };
List<int> num = new List<int>();
List<string> str = new List<string>();
for (int i = 0; i < things.Count(); i++)
{
int result;
if (int.TryParse(things[i], out result))
{
num.Add(result);
}
else
{
str.Add(things[i]);
}
}
Now Sort the lists and merge them back...
var strsort = from s in str
orderby s.Length
select s;
var numsort = from n in num
orderby n
select n;
for (int i = 0; i < things.Count(); i++)
{
if(i < numsort.Count())
things[i] = numsort.ElementAt(i).ToString();
else
things[i] = strsort.ElementAt(i - numsort.Count());
}
I jsut tried to make a contribution in this interesting question...
Android Studio takes source version equal to Target Version in your application. Compilation performed with source version equal to above mentioned Compile Version. So, take care that in your project Compile Version == Target Version (adjust module's build.gradle file).
From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .
router.navigateByUrl() is used for absolute path navigation.
ie,
If we need to navigate to entirely different route in that case we can use router.navigateByUrl
For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()
Syntax :
router.navigateByUrl(' ---- String ----');
router.navigate([], {relativeTo: route})
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
Here's a transcription of another answer I gave to a similar question:
If you apply utf8_encode() to an already UTF8 string it will return a garbled UTF8 output.
I made a function that addresses all this issues. It´s called Encoding::toUTF8().
You dont need to know what the encoding of your strings is. It can be Latin1 (iso 8859-1), Windows-1252 or UTF8, or the string can have a mix of them. Encoding::toUTF8() will convert everything to UTF8.
I did it because a service was giving me a feed of data all messed up, mixing UTF8 and Latin1 in the same string.
Usage:
$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);
Download:
https://github.com/neitanod/forceutf8
Update:
I've included another function, Encoding::fixUFT8(), wich will fix every UTF8 string that looks garbled.
Usage:
$utf8_string = Encoding::fixUTF8($garbled_utf8_string);
Examples:
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
will output:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Update: I've transformed the function (forceUTF8) into a family of static functions on a class called Encoding. The new function is Encoding::toUTF8().
In case if you are not aware of the number and name of columns in dataframe then this method can be handy:
column_list = []
df_column = pd.read_excel(file_name, 'Sheet1').columns
for i in df_column:
column_list.append(i)
converter = {col: str for col in column_list}
df_actual = pd.read_excel(file_name, converters=converter)
where column_list is the list of your column names.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
You can use a generator expression:
tuple(i for i in (1, 2, 3))
but parentheses were already taken for … generator expressions.
If you require your keys to be any object rather than just strings, then you could use my jshashtable.
import pandas as pd
Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
Here is somewhat old-fashioned solution:
/*
Splits string into parts delimitered with specified character.
*/
CREATE FUNCTION [dbo].[SDF_SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter
begin
set @iStart = 2
insert into @tParts
values( null )
end
else
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0
insert into @tParts
values ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString )
break
end
RETURN
END
In SQL Server 2008 you can achieve the same with .NET code. Maybe it would work faster, but definitely this approach is easier to manage.
This error can sometimes occur when you edit some Project Toolchain settings Atmel Studio 6.1.2730 SP2.
In my case I tried to edit Project Properties > Toolchain > Linker > General settings with 'All Configurations' selected in the Configuration. When I checked or unchecked a setting, a dialog with the error popped up. However, I found that I could make the same edits if I made them to only one build configuration at a time; i.e. with only 'Debug' or 'Release' selected instead of 'All Configurations'.
Interestingly, I later was able to edit the same Linker settings even with 'All Configurations' selected. I don't know what changed in my project that made this possible.
If you only have one line of text and your div has a fixed height, you can do this:
div {
line-height: (2*height - font-size);
text-align: right;
}
See fiddle.
As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:
string msg = @"I want to learn ""c#""";
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
In python 3.x. you use
print("Hello, World")
In Python 2.x. you use
print "Hello, World!"
Just use
<a [ngClass]="{'disabled': your_condition}"> This a tag is disabled</a>
Example:
<a [ngClass]="{'disabled': name=='junaid'}"> This a tag is disabled</a>
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
javap
to read the bytecodeThe javap
command takes class-names without the .class
extension. Try
javap -c ClassName
javap
will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.
To actually decompile (i.e., do the reverse of javac
) you will have to use proper decompiler. See for instance the following related question:
Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
Result:
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
If you are using Eclipse, for an existing project (which has a build.gradle
file) you can simply type gradle eclipse
which will create all the Eclipse files and folders for this project.
It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
For Each line As String In System.IO.File.ReadAllLines("D:\abc.csv")
DataGridView1.Rows.Add(line.Split(","))
Next
As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options
and xp_cmdshell
to 1
, in that order.
Adding to this, if you want to preserve the previous values, you can read them from sys.configurations
first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure
calls:
declare @prevAdvancedOptions int
declare @prevXpCmdshell int
select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'
if (@prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 1
reconfigure
end
if (@prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 1
reconfigure
end
/* do work */
if (@prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 0
reconfigure
end
if (@prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 0
reconfigure
end
Note that this relies on SQL Server version 2005 or later (original question was for 2008).
There may be two situations.
Please see and confim the same.
In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>
.
The maximum value of an integer (which is signed) is 2147483647
. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.
If that exception wouldn't be thrown, you'd have a value of -2145629296
for your Volume
, which is most probably not wanted.
Solution: Use an Int64
for your volume. With a max value of 9223372036854775807
, you're probably more on the safe side.
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
user@bsd:~/work/git$ rm slides.tex
user@bsd:~/work/git$ git pull
Already up-to-date.
user@bsd:~/work/git$ ls slides.tex
ls: slides.tex: No such file or directory
Restore the deleted file:
user@bsd:~/work/git$ git checkout
D .slides.tex.swp
D slides.tex
user@bsd:~/work/git$ git checkout slides.tex
user@bsd:~/work/git$ ls slides.tex
slides.tex
Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.
Example:
public class A
{
public static class B
{
}
}
Because class B
is declared static you can explicitly instantiate as:
B b = new B();
Note if class B
wasn't declared static to make it stand alone, an instance object call would've looked like this:
A a= new A();
B b = a.new B();
You can do this:
<div style="text-align: center">
<a href="contact.html" class="button large hpbottom">Get Started</a>
</div>
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
I have the following code that scales the entire page through CSS properties. The important thing is to set body.style.width to the inverse of the zoom to avoid horizontal scrolling. You must also set transform-origin to top left to keep the top left of the document at the top left of the window.
var zoom = 1;
var width = 100;
function bigger() {
zoom = zoom + 0.1;
width = 100 / zoom;
document.body.style.transformOrigin = "left top";
document.body.style.transform = "scale(" + zoom + ")";
document.body.style.width = width + "%";
}
function smaller() {
zoom = zoom - 0.1;
width = 100 / zoom;
document.body.style.transformOrigin = "left top";
document.body.style.transform = "scale(" + zoom + ")";
document.body.style.width = width + "%";
}
when you change a file which is already in the repository, you have to git add
it again if you want it to be staged.
This allows you to commit only a subset of the changes you made since the last commit. For example, let's say you have file a
, file b
and file c
. You modify file a
and file b
but the changes are very different in nature and you don't want all of them to be in one single commit. You issue
git add a
git commit a -m "bugfix, in a"
git add b
git commit b -m "new feature, in b"
As a side note, if you want to commit everything you can just type
git commit -a
Hope it helps.
If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)
This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.
To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off
Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature
IPv6
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()
IPv4
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()
Generally you can just cast the variable to become a short
.
You can also get problems like this that can be confusing. This is because the +
operator promotes them to an int
Casting the elements won't help:
You need to cast the expression:
TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.
For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.
However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b
to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe
, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.
This is what I expected to see when I came to this question:
#!/usr/bin/env python
import pandas as pd
df = pd.DataFrame([(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, 1, 2),
(3, 4, 5, 6)],
columns=list('abcd'),
index=['India', 'France', 'England', 'Germany'])
print(df)
gives
a b c d
India 1 2 3 4
France 5 6 7 8
England 9 0 1 2
Germany 3 4 5 6
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
pod update POD_NAME
will update latest pod but not update Podfile.lock
file.
So, you may update your Podfile with specific version of your pod e.g pod 'POD_NAME', '~> 2.9.0'
and then use command pod install
Later, you can remove the specific version naming from your Podfile and can again use pod install
. This will helps to keep Podfile.lock
updated.
&
is used to separate commands. Therefore you can use ^
to escape the &
.
It's simple using a table:
<html>
<head>
<title>100% Height test</title>
</head>
<body>
<table style="float: left; height: 100%; width: 200px; border: 1px solid red">
<tbody>
<tr>
<td>Nav area</td>
</tr>
</tbody>
</table>
<div style="border: 1px solid green;">Content blabla... text
<br /> text
<br /> text
<br /> text
<br />
</div>
</body>
</html>
When DIV was introduced, people were so afraid of tables that the poor DIV became the metaphorical hammer.
SEMAPHORE EXAMPLE ::
sem_t m;
sem_init(&m, 0, 0); // initialize semaphore to 0
sem_wait(&m);
// critical section here
sem_post(&m);
Reference : http://pages.cs.wisc.edu/~remzi/Classes/537/Fall2008/Notes/threads-semaphores.txt
#multi argument
def joke(r):
if len(r)==2:
x, y = r
return x + y
elif len(r)==3:
x,y,z=r
return x+y+z
#using map
print(list(map(joke,[[2,3],[3,4,5]])))
output = [6,12]
if the case like above and just want use function
def add(x,y):
ar =[]
for xx in x:
ar.append(xx+y)
return ar
print(list(map(add,[[3,2,4]],[2]))[0])
output = [5,4,6]
Note: you can modified as you want.
If you are using Kotlin, you can define an extension function for DatePicker
:
fun DatePicker.getDate(): Date {
val calendar = Calendar.getInstance()
calendar.set(year, month, dayOfMonth)
return calendar.time
}
Then, it's just: datePicker.getDate()
. As if it had always existed.
Use the eq selector to selct the nth row (0-based) and add your row after it using after, so:
$('#my_table > tbody:last tr:eq(2)').after(html);
where html is a tr
When you query a blank array add "<< 0" to the array in the where block so it doesn't return "NULL" and break the query.
Topic.where('id not in (?)',actions << 0)
If actions could be an empty or blank array.
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
If you need both the sorted list and the list of indices, you could do:
L = [2,3,1,4,5]
from operator import itemgetter
indices, L_sorted = zip(*sorted(enumerate(L), key=itemgetter(1)))
list(L_sorted)
>>> [1, 2, 3, 4, 5]
list(indices)
>>> [2, 0, 1, 3, 4]
Or, for Python <2.4 (no itemgetter
or sorted
):
temp = [(v,i) for i,v in enumerate(L)]
temp.sort
indices, L_sorted = zip(*temp)
p.s. The zip(*iterable)
idiom reverses the zip process (unzip).
To deal with your specific requirements:
"my specific need to sort a list of objects based on a property of the objects. i then need to re-order a corresponding list to match the order of the newly sorted list."
That's a long-winded way of doing it. You can achieve that with a single sort by zipping both lists together then sort using the object property as your sort key (and unzipping after).
combined = zip(obj_list, secondary_list)
zipped_sorted = sorted(combined, key=lambda x: x[0].some_obj_attribute)
obj_list, secondary_list = map(list, zip(*zipped_sorted))
Here's a simple example, using strings to represent your object. Here we use the length of the string as the key for sorting.:
str_list = ["banana", "apple", "nom", "Eeeeeeeeeeek"]
sec_list = [0.123423, 9.231, 23, 10.11001]
temp = sorted(zip(str_list, sec_list), key=lambda x: len(x[0]))
str_list, sec_list = map(list, zip(*temp))
str_list
>>> ['nom', 'apple', 'banana', 'Eeeeeeeeeeek']
sec_list
>>> [23, 9.231, 0.123423, 10.11001]
A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
The most commonly used type parameter names are:
In Java 7 it is permitted to instantiate like this:
Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6
you can search on
http://
<ip/hostname>
:<port>
/v2/_catalog
Here is some CSS using nth-of-type
selectors that seems to work:
.modal:nth-of-type(even) {
z-index: 1042 !important;
}
.modal-backdrop.in:nth-of-type(even) {
z-index: 1041 !important;
}
Bootply: http://bootply.com/86973
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
For :
OS X : 10.11.6
Java : 8
I confirm the answer of @Morrie .
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home;
But if you are running containers your life will be easier
Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.
Best solution is to use Guava's ListenableFuture. An example :
ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
someBackgroundTask();
}
});
Futures.addCallback(future, new FutureCallback<Long>()
{
@Override
public void onSuccess(Long result)
{
doSomething();
}
@Override
public void onFailure(Throwable t)
{
}
};
I know this question is several years old, but what I think you're trying to do is get it so where a large element, like an image doesn't interfere with the height of a div?
I just ran into something similar, where I wanted an image to overflow a div, but I wanted it to be at the end of a string of text, so I didn't know where it would end up being.
A solution I figured out was to put the margin-bottom: -element's height, so if the image is 20px hight,
margin-bottom: -20px;
vertical-align: top;
for example.
That way it floated over the outside of the div, and stayed next to the last word in the string.
Give it @Year and @Week, return first date of that week.
Declare @Year int
,@Week int
,@YearText varchar(4)
set @Year = 2009
set @Week = 10
set @YearText = @Year
print dateadd(day
,1 - datepart(dw, @YearText + '-01-01')
+ (@Week-1) * 7
,@YearText + '-01-01')
This version need not math library and checked the return value of clock_gettime().
#include <time.h>
#include <stdlib.h>
#include <stdint.h>
/**
* @return milliseconds
*/
uint64_t get_now_time() {
struct timespec spec;
if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
abort();
}
return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
}
Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.
You can try this code for checking which date value is the highest from two dates with a format MM/DD/YYYY:
function d_check() {
var dl_sdt=document.getElementIdBy("date_input_Id1").value; //date one
var dl_endt=document.getElementIdBy("date_input_Id2").value; //date two
if((dl_sdt.substr(6,4)) > (dl_endt.substr(6,4))) {
alert("first date is greater");
return false;
}
else if((((dl_sdt.substr(0,2)) > (dl_endt.
substr(0,2)))&&(frdt(dl_sdt.substr(3,2)) > (dl_endt.substr(3,2))))||
(((dl_sdt.substr(0,2)) > (dl_endt.substr(0,2)))&&
((dl_sdt.substr(3,2)) < (dl_endt.substr(3,2))))||
(((dl_sdt.substr(0,2)) == (dl_endt.substr(0,2)))&&((dl_sdt.substr(3,2)) >
(dl_endt.substr(3,2))))) {
alert("first date is greater");
return false;
}
alert("second date is digher");
return true;
}
/*for checking this....create a form and give id's to two date inputs.The date format should be mm/dd/yyyy or mm-dd-yyyy or mm:dd:yyyy or mm.dd.yyyy like this. */
The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".
As for its use in Java, it stands for varargs
, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs
must be at the end of the method signature and there can only be one per method.
Perfect Solution that goes further to the goal
Goal: Disable the blinking curser when EditText
is not in focus, and enable the blinking curser when EditText
is in focus. Below also opens keyboard when EditText
is clicked, and hides it when you press done in the keyboard.
1) Set in your xml under your EditText
:
android:cursorVisible="false"
2) Set onClickListener:
iEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener()
{
public void onClick(View v)
{
if (v.getId() == iEditText.getId())
{
iEditText.setCursorVisible(true);
}
}
};
3) then onCreate
, capture the event when done is pressed using OnEditorActionListener
to your EditText
, and then setCursorVisible(false)
.
//onCreate...
iEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
iEditText.setCursorVisible(false);
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(iEditText.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
In JavaScript, there is a number called Infinity
.
Examples:
(Infinity>100)
=> true
// Also worth noting
Infinity - 1 == Infinity
=> true
Math.pow(2,1024) === Infinity
=> true
This may be sufficient for some questions regarding this topic.
MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.
The conventional operators
are available for DateTime
since .NET Framework 1.1. Also, addition and subtraction of DateTime
objects are also possible using conventional operators +
and -
.
One example from MSDN:
Equality:System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);
// areEqual gets false.
bool areEqual = april19 == otherDate;
otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Other operators can be used likewise.
Here is the list all operators available for DateTime
.
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
You could alter your CSS to render them less obtrusively, e.g.
div p,
div br {
display: inline;
}
or - as my commenter points out:
div br {
display: none;
}
but then to achieve the example of what you want, you'll need to trim the p
down, so:
div br {
display: none;
}
div p {
padding: 0;
margin: 0;
}
It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.
There are two parts of this problem
1) using a parameter that would not alter an url (using params property):
$stateProvider
.state('login', {
params: [
'toStateName',
'toParamsJson'
],
templateUrl: 'partials/login/Login.html'
})
2) passing an object as parameter: Well, there is no direct way how to do it now, as every parameter is converted to string (EDIT: since 0.2.13, this is no longer true - you can use objects directly), but you can workaround it by creating the string on your own
toParamsJson = JSON.stringify(toStateParams);
and in target controller deserialize the object again
originalParams = JSON.parse($stateParams.toParamsJson);
Python includes two functions in the math
package; radians
converts degrees to radians, and degrees
converts radians to degrees.
To match the output of your calculator you need:
>>> math.cos(math.radians(1))
0.9998476951563913
Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.
The middle one writes to the pipeline. Write-Host
and Out-Host
writes to the console. 'echo' is an alias for Write-Output
which writes to the pipeline as well. The best way to write to the console would be using the Write-Host
cmdlet.
When an object is written to the pipeline it can be consumed by other commands in the chain. For example:
"hello world" | Do-Something
but this won't work since Write-Host
writes to the console, not to the pipeline (Do-Something will not get the string):
Write-Host "hello world" | Do-Something
in my case it didn't work like following
@Query("select count(e)>0 from MyEntity e where ...")
You can return it as boolean value with following
@Query(value = "SELECT CASE WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")
For reversing the same list use:
array.reverse()
To assign reversed list into some other list use:
newArray = array[::-1]
There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float
or double
to represent money.
So if you want decimal places in your result, that result must either be a String
(which you already got with the DecimalFormat
), or a BigDecimal
(which has a setScale()
method that does exactly what you want). Otherwise, the result cannot be what you want it to be.
Read The Floating-Point Guide for more information.
Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True)
. The last parameter is Overwrite switch, which System.IO.File.Move
doesn't have.
Use the native element.submit()
to circumvent the preventDefault in the jQuery handler, and note that your return statement only returns from the each loop, it does not return from the event handler
$('form').submit(function(e){
e.preventDefault();
var valid = true;
$('[name="atendeename[]"]', this).each(function(index, el){
if ( $(el).val() ) {
var entree = $(el).next('input');
if ( ! entree.val()) {
entree.focus();
valid = false;
}
}
});
if (valid) this.submit();
});
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
I tried all the proposals to fix the render performance problem in my phonegap app. But nothing realy worked.
Finally, after a whole day of searching, I made it. I set within the tag (not the tag) of my AndroidManifest
<application android:hardwareAccelerated="false" ...
Now the app behaves in the same fast way as my webbrowser. Seems like, if hardware acceleration is not always the best feature...
The detailed problem I had: https://stackoverflow.com/a/24467920/3595386
This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document.
Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc.
I tried commenting as much as possible throughout the code so you could understand what each part is doing.
This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can’t do something with it.
Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders.
This example code will get all the files and create a list in a text document and place that text document in Folder1.
Caution: you shouldn’t save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main(string[] args)
{
// Create a header for your text file
string[] HeaderA = { "****** List of Files ******" };
System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);
// Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
// named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
{
//Now that we have a list of files, write them to a text file.
WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
}
// Now, append the header and list to the text file.
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
{
// First - call the header
foreach (string line in HeaderA)
{
file.WriteLine(line);
}
file.WriteLine(); // This line just puts a blank space between the header and list of files.
// Now, call teh list of files.
foreach (string name in arrayA)
{
file.WriteLine(name);
}
}
}
// These are just the "throw new exception" calls that are needed when converting the array's to strings.
// This one is for the Header.
private static void WriteAllLines(string v, string file)
{
//throw new NotImplementedException();
}
// And this one is for the list of files.
private static void WriteAllLines(string v, string[] arrayA)
{
//throw new NotImplementedException();
}
}
}
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
I have come up with a solution that is relatively accurate at evaluating when the angular initialisation is complete.
The directive is:
.directive('initialisation',['$rootScope',function($rootScope) {
return {
restrict: 'A',
link: function($scope) {
var to;
var listener = $scope.$watch(function() {
clearTimeout(to);
to = setTimeout(function () {
console.log('initialised');
listener();
$rootScope.$broadcast('initialised');
}, 50);
});
}
};
}]);
That can then just be added as an attribute to the body
element and then listened for using $scope.$on('initialised', fn)
It works by assuming that the application is initialised when there are no more $digest cycles. $watch is called every digest cycle and so a timer is started (setTimeout not $timeout so a new digest cycle is not triggered). If a digest cycle does not occur within the timeout then the application is assumed to have initialised.
It is obviously not as accurate as satchmoruns solution (as it is possible a digest cycle takes longer than the timeout) but my solution doesn't need you to keep track of the modules which makes it that much easier to manage (particularly for larger projects). Anyway, seems to be accurate enough for my requirements. Hope it helps.
You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.
CSS:
.tinted { opacity: 0.8; }
If you're interested in better browser compatability, I suggest reading this:
http://css-tricks.com/css-transparency-settings-for-all-broswers/
If you're determined enough you can get this working as far back as IE7 (who knew!)
Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.
Try this:
public class ConnectionProvider
{
DbConnection conn;
string connectionString;
DbProviderFactory factory;
// Constructor that retrieves the connectionString from the config file
public ConnectionProvider()
{
this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString.ToString();
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[0].ProviderName.ToString());
}
// Constructor that accepts the connectionString and Database ProviderName i.e SQL or Oracle
public ConnectionProvider(string connectionString, string connectionProviderName)
{
this.connectionString = connectionString;
factory = DbProviderFactories.GetFactory(connectionProviderName);
}
// Only inherited classes can call this.
public DbConnection GetOpenConnection()
{
conn = factory.CreateConnection();
conn.ConnectionString = this.connectionString;
conn.Open();
return conn;
}
}
Whenever you write custom text view basic HTML set text feature will be get vanished form some of the devices.
So we need to do following addtional steps make is work
public class CustomTextView extends TextView {
public CustomTextView(..) {
// other instructions
setText(Html.fromHtml(getText().toString()));
}
}
aunpack -e *.zip
, with atool
installed.
Has the advantage that it deals intelligently with errors, and always unpacks into subdirectories unless the zip contains only one file . Thus, there is no danger of polluting the current directory with masses of files, as there is with unzip
on a zip with no directory structure.
Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)
Here is how I would write a validator for MaxValue
public class MaxValueAttribute : ValidationAttribute
{
private readonly int _maxValue;
public MaxValueAttribute(int maxValue)
{
_maxValue = maxValue;
}
public override bool IsValid(object value)
{
return (int) value <= _maxValue;
}
}
The MinValue Attribute should be fairly the same
The option you're looking for is -R
.
cp -R path_to_source path_to_destination/
destination
doesn't exist, it will be created.-R
means copy directories recursively
. You can also use -r
since it's case-insensitive./
as per @muni764's comment.http://jsfiddle.net/cwZSW/1406/
#progress {_x000D_
background: #333;_x000D_
border-radius: 13px;_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
#progress:after {_x000D_
content: '';_x000D_
display: block;_x000D_
background: orange;_x000D_
width: 50%;_x000D_
height: 100%;_x000D_
border-radius: 9px;_x000D_
}
_x000D_
<div id="progress"></div>
_x000D_
This has been fixed
http://guides.rubygems.org/ssl-certificate-update/
Now that RubyGems 2.6.x has been released, you can manually update to this version.
Download https://rubygems.org/downloads/rubygems-update-2.6.7.gem
Please download the file in a directory that you can later point to (eg. the root of your harddrive C:)
Now, using your Command Prompt:
C:\>gem install --local C:\rubygems-update-2.6.7.gem
C:\>update_rubygems --no-ri --no-rdoc
After this, gem --version should report the new update version.
You can now safely uninstall rubygems-update gem:
C:\>gem uninstall rubygems-update -x
If you don't mind wasting a line by leaving it empty, consider the following hack (it is a hack, and use this only if you don't like adding any additional plugins).
| | | |
|-|-|-|
|__Bold Key__| Value1 |
| Normal Key | Value2 |
To view how the above one could look, copy the above and visit https://stackedit.io/editor
It worked with GitLab/GitHub's Markdown implementations.
You cannot test for string[]
in the general case but you can test for Array
quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330
If you specifically want for string
array you can do something like:
if (Array.isArray(value)) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString && value.length > 0){
console.log('string[]!');
}
}
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
You need to use a long literal:
obj.function(600851475143l); // note the "l" at the end
But I would expect that function to run out of memory (or time) ...
Also, Given a DataFrame
data
as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:
>>> data.iloc[:,[0,3]]
will give you
a d
0 0.883283 0.100975
1 0.614313 0.221731
2 0.438963 0.224361
3 0.466078 0.703347
4 0.955285 0.114033
5 0.268443 0.416996
6 0.613241 0.327548
7 0.370784 0.359159
8 0.692708 0.659410
9 0.806624 0.875476
Vivaldi Chromium-based Browser can hide the address bar for my Home Theather PC. Using that app you can show/hide a floating bar with F8 key. Other answers are unrelated to what was asked!
Use https://prestodb.io/docs/current/connector/kafka-tutorial.html
A super SQL engine, provided by Facebook, that connects on several data sources (Cassandra, Kafka, JMX, Redis ...).
PrestoDB is running as a server with optional workers (there is a standalone mode without extra workers), then you use a small executable JAR (called presto CLI) to make queries.
Once you have configured well the Presto server , you can use traditionnal SQL:
SELECT count(*) FROM TOPIC_NAME;
$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');
Well, I tried to measure it up with the code below:
For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:
LENGTH sum: 10626, per Iteration: 10626.0
CHANNEL sum: 5535, per Iteration: 5535.0
URL sum: 660, per Iteration: 660.0
For runs = 5 and iterations = 50 the picture draws different.
LENGTH sum: 39496, per Iteration: 157.984
CHANNEL sum: 74261, per Iteration: 297.044
URL sum: 95534, per Iteration: 382.136
File must be caching the calls to the filesystem, while channels and URL have some overhead.
Code:
import java.io.*;
import java.net.*;
import java.util.*;
public enum FileSizeBench {
LENGTH {
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
return me.length();
}
},
CHANNEL {
@Override
public long getResult() throws Exception {
FileInputStream fis = null;
try {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
fis = new FileInputStream(me);
return fis.getChannel().size();
} finally {
fis.close();
}
}
},
URL {
@Override
public long getResult() throws Exception {
InputStream stream = null;
try {
URL url = FileSizeBench.class
.getResource("FileSizeBench.class");
stream = url.openStream();
return stream.available();
} finally {
stream.close();
}
}
};
public abstract long getResult() throws Exception;
public static void main(String[] args) throws Exception {
int runs = 5;
int iterations = 50;
EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);
for (int i = 0; i < runs; i++) {
for (FileSizeBench test : values()) {
if (!durations.containsKey(test)) {
durations.put(test, 0l);
}
long duration = testNow(test, iterations);
durations.put(test, durations.get(test) + duration);
// System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
}
}
for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
System.out.println();
System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
}
}
private static long testNow(FileSizeBench test, int iterations)
throws Exception {
long result = -1;
long before = System.nanoTime();
for (int i = 0; i < iterations; i++) {
if (result == -1) {
result = test.getResult();
//System.out.println(result);
} else if ((result = test.getResult()) != result) {
throw new Exception("variance detected!");
}
}
return (System.nanoTime() - before) / 1000;
}
}
//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();
var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();
dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);
Well, you may try this '.*[0-9]'
I tried the Visual Studio Project Renamer, but, it threw exceptions in the few cases where I tried it.
I have had good success with CopyWiz.
I am in no way affiliated with them, and I have not yet paid for it, but I may have to soon, as it is the only tool that seems to work for both my C# and C++ projects. I do hope they make a little money, and continue to improve it, though.
Method1: To uninstall Anaconda3 go to the Anaconda3 folder, there u will be able to find an executable called Uninstall-Anaconda3.exe, double click on it. This should uninstall ur application. There are times when the shortcut of anaconda command prompt,jupyter notebook, spyder, etc exists, so delete those files too.
Method2 (Windows8): Go to control panel->Programs->Uninstall a Program and then select Anaconda3(Python3.1. 64-bit)in the menu.
If you ultimately want to convert the double
output of your round()
function to an int
, then the accepted solutions of this question will look something like:
int roundint(double r) {
return (int)((r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5));
}
This clocks in at around 8.88 ns on my machine when passed in uniformly random values.
The below is functionally equivalent, as far as I can tell, but clocks in at 2.48 ns on my machine, for a significant performance advantage:
int roundint (double r) {
int tmp = static_cast<int> (r);
tmp += (r-tmp>=.5) - (r-tmp<=-.5);
return tmp;
}
Among the reasons for the better performance is the skipped branching.
An alternative would be to use scrollViewWillEndDragging:withVelocity:targetContentOffset
which is called whenever the user lifts the finger and contains the target content offset where the scroll will stop. Using this content offset in scrollViewDidScroll:
correctly identifies when the scroll view has stopped scrolling.
private var targetY: CGFloat?
public func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
targetY = targetContentOffset.pointee.y
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y == targetY) {
print("finished scrolling")
}
You could use GNU Awk, see this article of the user guide.
As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
if (substr($c, 1, 1) == "\"") {
$c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
gsub("\"\"", "\"", $c) # Normalize double quotes
}
print $c
}
' c=3 < <(dos2unix <textfile.csv)
Note the use of dos2unix
to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.
If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
RS="\0" # Read the whole input file as one record;
# assume there is no null character in input.
FS="" # Suppose this setting eases internal splitting work.
ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
field=0;
for (i=1; i<=nof; i++){
field++
if (field==c) {
if (substr(a[i], 1, 1) == "\"") {
a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within
# the two quotes.
gsub(/""/, "\"", a[i]) # Normalize double quotes.
}
print a[i]
}
if (seps[i]!=",") field=0
}
}
' c=3 < <(dos2unix <textfile.csv)
There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:
csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u
csvquote
can be used to process arbitrary large files.
Just run the following line at the end of your function:
$scope.$apply()
You can do it using namespaces, like this:
export namespace Library {
export const BOOK_SHELF_NONE: string = 'NONE';
}
Then you can import it from anywhere else:
import {Library} from './Library';
console.log(Library.BOOK_SHELF_NONE);
If you need a class there as well include it inside the namespace: export class Book {...}
If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.
you can try this solution, is the best... url(github)
// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8
// Extend this class to save bytes
.transparent-background {
background-color: transparent;
zoom: 1;
}
// The mixin
@mixin transparent($color, $alpha) {
$rgba: rgba($color, $alpha);
$ie-hex-str: ie-hex-str($rgba);
@extend .transparent-background;
background-color: $rgba;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}
// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
@each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
.#{$name}-#{$alpha} {
@include transparent($color, $alpha / 100);
}
}
}
// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);
Another real world example using a list
an extract for a template for php.ini
{% if 'cli/php.ini' in item.d %}
max_execution_time = 0
memory_limit = 1024M
{% else %}
max_execution_time = 300
memory_limit = 512M
{% endif %}
This is the var
php_templates:
- { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/apache2/php.ini" }
- { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/cli/php.ini" }
Then i deploy with this
- name: push templated files
template:
src: "{{item.s}}"
dest: "{{item.d}}"
mode: "{{item.m | default(0644) }}"
owner: "{{item.o | default('root') }}"
group: "{{item.g | default('root') }}"
backup: yes
with_items: "{{php_templates}}"
Use this: For java
view.getBackground().setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_OVER)
for Kotlin
view.background.setColorFilter(Color.parseColor("#343434"),PorterDuff.Mode.SRC_OVER)
you can use PorterDuff.Mode.SRC_ATOP, if your background has rounded corners etc.
It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.
From facebook:
size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/
Set the login iframe opacity to 0 and show a background image in the parent div
.fb_iframe_widget iframe {
opacity: 0;
}
.fb_iframe_widget {
background-image: url(another-button.png);
background-repeat: no-repeat;
}
If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.
I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.
I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).
Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.
TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
Just read it in to MATLAB in one block
fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);
You can then process it using logical addressing
ind50 = data{2}>=50 ;
ind50 is then an index of the rows where column 2 is greater than 50. So
data{1}(ind50)
will list all the strings for the rows of interest.
Then just use fprintf
to write out your data to the new file
In my apache error log, I saw:
[Tue Feb 16 14:55:02 2010] [notice] child pid 9985 exit signal File size limit exceeded (25)
So I, removed all the contents of my largest log file 2.1GB /var/log/system.log. Now everything works.
Vietnamese characters for those who need them
'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$str = strtr( $str, $unwanted_array );
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.
You could just remove the id attribute and and replace it with:
<input type='text' name='task'>
and to get an array of the values of task do
var taskArray = new Array();
$("input[name=task]").each(function() {
taskArray.push($(this).val());
});
I modified Neutrino's solution to make the xaml look less verbose when specifying the value:
Sorry for no pictures of the rendered xaml, just imagine a [=] hamburger button that you click and it turns into [<-] a back button and also toggles the visibility of a Grid.
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
...
<Grid>
<Button x:Name="optionsButton">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<local:SetterAction PropertyName="Visibility" Value="Collapsed" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="Visible" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Visible" />
</i:EventTrigger>
</i:Interaction.Triggers>
<glyphs:Hamburger Width="10" Height="10" />
</Button>
<Button x:Name="optionsBackButton" Visibility="Collapsed">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<local:SetterAction PropertyName="Visibility" Value="Collapsed" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsButton}" Value="Visible" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Collapsed" />
</i:EventTrigger>
</i:Interaction.Triggers>
<glyphs:Back Width="12" Height="11" />
</Button>
</Grid>
...
<Grid Grid.RowSpan="2" x:Name="optionsPanel" Visibility="Collapsed">
</Grid>
You can also specify values this way like in Neutrino's solution:
<Button x:Name="optionsButton">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<local:SetterAction PropertyName="Visibility" Value="{x:Static Visibility.Collapsed}" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="{x:Static Visibility.Visible}" />
<local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="{x:Static Visibility.Visible}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<glyphs:Hamburger Width="10" Height="10" />
</Button>
And here's the code.
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
namespace Mvvm.Actions
{
/// <summary>
/// Sets a specified property to a value when invoked.
/// </summary>
public class SetterAction : TargetedTriggerAction<FrameworkElement>
{
#region Properties
#region PropertyName
/// <summary>
/// Property that is being set by this setter.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty =
DependencyProperty.Register("PropertyName", typeof(string), typeof(SetterAction),
new PropertyMetadata(String.Empty));
#endregion
#region Value
/// <summary>
/// Property value that is being set by this setter.
/// </summary>
public object Value
{
get { return (object)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(SetterAction),
new PropertyMetadata(null));
#endregion
#endregion
#region Overrides
protected override void Invoke(object parameter)
{
var target = TargetObject ?? AssociatedObject;
var targetType = target.GetType();
var property = targetType.GetProperty(PropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
if (property == null)
throw new ArgumentException(String.Format("Property not found: {0}", PropertyName));
if (property.CanWrite == false)
throw new ArgumentException(String.Format("Property is not settable: {0}", PropertyName));
object convertedValue;
if (Value == null)
convertedValue = null;
else
{
var valueType = Value.GetType();
var propertyType = property.PropertyType;
if (valueType == propertyType)
convertedValue = Value;
else
{
var propertyConverter = TypeDescriptor.GetConverter(propertyType);
if (propertyConverter.CanConvertFrom(valueType))
convertedValue = propertyConverter.ConvertFrom(Value);
else if (valueType.IsSubclassOf(propertyType))
convertedValue = Value;
else
throw new ArgumentException(String.Format("Cannot convert type '{0}' to '{1}'.", valueType, propertyType));
}
}
property.SetValue(target, convertedValue);
}
#endregion
}
}
Easiest way is to throw a ResponseStatusException
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
return json;
}
Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.
In short, the following are the steps to generate flame graphs
yum -y install perf
wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz
tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64
echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict
JAVA_PID=`pgrep java`
./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg
flame-graph.svg
can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.
There are few other approaches to generating them
-XX:+PreserveFramePointer
as the JVM options as described here-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
as described hereBut using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.
Their wiki provides details on how to leverage it. And more about flame graphs can be found here
For spaces, you can add single space in the digits. If you need any special characters like the dot, a comma also you can add to this list
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
I would suggest a different approach that I think requires less code and is more "localization-friendly".
Supposing that your destination activity is called "ActivityStack", define in the manifest an intent filter for it with a custom scheme (e.g. "myappscheme") in AndroidManifest.xml:
<activity
android:name=".ActivityStack">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:host="stack"/>
<data android:scheme="myappscheme" />
</intent-filter>
</activity>
Define the TextView without any special tag (it is important to NOT use the "android:autoLink" tag, see: https://stackoverflow.com/a/20647011/1699702):
<TextView
android:id="@+id/stackView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stack_string" />
then use a link with custom scheme and host in the text of the TextView as (in String.xml):
<string name="stack_string">Android is a Software <a href="myappscheme://stack">stack</a></string>
and "activate" the link with setMovementMethod() (in onCreate() for activities or onCreateView() for fragments):
TextView stack = findViewById(R.id.stackView);
stack.setMovementMethod(LinkMovementMethod.getInstance());
This will open the stack activity with a tap on the "stack" word.
If an Activity calls onPause
with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume
.
Sticky broadcasts are deprecated.
See sendStickyBroadcast
documentation.
This method was deprecated in API level 21.
Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);
Related post: What is the difference between sendStickyBroadcast and sendBroadcast in Android?
See removeStickyBroadcast(Intent)
, and on API Level 5 +, isInitialStickyBroadcast()
for usage in the Receiver's onReceive
.
In the hopes this elegant solution of a colleague of mine is even seen in this long post I'd like to share this approach for subclassing which follows the interface approach and beyond.
Please be aware that we use custom exceptions here and this code won't compile unless you replace it with your exceptions.
The documentation is extensive and I hope it's understandable for most of you.
The interface that every subclassed enum needs to implement.
public interface Parameter {
/**
* Retrieve the parameters name.
*
* @return the name of the parameter
*/
String getName();
/**
* Retrieve the parameters type.
*
* @return the {@link Class} according to the type of the parameter
*/
Class<?> getType();
/**
* Matches the given string with this parameters value pattern (if applicable). This helps to find
* out if the given string is a syntactically valid candidate for this parameters value.
*
* @param valueStr <i>optional</i> - the string to check for
* @return <code>true</code> in case this parameter has no pattern defined or the given string
* matches the defined one, <code>false</code> in case <code>valueStr</code> is
* <code>null</code> or an existing pattern is not matched
*/
boolean match(final String valueStr);
/**
* This method works as {@link #match(String)} but throws an exception if not matched.
*
* @param valueStr <i>optional</i> - the string to check for
* @throws ArgumentException with code
* <dl>
* <dt>PARAM_MISSED</dt>
* <dd>if <code>valueStr</code> is <code>null</code></dd>
* <dt>PARAM_BAD</dt>
* <dd>if pattern is not matched</dd>
* </dl>
*/
void matchEx(final String valueStr) throws ArgumentException;
/**
* Parses a value for this parameter from the given string. This method honors the parameters data
* type and potentially other criteria defining a valid value (e.g. a pattern).
*
* @param valueStr <i>optional</i> - the string to parse the parameter value from
* @return the parameter value according to the parameters type (see {@link #getType()}) or
* <code>null</code> in case <code>valueStr</code> was <code>null</code>.
* @throws ArgumentException in case <code>valueStr</code> is not parsable as a value for this
* parameter.
*/
Object parse(final String valueStr) throws ArgumentException;
/**
* Converts the given value to its external form as it is accepted by {@link #parse(String)}. For
* most (ordinary) parameters this is simply a call to {@link String#valueOf(Object)}. In case the
* parameter types {@link Object#toString()} method does not return the external form (e.g. for
* enumerations), this method has to be implemented accordingly.
*
* @param value <i>mandatory</i> - the parameters value
* @return the external form of the parameters value, never <code>null</code>
* @throws InternalServiceException in case the given <code>value</code> does not match
* {@link #getType()}
*/
String toString(final Object value) throws InternalServiceException;
}
The implementing ENUM base class.
public enum Parameters implements Parameter {
/**
* ANY ENUM VALUE
*/
VALUE(new ParameterImpl<String>("VALUE", String.class, "[A-Za-z]{3,10}"));
/**
* The parameter wrapped by this enum constant.
*/
private Parameter param;
/**
* Constructor.
*
* @param param <i>mandatory</i> - the value for {@link #param}
*/
private Parameters(final Parameter param) {
this.param = param;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.param.getName();
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getType() {
return this.param.getType();
}
/**
* {@inheritDoc}
*/
@Override
public boolean match(final String valueStr) {
return this.param.match(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public void matchEx(final String valueStr) {
this.param.matchEx(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public Object parse(final String valueStr) throws ArgumentException {
return this.param.parse(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public String toString(final Object value) throws InternalServiceException {
return this.param.toString(value);
}
}
The subclassed ENUM which "inherits" from base class.
public enum ExtendedParameters implements Parameter {
/**
* ANY ENUM VALUE
*/
VALUE(my.package.name.VALUE);
/**
* EXTENDED ENUM VALUE
*/
EXTENDED_VALUE(new ParameterImpl<String>("EXTENDED_VALUE", String.class, "[0-9A-Za-z_.-]{1,20}"));
/**
* The parameter wrapped by this enum constant.
*/
private Parameter param;
/**
* Constructor.
*
* @param param <i>mandatory</i> - the value for {@link #param}
*/
private Parameters(final Parameter param) {
this.param = param;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.param.getName();
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getType() {
return this.param.getType();
}
/**
* {@inheritDoc}
*/
@Override
public boolean match(final String valueStr) {
return this.param.match(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public void matchEx(final String valueStr) {
this.param.matchEx(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public Object parse(final String valueStr) throws ArgumentException {
return this.param.parse(valueStr);
}
/**
* {@inheritDoc}
*/
@Override
public String toString(final Object value) throws InternalServiceException {
return this.param.toString(value);
}
}
Finally the generic ParameterImpl to add some utilities.
public class ParameterImpl<T> implements Parameter {
/**
* The default pattern for numeric (integer, long) parameters.
*/
private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");
/**
* The default pattern for parameters of type boolean.
*/
private static final Pattern BOOLEAN_PATTERN = Pattern.compile("0|1|true|false");
/**
* The name of the parameter, never <code>null</code>.
*/
private final String name;
/**
* The data type of the parameter.
*/
private final Class<T> type;
/**
* The validation pattern for the parameters values. This may be <code>null</code>.
*/
private final Pattern validator;
/**
* Shortcut constructor without <code>validatorPattern</code>.
*
* @param name <i>mandatory</i> - the value for {@link #name}
* @param type <i>mandatory</i> - the value for {@link #type}
*/
public ParameterImpl(final String name, final Class<T> type) {
this(name, type, null);
}
/**
* Constructor.
*
* @param name <i>mandatory</i> - the value for {@link #name}
* @param type <i>mandatory</i> - the value for {@link #type}
* @param validatorPattern - <i>optional</i> - the pattern for {@link #validator}
* <dl>
* <dt style="margin-top:0.25cm;"><i>Note:</i>
* <dd>The default validation patterns {@link #NUMBER_PATTERN} or
* {@link #BOOLEAN_PATTERN} are applied accordingly.
* </dl>
*/
public ParameterImpl(final String name, final Class<T> type, final String validatorPattern) {
this.name = name;
this.type = type;
if (null != validatorPattern) {
this.validator = Pattern.compile(validatorPattern);
} else if (Integer.class == this.type || Long.class == this.type) {
this.validator = NUMBER_PATTERN;
} else if (Boolean.class == this.type) {
this.validator = BOOLEAN_PATTERN;
} else {
this.validator = null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean match(final String valueStr) {
if (null == valueStr) {
return false;
}
if (null != this.validator) {
final Matcher matcher = this.validator.matcher(valueStr);
return matcher.matches();
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void matchEx(final String valueStr) throws ArgumentException {
if (false == this.match(valueStr)) {
if (null == valueStr) {
throw ArgumentException.createEx(ErrorCode.PARAM_MISSED, "The value must not be null",
this.name);
}
throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value must match the pattern: "
+ this.validator.pattern(), this.name);
}
}
/**
* Parse the parameters value from the given string value according to {@link #type}. Additional
* the value is checked by {@link #matchEx(String)}.
*
* @param valueStr <i>optional</i> - the string value to parse the value from
* @return the parsed value, may be <code>null</code>
* @throws ArgumentException in case the parameter:
* <ul>
* <li>does not {@link #matchEx(String)} the {@link #validator}</li>
* <li>cannot be parsed according to {@link #type}</li>
* </ul>
* @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
* programming error.
*/
@Override
public T parse(final String valueStr) throws ArgumentException, InternalServiceException {
if (null == valueStr) {
return null;
}
this.matchEx(valueStr);
if (String.class == this.type) {
return this.type.cast(valueStr);
}
if (Boolean.class == this.type) {
return this.type.cast(Boolean.valueOf(("1".equals(valueStr)) || Boolean.valueOf(valueStr)));
}
try {
if (Integer.class == this.type) {
return this.type.cast(Integer.valueOf(valueStr));
}
if (Long.class == this.type) {
return this.type.cast(Long.valueOf(valueStr));
}
} catch (final NumberFormatException e) {
throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value cannot be parsed as "
+ this.type.getSimpleName().toLowerCase() + ".", this.name);
}
return this.parseOther(valueStr);
}
/**
* Field access for {@link #name}.
*
* @return the value of {@link #name}.
*/
@Override
public String getName() {
return this.name;
}
/**
* Field access for {@link #type}.
*
* @return the value of {@link #type}.
*/
@Override
public Class<T> getType() {
return this.type;
}
/**
* {@inheritDoc}
*/
@Override
public final String toString(final Object value) throws InternalServiceException {
if (false == this.type.isAssignableFrom(value.getClass())) {
throw new InternalServiceException(ErrorCode.PANIC,
"Parameter.toString(): Bad type of value. Expected {0} but is {1}.", this.type.getName(),
value.getClass().getName());
}
if (String.class == this.type || Integer.class == this.type || Long.class == this.type) {
return String.valueOf(value);
}
if (Boolean.class == this.type) {
return Boolean.TRUE.equals(value) ? "1" : "0";
}
return this.toStringOther(value);
}
/**
* Parse parameter values of other (non standard types). This method is called by
* {@link #parse(String)} in case {@link #type} is none of the supported standard types (currently
* String, Boolean, Integer and Long). It is intended for extensions.
* <dl>
* <dt style="margin-top:0.25cm;"><i>Note:</i>
* <dd>This default implementation always throws an InternalServiceException.
* </dl>
*
* @param valueStr <i>mandatory</i> - the string value to parse the value from
* @return the parsed value, may be <code>null</code>
* @throws ArgumentException in case the parameter cannot be parsed according to {@link #type}
* @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
* programming error.
*/
protected T parseOther(final String valueStr) throws ArgumentException, InternalServiceException {
throw new InternalServiceException(ErrorCode.PANIC,
"ParameterImpl.parseOther(): Unsupported parameter type: " + this.type.getName());
}
/**
* Convert the values of other (non standard types) to their external form. This method is called
* by {@link #toString(Object)} in case {@link #type} is none of the supported standard types
* (currently String, Boolean, Integer and Long). It is intended for extensions.
* <dl>
* <dt style="margin-top:0.25cm;"><i>Note:</i>
* <dd>This default implementation always throws an InternalServiceException.
* </dl>
*
* @param value <i>mandatory</i> - the parameters value
* @return the external form of the parameters value, never <code>null</code>
* @throws InternalServiceException in case the given <code>value</code> does not match
* {@link #getClass()}
*/
protected String toStringOther(final Object value) throws InternalServiceException {
throw new InternalServiceException(ErrorCode.PANIC,
"ParameterImpl.toStringOther(): Unsupported parameter type: " + this.type.getName());
}
}
As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents
to access REST APIs:
$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');
Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.
As posted in another answer, the wildcard library works for both glob and regex filename matching: http://code.google.com/p/wildcard/
I used the following code to match glob patterns including absolute and relative on *nix style file systems:
String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
baseDir = File.separator;
filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();
I spent some time trying to get the FileUtils.listFiles methods in the Apache commons io library (see Vladimir's answer) to do this but had no success (I realise now/think it can only handle pattern matching one directory or file at a time).
Additionally, using regex filters (see Fabian's answer) for processing arbitrary user supplied absolute type glob patterns without searching the entire file system would require some preprocessing of the supplied glob to determine the largest non-regex/glob prefix.
Of course, Java 7 may handle the requested functionality nicely, but unfortunately I'm stuck with Java 6 for now. The library is relatively minuscule at 13.5kb in size.
Note to the reviewers: I attempted to add the above to the existing answer mentioning this library but the edit was rejected. I don't have enough rep to add this as a comment either. Isn't there a better way...
The pair RegOpenKey and RegQueryKeyEx will do the trick.
If you use MFC CRegKey class is even more easier solution.
There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class. It's called JSX Control Statements:
<View style={styles.container}>
<If condition={ this.state == 'news' }>
<Text>data</Text>
</If>
</View>
It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.
As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.
.nextInt()
gets the next int
, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.
You can insert another .nextLine()
after you get the int
to fix this. Or (I prefer this way), read the int
in as a string
, and parse it to an int
.
You're currently trying to access a method like a property
Console.WriteLine("{0}",x.fullNameMethod);
It should be
Console.WriteLine("{0}",x.fullNameMethod());
Alternatively you could turn it into a property using
public string fullName
{
get
{
string x = firstName + " " + lastName;
return x;
}
}
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
getElementById("id").removeAttribute("style");
if you are using jQuery then
$("#id").removeClass("classname");
You can have multiple .gitignore
, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore
: git check-ignore -v -- afile
.
And you can have different version of a .gitignore
file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.
If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore
files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.
Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile
in order to see which gitignore run (from which .gitignore
file) is applied to 'yourfile
', and better understand why said file is ignored.
See "which gitignore
rule is ignoring my file?"
In normal winForms, value of Label object is changed by,
myLabel.Text= "Your desired string";
But in WPF Label control, you have to use .content property of Label control for example,
myLabel.Content= "Your desired string";
You can use the setTimeout
or setInterval
functions.
You can use an ExecutorCompletionService. The documentation even has an example for your exact use-case:
Suppose instead that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:
void solve(Executor e, Collection<Callable<Result>> solvers) throws InterruptedException {
CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e);
int n = solvers.size();
List<Future<Result>> futures = new ArrayList<Future<Result>>(n);
Result result = null;
try {
for (Callable<Result> s : solvers)
futures.add(ecs.submit(s));
for (int i = 0; i < n; ++i) {
try {
Result r = ecs.take().get();
if (r != null) {
result = r;
break;
}
} catch (ExecutionException ignore) {
}
}
} finally {
for (Future<Result> f : futures)
f.cancel(true);
}
if (result != null)
use(result);
}
The important thing to notice here is that ecs.take() will get the first completed task, not just the first submitted one. Thus you should get them in the order of finishing the execution (or throwing an exception).
The tibble vignette has an updated way to change its default printing behavior:
You can control the default appearance with options:
options(tibble.print_max = n, tibble.print_min = m)
: if there are more than n rows, print only the first m rows. Useoptions(tibble.print_max = Inf)
to always show all rows.
options(tibble.width = Inf)
will always print all columns, regardless of the width of the screen.
examples
This will always print all rows:
options(tibble.print_max = Inf)
This will not actually limit the printing to 50 lines:
options(tibble.print_max = 50)
But this will restrict printing to 50 lines:
options(tibble.print_max = 50, tibble.print_min = 50)
Like "VB's On Error Resume Next?" That sounds kind of scary. First recommendation is don't do it. Second recommendation is don't do it and don't think about it. You need to isolate your faults better. As to how to approach this problem, it depends on how you're code is structured. If you are using a pattern like MVC or the like then this shouldn't be too difficult and would definitely not require a global exception swallower. Secondly, look for a good logging library like log4net or use tracing. We'd need to know more details like what kinds of exceptions you're talking about and what parts of your application may result in exceptions being thrown.
The best way to view and manage your Android app database is to use the library DatabaseManager_For_Android.
It's a single Java activity file; just add it to your source folder. You can view the tables in your app database, update, delete, insert rows to you table. Everything from inside your app.
When the development is done remove the Java file from your src folder. That's it.
You can view the 5 minute demo, Database Manager for Android SQLite Database .
You start it like this:
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
and then
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
If we use Kotlin it is shorter. Example of class which responds for provide call logs:
import android.content.Context
import android.database.Cursor
import android.provider.CallLog.Calls.*
class CallsLoader {
fun getCallLogs(context: Context): List<List<String?>> {
val c = context.applicationContext
val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)
val cursor = c.contentResolver.query(
CONTENT_URI,
projection,
null,
null,
null,
null
)
return cursorToMatrix(cursor)
}
private fun cursorToMatrix(cursor: Cursor?): List<List<String?>> {
val matrix = mutableListOf<List<String?>>()
cursor?.use {
while (it.moveToNext()) {
val list = listOf(
it.getStringFromColumn(CACHED_NAME),
it.getStringFromColumn(NUMBER),
it.getStringFromColumn(TYPE),
it.getStringFromColumn(DATE),
it.getStringFromColumn(DURATION)
)
matrix.add(list.toList())
}
}
return matrix
}
private fun Cursor.getStringFromColumn(columnName: String) =
getString(getColumnIndex(columnName))
}
We can also convert cursor to map:
fun getCallLogs(context: Context): Map<String, Array<String?>> {
val c = context.applicationContext
val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)
val cursor = c.contentResolver.query(
CONTENT_URI,
projection,
null,
null,
null,
null
)
return cursorToMap(cursor)
}
private fun cursorToMap(cursor: Cursor?): Map<String, Array<String?>> {
val arraySize = cursor?.count ?: 0
val map = mapOf(
CACHED_NAME to Array<String?>(arraySize) { "" },
NUMBER to Array<String?>(arraySize) { "" },
TYPE to Array<String?>(arraySize) { "" },
DATE to Array<String?>(arraySize) { "" },
DURATION to Array<String?>(arraySize) { "" }
)
cursor?.use {
for (i in 0 until arraySize) {
it.moveToNext()
map[CACHED_NAME]?.set(i, it.getStringFromColumn(CACHED_NAME))
map[NUMBER]?.set(i, it.getStringFromColumn(NUMBER))
map[TYPE]?.set(i, it.getStringFromColumn(TYPE))
map[DATE]?.set(i, it.getStringFromColumn(DATE))
map[DURATION]?.set(i, it.getStringFromColumn(DURATION))
}
}
return map
}
you can git fetch nameofremoterepo
, then git log
and personally, I alias gitlog
to git log --graph --oneline --pretty --decorate --all
. try out and see if it fits you
When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.
I suppose you could (using basic string manipulation) generate the query string in the PreparedStatement
to have a number of ?
's matching the number of items in your list.
Of course if you're doing that you're just a step away from generating a giant chained OR
in your query, but without having the right number of ?
in the query string, I don't see how else you can work around this.
Short and simple implementation in Kotlin, with nullable support:
Add methods to Parcel
fun Parcel.writeBoolean(flag: Boolean?) {
when(flag) {
true -> writeInt(1)
false -> writeInt(0)
else -> writeInt(-1)
}
}
fun Parcel.readBoolean(): Boolean? {
return when(readInt()) {
1 -> true
0 -> false
else -> null
}
}
And use it:
parcel.writeBoolean(isUserActive)
parcel.readBoolean() // For true, false, null
parcel.readBoolean()!! // For only true and false