The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.
To Fix the no-man's land, this might work. It's not elegant, but works.
#doc3 {
margin: auto 10px;
width: auto;
height: 2000px;
background-color: yellow;
}
This will call methods from dictionary
This is python switch statement with function calling
Create few modules as per the your requirement. If want to pass arguments then pass.
Create a dictionary, which will call these modules as per requirement.
def function_1(arg):
print("In function_1")
def function_2(arg):
print("In function_2")
def function_3(fileName):
print("In function_3")
f_title,f_course1,f_course2 = fileName.split('_')
return(f_title,f_course1,f_course2)
def createDictionary():
dict = {
1 : function_1,
2 : function_2,
3 : function_3,
}
return dict
dictionary = createDictionary()
dictionary[3](Argument)#pass any key value to call the method
I had the same task, and I aligned my images to the right by adding this:
<div style="text-align: right"><img src="/default/image/sms.png" width="100" /></div>
For aligning your image to the left or center, replace
<div style="text-align: right">
with
<div style="text-align: center">
<div style="text-align: left">
On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.
Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/
$(document).ready(function () {
var $obj = $('#comment');
var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$obj.addClass('fixed');
} else {
// otherwise remove it
$obj.removeClass('fixed');
}
});
});
I looked for an array wrapper which makes it comparable to use with guava TreeRangeMap. The class doesn't accept comparator.
After some research I realized that ByteBuffer from JDK has this feature and it doesn't copy original array which is good. More over you can compare faster with ByteBuffer::asLongBuffer 8 bytes at time (also doesn't copy). By default ByteBuffer::wrap(byte[]) use BigEndian so order relation is the same as comparing individual bytes.
.
Yes, you can:
UPDATE foobar SET column_a = CASE
WHEN column_b = '123' THEN 1
WHEN column_b = '345' THEN 2
END
WHERE column_b IN ('123','345')
And working proof: http://sqlfiddle.com/#!2/97c7ea/1
ngRoute is part of the core AngularJS framework.
ui-router is a community library that has been created to attempt to improve upon the default routing capabilities.
Here is a good article about configuring/setting up ui-router:
try this..
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%'
GO
or you can generate a scripts of all procedures and search from there.
class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of
This should answer Greg's question.
Here's an cleaner solution:
guard CharacterSet(charactersIn: "123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
return false
}
return true
For decimals just add .
, example 123456789.
Complete set of Linq to SQL extensions of Duplicates functions checked in MS SQL Server. Without using .ToList() or IEnumerable. These queries executing in SQL Server rather than in memory.. The results only return at memory.
public static class Linq2SqlExtensions {
public class CountOfT<T> {
public T Key { get; set; }
public int Count { get; set; }
}
public static IQueryable<TKey> Duplicates<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
=> source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(s => s.Key);
public static IQueryable<TSource> GetDuplicates<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
=> source.GroupBy(groupBy).Where(w => w.Count() > 1).SelectMany(s => s);
public static IQueryable<CountOfT<TKey>> DuplicatesCounts<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
=> source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(y => new CountOfT<TKey> { Key = y.Key, Count = y.Count() });
public static IQueryable<Tuple<TKey, int>> DuplicatesCountsAsTuble<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
=> source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(s => Tuple.Create(s.Key, s.Count()));
}
You need to send this
object only instead of this.value
while calling onchange
<input type='file' id="upload" onchange="readURL(this)" />
because you are using input
variable as this
in your function, like at line
var url = input.value;// reading value property of input element
EDIT - Try using jQuery like below --
remove onchange from input field :
<input type='file' id="upload" >
Bind onchange
event to input field :
$(function(){
$('#upload').change(function(){
var input = this;
var url = $(this).val();
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
{
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else
{
$('#img').attr('src', '/assets/no_preview.png');
}
});
});
The difference between insert()
and operator[]
has already been well explained in the other answers. However, new insertion methods for std::map
were introduced with C++11 and C++17 respectively:
emplace()
as also mentioned in einpoklum's comment and GutiMac's answer.insert_or_assign()
and try_emplace()
.Let me give a brief summary of the "new" insertion methods:
emplace()
: When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert()
, an element is only inserted if there is no element with the same key in the container.insert_or_assign()
: This method is an "improved" version of operator[]
. Unlike operator[]
, insert_or_assign()
doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer.try_emplace()
: This method is an "improved" version of emplace()
. Unlike emplace()
, try_emplace()
doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.For more details on insert_or_assign()
and try_emplace()
please see my answer here.
You can trace the Progress Staus by the getProgress method in webview class.
Initialize the progress status
private int mProgressStatus = 0;
then the AsyncTask for loading like this:
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
your_class.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
while (mProgressStatus < 100) {
mProgressStatus = webview.getProgress();
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
ALTER TABLE CHANGE ;
Example:
ALTER TABLE global_user CHANGE deviceToken deviceId VARCHAR(255) ;
Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.
expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:
if expr match "$LIST" "$SOURCE"; then
But I'm not really clear what SOURCE is supposed to represent.
It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?
My solution for Python 3.6.5 64-bit Windows 10:
pip uninstall sklearn
pip uninstall scikit-learn
pip install sklearn
No need to restart command-line but you can do this if you want. It took me one day to fix this bug. Hope this help.
Casting my hat into the ring a couple years later.
Will need to save the beginning center of the image view:
var panBegin: CGPoint.zero
Then update the new center using a transform:
if recognizer.state == .began {
panBegin = imageView!.center
} else if recognizer.state == .ended {
panBegin = CGPoint.zero
} else if recognizer.state == .changed {
let translation = recognizer.translation(in: view)
let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)
imageView!.center = panBegin.applying(panOffsetTransform)
}
If you have time, use Vuex store for watching variables (aka state) or trigger (aka dispatch) an action directly.
I know this is a very old thread, but no one mentioned which to me is the cleanest answer:
echo -n $str | tail -c 1
Note the -n
is just so the echo doesn't include a newline at the end.
// @param db, readable database from SQLiteOpenHelper
public boolean doesTableExist(SQLiteDatabase db, String tableName) {
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
You can use array.nbytes
for numpy arrays, for example:
>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192
An alternative approach to those described above would be to create an external agent using java.lang.instrument
to find out what classes are loaded and run your program with the -javaagent
switch:
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class SimpleTransformer implements ClassFileTransformer {
public SimpleTransformer() {
super();
}
public byte[] transform(ClassLoader loader, String className, Class redefiningClass, ProtectionDomain domain, byte[] bytes) throws IllegalClassFormatException {
System.out.println("Loading class: " + className);
return bytes;
}
}
This approach has the added benefit of providing you with information about which ClassLoader loaded a given class.
For future Googlers, If you get an error similar below after you trigger click for a polygon
"Uncaught TypeError: Cannot read property 'vertex' of undefined"
then try the code below
google.maps.event.trigger(polygon, "click", {});
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
You had a unescaped "
in the onclick handler, escape it with \"
$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "' onclick=\"(canLaunch('" + v.LibraryItemId + " '))\">View »</a></div></div>")
Is maching set to CASE_INSENSITIVE?
This should work
<a href="javascript:window.open('document.aspx','mywindowtitle','width=500,height=150')">open window</a>
Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():
SELECT *
FROM (SELECT ID, SKU, Product,
ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
FROM MyTable
WHERE SKU LIKE 'FOO%') AS a
WHERE a.RowNumber = 1
It's easy with git add -i
. Type a
(for "add untracked"), then *
(for "all"), then q
(to quit) and you're done.
To do it with a single command: echo -e "a\n*\nq\n"|git add -i
I'd use popen() (++waqas).
But sometimes you need reading and writing...
It seems like nobody does things the hard way any more.
(Assuming a Unix/Linux/Mac environment, or perhaps Windows with a POSIX compatibility layer...)
enum PIPE_FILE_DESCRIPTERS
{
READ_FD = 0,
WRITE_FD = 1
};
enum CONSTANTS
{
BUFFER_SIZE = 100
};
int
main()
{
int parentToChild[2];
int childToParent[2];
pid_t pid;
string dataReadFromChild;
char buffer[BUFFER_SIZE + 1];
ssize_t readResult;
int status;
ASSERT_IS(0, pipe(parentToChild));
ASSERT_IS(0, pipe(childToParent));
switch (pid = fork())
{
case -1:
FAIL("Fork failed");
exit(-1);
case 0: /* Child */
ASSERT_NOT(-1, dup2(parentToChild[READ_FD], STDIN_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDOUT_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDERR_FILENO));
ASSERT_IS(0, close(parentToChild [WRITE_FD]));
ASSERT_IS(0, close(childToParent [READ_FD]));
/* file, arg0, arg1, arg2 */
execlp("ls", "ls", "-al", "--color");
FAIL("This line should never be reached!!!");
exit(-1);
default: /* Parent */
cout << "Child " << pid << " process running..." << endl;
ASSERT_IS(0, close(parentToChild [READ_FD]));
ASSERT_IS(0, close(childToParent [WRITE_FD]));
while (true)
{
switch (readResult = read(childToParent[READ_FD],
buffer, BUFFER_SIZE))
{
case 0: /* End-of-File, or non-blocking read. */
cout << "End of file reached..." << endl
<< "Data received was ("
<< dataReadFromChild.size() << "): " << endl
<< dataReadFromChild << endl;
ASSERT_IS(pid, waitpid(pid, & status, 0));
cout << endl
<< "Child exit staus is: " << WEXITSTATUS(status) << endl
<< endl;
exit(0);
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("read() failed");
exit(-1);
}
default:
dataReadFromChild . append(buffer, readResult);
break;
}
} /* while (true) */
} /* switch (pid = fork())*/
}
You also might want to play around with select() and non-blocking reads.
fd_set readfds;
struct timeval timeout;
timeout.tv_sec = 0; /* Seconds */
timeout.tv_usec = 1000; /* Microseconds */
FD_ZERO(&readfds);
FD_SET(childToParent[READ_FD], &readfds);
switch (select (1 + childToParent[READ_FD], &readfds, (fd_set*)NULL, (fd_set*)NULL, & timeout))
{
case 0: /* Timeout expired */
break;
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("Select() Failed");
exit(-1);
}
case 1: /* We have input */
readResult = read(childToParent[READ_FD], buffer, BUFFER_SIZE);
// However you want to handle it...
break;
default:
FAIL("How did we see input on more than one file descriptor?");
exit(-1);
}
You could use eventlet. It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.
Here's an example of a super minimal crawler:
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
shift()
is ideal for your situation. shift()
removes the first element from an array and returns that element. This method changes the length of the array.
array = [1, 2, 3, 4, 5];
array.shift(); // 1
array // [2, 3, 4, 5]
This issue is happening because you have installed jre1.8.0_101-1.8.0_101-fcs.i58.rpm as well jdk-1.7.0_80-fcs.x86_64.rpm. so just uninstall your jre rpm & restart your application. It should work out.
You need to achieve that using CSS
http://binnyva.blogspot.com/2006/01/icons-for-select-menu-options-in.html
This answer hopes to be a comprehensive wrap-up of information from other answers.
The very short version, given the data from the question plus a couple extras:
flat_array = [ apple, 1, banana, 2 ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [ apple, 1, banana ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana ] ] # count=2 of either k or k,v arrays
# there's one option for flat_array:
h1 = Hash[*flat_array] # => {apple=>1, banana=>2}
# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0 => {apple=>1, banana=>2}
h2b = Hash[nested_array] # => {apple=>1, banana=>2}
# ok if *only* the last value is missing:
h3 = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4 = Hash[incomplete_n] # or .to_h => {apple=>1, banana=>nil}
# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3 # => false
h3 == h4 # => true
Discussion and details follow.
In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:
a1
and a2
:(Note: I presume that apple
and banana
were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)
a1 = [ 'apple', 1 , 'banana', 2 ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input
a3
:In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:
a3 = [ [ 'apple', 1 ],
[ 'banana', 2 ],
[ ['orange','seedless'], 3 ],
[ 'pear', [4, 5] ],
]
a4
:For good measure, I thought I'd add one for a case where we might have an incomplete input:
a4 = [ [ 'apple', 1],
[ 'banana', 2],
[ ['orange','seedless'], 3],
[ 'durian' ], # a spiky fruit pricks us: no value!
]
a1
:Some have suggested using #to_h
(which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:
a1.to_h # => TypeError: wrong element type String at 0 (expected array)
Using Hash::[]
combined with the splat operator does:
Hash[*a1] # => {"apple"=>1, "banana"=>2}
So that's the solution for the simple case represented by a1
.
a2
:With an array of [key,value]
type arrays, there are two ways to go.
First, Hash::[]
still works (as it did with *a1
):
Hash[a2] # => {"apple"=>1, "banana"=>2}
And then also #to_h
works now:
a2.to_h # => {"apple"=>1, "banana"=>2}
So, two easy answers for the simple nested array case.
a3
:Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
a3.to_h # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
If we've gotten input data that's not balanced, we'll run into problems with #to_h
:
a4.to_h # => ArgumentError: wrong array length at 3 (expected 2, was 1)
But Hash::[]
still works, just setting nil
as the value for durian
(and any other array element in a4 that's just a 1-value array):
Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
a5
and a6
A few other answers mentioned flatten
, with or without a 1
argument, so let's create some new variables:
a5 = a4.flatten
# => ["apple", 1, "banana", 2, "orange", "seedless" , 3, "durian"]
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"]
I chose to use a4
as the base data because of the balance problem we had, which showed up with a4.to_h
. I figure calling flatten
might be one approach someone might use to try to solve that, which might look like the following.
flatten
without arguments (a5
):Hash[*a5] # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)
At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3
a key and durian
a value.
And this, as with a1
, just doesn't work:
a5.to_h # => TypeError: wrong element type String at 0 (expected array)
So a4.flatten
isn't useful to us, we'd just want to use Hash[a4]
flatten(1)
case (a6
):But what about only partially flattening? It's worth noting that calling Hash::[]
using splat
on the partially-flattened array (a6
) is not the same as calling Hash[a4]
:
Hash[*a6] # => ArgumentError: odd number of arguments for Hash
a6
):But what if this was how we'd gotten the array in the first place?
(That is, comparably to a1
, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6]
doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil
value?
In such a situation, there's still a way to do this, using Enumerable#each_slice
to get ourselves back to key/value pairs as elements in the outer array:
a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]]
Note that this ends up getting us a new array that isn't "identical" to a4
, but does have the same values:
a4.equal?(a7) # => false
a4 == a7 # => true
And thus we can again use Hash::[]
:
Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]
It's important to note that the each_slice(2)
solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:
a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # multi-value key
# ["durian"], # missing value
# ["lychee", 4]] # new well-formed item
a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]
a7_plus = a6_plus.each_slice(2).to_a
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # so far so good
# ["durian", "lychee"], # oops! key became value!
# [4]] # and we still have a key without a value
a4_plus == a7_plus # => false, unlike a4 == a7
And the two hashes we'd get from this are different in important ways:
ap Hash[a4_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => nil, # correct
"lychee" => 4 # correct
}
ap Hash[a7_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => "lychee", # incorrect
4 => nil # incorrect
}
(Note: I'm using awesome_print
's ap
just to make it easier to show the structure here; there's no conceptual requirement for this.)
So the each_slice
solution to an unbalanced flat input only works if the unbalanced bit is at the very end.
[key, value]
pairs (a sub-array for each item in the outer array).#to_h
or Hash::[]
will both work.Hash::[]
combined with the splat (*
) will work, so long as inputs are balanced.value
item is the only one that's missing.Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.
There are a lot of good answers here already. But for me it was hard to find some example, where the shape or array can break all the program.
So here is the one:
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(a,b)
This will fail with error:
ValueError: Expected 2D array, got 1D array instead
but if we add reshape
to a
:
a = np.array([1,2,3,4]).reshape(-1,1)
this works correctly!
You can use mbstring:
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
...will remove invalid characters.
See: Replacing invalid UTF-8 characters by question marks, mbstring.substitute_character seems ignored
change placeholder text using jquery
try this
$('#selector').attr("placeholder", "Type placeholder");
I know that what I do is quite the workaround, however it works perfectly and that is the way I do it everytime.
Then, proceed like this:
Cheers!
JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.
However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.
You can give yourself permissions to fix this problem.
Right click on cacerts > choose properties > select Securit tab > Allow all permissions to all the Group and user names.
This worked for me.
I use date.js. It handles this easily and takes care of all the leap-year nastiness.
Be careful with that.
But you can use the rebase command
git rebase -i HEAD~2
A vi
will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi
. A couple of things can be performed on this mode.
Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.
In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.
Without additional details on the specific error, it is difficult to provide more specific help.
UPDATE
CREATE TABLE ORD (
ORDID INT NOT NULL AUTO_INCREMENT,
//Rest of table code
PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;
This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.
Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.
ALTER TABLE ORD AUTO_INCREMENT = 622;
UPDATE 2
Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
var array = new Array();_x000D_
_x000D_
array.push('123');_x000D_
array.push('456');_x000D_
array.push('789');_x000D_
_x000D_
var _searchedIndex = $.inArray('456',array);_x000D_
alert(_searchedIndex );_x000D_
if(_searchedIndex >= 0){_x000D_
array.splice(_searchedIndex,1);_x000D_
alert(array );_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
_x000D_
Let's take a simple example. Let's say two tables named test
and customer
are there described as:
create table test(
test_id int(11) not null auto_increment,
primary key(test_id));
create table customer(
customer_id int(11) not null auto_increment,
name varchar(50) not null,
primary key(customer_id));
One more table is there which keeps the track of test
s and customer
:
create table tests_purchased(
customer_id int(11) not null,
test_id int(11) not null,
created_date datetime not null,
primary key(customer_id, test_id));
We can see that in the table tests_purchased
the primary key is a composite key, so we will use the <composite-id ...>...</composite-id>
tag in the hbm.xml
mapping file. So the PurchasedTest.hbm.xml
will look like:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entities.PurchasedTest" table="tests_purchased">
<composite-id name="purchasedTestId">
<key-property name="testId" column="TEST_ID" />
<key-property name="customerId" column="CUSTOMER_ID" />
</composite-id>
<property name="purchaseDate" type="timestamp">
<column name="created_date" />
</property>
</class>
</hibernate-mapping>
But it doesn't end here. In Hibernate we use session.load (entityClass
, id_type_object
) to find and load the entity using primary key. In case of composite keys, the ID object should be a separate ID class (in above case a PurchasedTestId
class) which just declares the primary key attributes like below:
import java.io.Serializable;
public class PurchasedTestId implements Serializable {
private Long testId;
private Long customerId;
// an easy initializing constructor
public PurchasedTestId(Long testId, Long customerId) {
this.testId = testId;
this.customerId = customerId;
}
public Long getTestId() {
return testId;
}
public void setTestId(Long testId) {
this.testId = testId;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
@Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof PurchasedTestId)) return false;
PurchasedTestId arg1 = (PurchasedTestId) arg0;
return (this.testId.longValue() == arg1.getTestId().longValue()) &&
(this.customerId.longValue() == arg1.getCustomerId().longValue());
}
@Override
public int hashCode() {
int hsCode;
hsCode = testId.hashCode();
hsCode = 19 * hsCode+ customerId.hashCode();
return hsCode;
}
}
Important point is that we also implement the two functions hashCode()
and equals()
as Hibernate relies on them.
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
Using jQuery:
var a = [1,2,3];
var b = [2,3,4,5];
var c = $(b).not($(b).not(a));
alert(c);
To make it simple,
To get host name,
hostname
or
uname -n
or
cat /etc/host
Output can be redirected to any file & read back from application
E.g.: # hostname > /usr/src//hostname.txt
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
You can pass the column name but you cannot use it in a sql statemnt like
Select @Columnname From Table
One could build a dynamic sql string and execute it like EXEC (@SQL)
For more information see this answer on dynamic sql.
you can use the download attribute on an a tag ...
<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
You can download winutils.exe here: http://public-repo-1.hortonworks.com/hdp-win-alpha/winutils.exe
Then copy it to your HADOOP_HOME/bin
directory.
Just change the "application/json" to "text/plain" and do not forget the JSON.stringify(request):
var request = {Company: sapws.dbName, UserName: username, Password: userpass};
console.log(request);
$.ajax({
type: "POST",
url: this.wsUrl + "/Login",
contentType: "text/plain",
data: JSON.stringify(request),
crossDomain: true,
});
choices = {'key1':'val1', 'key2':'val2'}
Here's the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
Basically, .items
is a Django keyword that splits a dictionary into a list of (key, value)
pairs, much like the Python method .items()
. This enables iteration over a dictionary in a Django template.
When you get in this state, try performing a Rebuild-All. If this fixes the problem, you may have the same issue I had.
Some background (my understanding):
SQLite has 1 managed assembly (System.Data.SQLite.dll) and several platform specific assemblies (SQLite.Interop.dll). When installing SQLite with Nuget, Nuget will add the platform specific assemblies to your project (within several folders: \x86, \x64), and configures these dlls to "Copy Always".
Upon load, the managed assembly will search for platform specific assemblies inside the \x86 and \x64 folders. You can see more on that here. The exception is this managed assembly attempting to find the relevant (SQLite.Interop.dll) inside these folders (and failing).
My Scenario:
I have 2 projects in my solution; a WPF app, and a class library. The WPF app references the class library, and the class library references SQLite (installed via Nuget).
The issue for me was when I modify only the WPF app, VS attempts to do a partial rebuild (realizing that the dependent dll hasn't changed). Somewhere in this process, VS cleans the content of the \x86 and \x64 folders (blowing away SQLite.Interop.dll). When I do a full Rebuild-All, VS copies the folders and their contents correctly.
My Solution:
To fix this, I ended up adding a Post-Build process using xcopy to force copying the \x86 and \x64 folders from the class library to my WPF project \bin directory.
Alternatively, you could do fancier things with the build configuration / output directories.
This is late to the game, but I built this recursive caster. It works for my needs and I think it's relatively complete. It may help you.
def _parseJSON(self, obj):
newobj = {}
for key, value in obj.iteritems():
key = str(key)
if isinstance(value, dict):
newobj[key] = self._parseJSON(value)
elif isinstance(value, list):
if key not in newobj:
newobj[key] = []
for i in value:
newobj[key].append(self._parseJSON(i))
elif isinstance(value, unicode):
val = str(value)
if val.isdigit():
val = int(val)
else:
try:
val = float(val)
except ValueError:
val = str(val)
newobj[key] = val
return newobj
Just pass it a JSON object like so:
obj = json.loads(content, parse_float=float, parse_int=int)
obj = _parseJSON(obj)
I have it as a private member of a class, but you can repurpose the method as you see fit.
This is from the lovely JavaScript library MooTools:
if (obj.nodeName){
switch (obj.nodeType){
case 1: return 'element';
case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
}
}
A feature to allow HTML for title and text parameters has been added with a recent merge into the master branch on GitHub https://github.com/t4t5/sweetalert/commit/9c3bcc5cb75e598d6faaa37353ecd84937770f3d
Simply use JSON configuration and set 'html' to true, eg:
swal({ html:true, title:'<i>TITLE</i>', text:'<b>TEXT</b>'});
This was merged less than a week ago and is hinted at in the README.md (html is set to false in one of the examples although not explicitly described) however it is not yet documented on the marketing page http://tristanedwards.me/sweetalert
To edit bashrc in Ubuntu
$ /usr/bin/vim ~/.bashrc
type PATH=$PATH:$HOME/anaconda3/bin
Press Esc and :wq
to save bashrc file and exit vim
enter image description here
then
$ export PATH=~/anaconda3/bin:$PATH
and type $ source ~/.bashrc
Now to confirm the installation of conda type
$ conda --version
clock()
returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC
, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
If you look at your original connection string:
<property name="url" value="jdbc:hsqldb:hsql://localhost"/>
The Hypersonic docs suggest that you're missing an alias after localhost:
If you're using ctx.drawImage()
function, you can do the following:
var img = loadImage('../yourimage.png', callback);
function loadImage(src, callback) {
var img = new Image();
img.onload = callback;
img.setAttribute('crossorigin', 'anonymous'); // works for me
img.src = src;
return img;
}
And in your callback you can now use ctx.drawImage
and export it using toDataURL
16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx
Use the STL find function.
Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if
would give you an iterator that points to the first such element).
You are facing issue in
s1.name="Paolo";
because, in the LHS, you're using an array type, which is not assignable.
To elaborate, from C11
, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy()
to copy into the array.
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.
Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.
You can use Case Insensitive Indexes:
The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode
/*
* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
To use the index, queries must specify the same collation.
db.users.insert( [ { name: "Oguz" },
{ name: "oguz" },
{ name: "OGUZ" } ] )
// does not use index, finds one result
db.users.find( { name: "oguz" } )
// uses the index, finds three results
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 2 } )
// does not use the index, finds three results (different strength)
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 1 } )
or you can create a collection with default collation:
db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation
You can achieve that with the help of Newtonsoft.Json. Install Newtonsoft.Json from Nuget and the :
using Newtonsoft.Json;
dynamic results = JsonConvert.DeserializeObject<dynamic>(YOUR_JSON);
I recommend you use a try/catch to prevent some possible issues:
OOP:
var preloadImage = function (url) {
try {
var _img = new Image();
_img.src = url;
} catch (e) { }
}
Standard:
function preloadImage (url) {
try {
var _img = new Image();
_img.src = url;
} catch (e) { }
}
Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.
Maybe I don't completely understand the accepted answer so it didn't work for me.
What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
because none of the options are selected, thus item = null
<%
if(item == null){
item = "selectedDept"; //known value from your database
}
%>
This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me
According to Github API two empty lines are a new paragraph (same as here in stackoverflow)
You can test it with http://prose.io
If you using ubuntu 14.04 here is the fix to this problem:
First check php5-mcryp is already installed apt-get install php5-mcrypt
If installed, just run this two command or install and run this two command
$ sudo php5enmod mcrypt
$ sudo service apache2 restart
I hope it will work.
You may use line-height on div1 as below:
<div id="div1" style="line-height:0px;">
<div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>
See this: http://jsfiddle.net/wCpU8/
$total_ratings
is an array, which you can't use for a division.
From above:
$total_ratings = mysqli_fetch_array($result);
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
Typically, software will run in different environments:
development
testing
staging
production
The dependencies which are declared in the require
section of composer.json
are typically dependencies which are required for running an application or a package in
staging
production
environments, whereas the dependencies declared in the require-dev
section are typically dependencies which are required in
developing
testing
environments.
For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:
friendsofphp/php-cs-fixer
(to detect and fix coding style issues)squizlabs/php_codesniffer
(to detect and fix coding style issues)phpunit/phpunit
(to drive the development using tests)Now, in development
and testing
environments, you would typically run
$ composer install
to install both production
and development
dependencies.
However, in staging
and production
environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run
$ composer install --no-dev
to install only production
dependencies.
In other words, the sections
require
require-dev
indicate to composer
which packages should be installed when you run
$ composer install
or
$ composer install --no-dev
That is all.
Note Development dependencies of packages your application or package depend on will never be installed
For reference, see:
you can also use
word-break: break-all;
when nothing seems working this works always ;)
Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:
<Window.Resources>
<CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>
The DataGrid line looks like this:
<DataGrid
DataContext="{StaticResource ItemCollectionViewSource}"
ItemsSource="{Binding}"
AutoGenerateColumns="False">
In the code behind, you link CollectionViewSource with your link.
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;
For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
As far as .net languages go, VS is hard to beat.
I have used SharpDevelop before for .net, and is overall pretty good.
For other languages like Java, Eclipse is really good, as well as some of the Eclipse variants like Aptana for web work.
Then there's always notepad...
Inculding all impressive answers the expert developers specially Ribamar Santos
provided, if you didn't get it working, you must check something more tricky!
Something like Airplane mode
of your (emulated) phone! Or your network status of Emulator
(Data status and Voice status on Cellular tab of Emulator configuration
) that might be manipulated to don't express network! for some emulation needs!
I've overcome to this problem by this trick! It was a bit breathtaking debug to find this hole!
I know this is old, but for those having problems in Edge:
Plain JS: window.scrollTop=0;
Unfortunately, scroll()
and scrollTo()
throw errors in Edge.
I hit the same issue and none of the solutions worked. I then bumped an answer in stackexchange dba which lead to this link. So here is what I did:
sudo mysqld_safe --skip-grant-tables --skip-networking &
sudo mysql -uroot
and got into mysql consoleALTER USER root@localhost identified via unix_socket;
and flush privileges;
consecutively to allow for password-less loginIf you want to set the password then you need to do one more step, that is running ALTER USER root@localhost IDENTIFIED VIA mysql_native_password;
and SET PASSWORD = PASSWORD('YourPasswordHere');
consecutively.
UPDATE
Faced this issue recently and here is how I resolved it with recent version, but before that some background. Mariadb does not require a password when is run as root. So first run it as a root. Then once in the Mariadb console, change password there. If you are content with running it as admin, you can just keep doing it but I find that cumbersome especially because I cannot use that with DB Admin Tools. TL;DR here is how I did it on Mac (should be similar for *nix systems)
sudo mariadb-secure-installation
then follow instructions on the screen!
Hope this will help someone and serve me a reference for future problems
I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:
self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
print("You clicked with event = {}".format(trigger_event))
Comparing the following two ways of coding a button click:
btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))
The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"
We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:
btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))
Output:
Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3
I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:
FOR /F "tokens=*" %G IN ('dir /b') DO robocopy "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0
As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.
It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.
From: jQuery text truncation (read more style)
Try this:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
And you can also use a plugin:
As a extension of String
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Use as
"This is your title".trimToLength(10);
check this, you should give arguments in msecs, Dont just send progress
to seekTo(int)
and also check this getCurrentPostion() and getDuration().
You can do some calcuations, ie., convert progress
in msec like msce = (progress/100)*getDuration()
then do seekTo(msec)
Or else i have an easy idea, you don't need to change any code anywer else just add seekBar.setMax(mPlayer.getDuration())
once your media player is prepared.
and here is link exactly what you want seek bar update
I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.
Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.
For all those interested in concatenation with the requirejs optimizer, check out this post
Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS
I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me
$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7
It looks like Microsoft invaded brains of all other respondents and made them write as complicated solutions as possible. Here is the simplest way without any additional functions/declare statements:
SELECT geography::Point(LATITUDE_1, LONGITUDE_1, 4326).STDistance(geography::Point(LATITUDE_2, LONGITUDE_2, 4326))
Simply substitute your data instead of LATITUDE_1
, LONGITUDE_1
, LATITUDE_2
, LONGITUDE_2
e.g.:
SELECT geography::Point(53.429108, -2.500953, 4326).STDistance(geography::Point(c.Latitude, c.Longitude, 4326))
from coordinates c
this worked for me!
if some_queryset.objects.all().exists(): print("this table is not empty")
In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.
None of the answers here satisfies my needs.
The answer from Muno is wrong because it lists ONLY the USB ports.
The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)
I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.
My code has been tested on Windows XP, Windows 7 and Windows 10.
The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).
If you use my code you do not need SerialPort.GetPortNames()
anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??
using System.Management;
using Microsoft.Win32;
using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
foreach (ManagementObject i_Inst in i_Entity.GetInstances())
{
Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
continue; // Skip all devices except device class "PORTS"
String s_Caption = i_Inst.GetPropertyValue("Caption") .ToString();
String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
String s_RegPath = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();
int s32_Pos = s_Caption.IndexOf(" (COM");
if (s32_Pos > 0) // remove COM port from description
s_Caption = s_Caption.Substring(0, s32_Pos);
Console.WriteLine("Port Name: " + s_PortName);
Console.WriteLine("Description: " + s_Caption);
Console.WriteLine("Manufacturer: " + s_Manufact);
Console.WriteLine("Device ID: " + s_DeviceID);
Console.WriteLine("-----------------------------------");
}
}
I tested the code with a lot of COM ports. This is the Console output:
Port Name: COM29
Description: CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID: USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name: COM28
Description: Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID: USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name: COM25
Description: USB-SERIAL CH340
Manufacturer: wch.cn
Device ID: USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name: COM26
Description: Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID: USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name: COM1
Description: Comunications Port
Manufacturer: (Standard port types)
Device ID: ACPI\PNP0501\1
-----------------------------------
Port Name: COM999
Description: EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID: ROOT\PORTS\0000
-----------------------------------
Port Name: COM20
Description: EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID: ROOT\PORTS\0001
-----------------------------------
Port Name: COM8
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name: COM9
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name: COM30
Description: Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID: USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------
COM1 is a COM port on the mainboard.
COM 8 and 9 are Buetooth COM ports.
COM 25 and 26 are USB to RS232 adapters.
COM 28 and 29 and 30 are Arduino-like boards.
COM 20 and 999 are EPSON ports.
You might need to convert the decimal
to money
(or decimal(8,2)
) to get that exact formatting. The convert
method can take a third parameter that controls the formatting style:
convert(varchar, cast(price as money)) 12345.67
convert(varchar, cast(price as money), 0) 12345.67
convert(varchar, cast(price as money), 1) 12,345.67
Security Warning:
md5(uniqid(rand(), TRUE))
is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.
Looks like you need an else with your if.
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
}
else
{
$token = $_SESSION['token'];
}
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
OK, here's my best pseudo math:
The equation for your line is:
Y = a + bX
Where:
b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
a = sum(y)/n - b(sum(x)/n)
Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)
... and now with added Sigma
b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)
a = (Σy)/n - b((Σx)/n)
Where Σ(xy) is the sum of all x*y etc. and n is the number of points
A query like this will also cause the error:
SELECT table1.id FROM table2
Where the table is specified in column select and not included in the from clause.
I use rank
:
rum <- read.table(textConnection("P1 P2 P3 T1 T2 T3 I1 I2
2 3 5 52 43 61 6 b
6 4 3 72 NA 59 1 a
1 5 6 55 48 60 6 f
2 4 4 65 64 58 2 b
1 5 6 55 48 60 6 c"), header = TRUE)
> rum[order(rum$I1, -rank(rum$I2), decreasing = TRUE), ]
P1 P2 P3 T1 T2 T3 I1 I2
1 2 3 5 52 43 61 6 b
5 1 5 6 55 48 60 6 c
3 1 5 6 55 48 60 6 f
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a
This is a ternary operator, it's basically an inline if statement
x ? y : z
works like
if(x) y else z
except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.
It's useful for writing succinct code, but can be overused to create hard to maintain code.
I had the same issue when trying to use php composer install
in a local directory on my Apache server for a laravel project I cloned from Github. My problem was I had already setup composer
globally on my Ubuntu 18 machine.
Adding sudo
instead of php
started the install of a whole slew of packages listed in the json.lock
file i.e. sudo composer install
.
DateTime
objects have the Kind
of Unspecified
by default, which for the purposes of ToLocalTime
is assumed to be UTC
.
To get the local time of an Unspecified
DateTime
object, you therefore just need to do this:
convertedDate.ToLocalTime();
The step of changing the Kind
of the DateTime
from Unspecified
to UTC
is unnecessary. Unspecified
is assumed to be UTC
for the purposes of ToLocalTime
: http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx
Use this.getClass().getCanonicalName()
to get the full class name.
Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.
Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?
Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.
tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.
Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.
hth! Regards, Remco
It's like this:
$('.tag.clickedTag').click(function (){
// this will catch with two classes
}
$('.tag.clickedTag.otherclass').click(function (){
// this will catch with three classes
}
$('.tag:not(.clickedTag)').click(function (){
// this will catch tag without clickedTag
}
The SQL script was originally created on a Windows OS. The '^M' characters are a result of Windows and Unix having different ideas about what to use for an end-of-line character. You can use perl at the command line to fix this.
perl -pie 's/\r//g' filename.txt
Try it:
git gc --prune=now
git remote prune origin
git pull
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
This will convert it to an int:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.
#include <termios.h>
#include <stdio.h>
static struct termios old, current;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */
if (echo) {
current.c_lflag |= ECHO; /* set echo mode */
} else {
current.c_lflag &= ~ECHO; /* set no echo mode */
}
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Output:
(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
After going through all the answers and executing most of them. Although I resisted to try the Restart magic, eventually, the issue is solved after restart on my macbook(MacOS Catalina Ver. 10.15.7).
It seems like a cache issue indeed but none of the commands that I have executed cleared the cache.
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {}
orPartial<User>
, or you need to redefine theUser
type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalz
I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Username
is left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "[email protected]";
Here is a working example for you.
Just create the header.php file, and where you want to use it do:
<?php
include('header.php');
?>
Same with the footer. You don't need php tags in these files if you just have html.
See more about include here:
import java.io.*;
class Main
{
public static void main(String args[]) throws IOException
{
int n1,n2,n3,l;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
n3=Integer.parseInt(args[2]);
if(n1>n2)
{
l=n1;
}
else
{
l=n2;
}
if(l<n3)
{
System.out.println("largest no is "+n3);
}
else
{
System.out.println("largest no is "+l);
}
}}
Consider above program, in this program I want to pass 3 no's from Command Line, to do so.
Step 1 : Right Click on Cup and Saucer icon, u'll see this window
Step 2: Click on Properties
Step 3: Click Run _> Arguments _> type three no's eg. 32 98 16 then click OK. Plz add space between two arguments. See here
Step 4: Run the Program by using F6.
Apart from what it's written in other answers, other details related to path of cookie, maximum age of cookie, whether it's secured or not also passed in Set-Cookie response header. For instance:
Set-Cookie:
name=
value[; expires=
date][; domain=
domain][; path=
path][; secure
]
However, not all of these details are passed back to the server by the client when making next HTTP request.
You can also set HttpOnly
flag at the end of your cookie, to indicate that your cookie is httponly and must not allowed to be accessed, in scripts by javascript code. This helps to prevent attacks such as session-hijacking.
For more information, see RFC 2109. Also have a look at Nicholas C. Zakas's article, HTTP cookies explained.
You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.
w.strip(',.').lower()
A simple way but dangerous way to do this would be to use eval()
. eval()
executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:
import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
print eval(s)
else:
print "Try entering a math problem"
Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.
Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.
Map is Select
:
Enumerable.Range(1, 10).Select(x => x + 2);
Reduce is Aggregate
:
Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
Filter is Where
:
Enumerable.Range(1, 10).Where(x => x % 2 == 0);
JAVA_OPTS
is environment variable used by tomcat in its startup/shutdown script to configure params.
You can set it in linux by
export JAVA_OPTS="-Djava.awt.headless=true"
I'm on debian, I found something quite natural to do :
apt-get install docker-compose
and it did the job (not tested on centos)
I had the same issue. The problem is that pip install tries to use C:\Users(username)\AppData\Local\Temp to unpack. You have to explicitly set those directories to R/W.I still couldn't do it because it was a work laptop and there were some permissions issues with trying to set these directories to R/W. The alternative is to go to your Env Variables, and set both Tmp and Temp to point to a writeable directory such as C:. The installation went fine. I was able to install pip.
The way I stumbled onto this is by not defaulting pip install in my installation. Even though the pip install was failing, the installer was not giving any errors. Removing pip and then trying to manually add it later is what pointed to what was going on.
For SQL server 2012,
First, log in to the SQL server as an administrator and go to Security tab
Then move into Server Roles and double click on sysadmin role
Now add user which you want to give permission to create Database by clicking Add button
Click OK button and now run the query
Hope this will help for someone
You can delete small batches using a while loop, something like this:
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
WHILE @@ROWCOUNT > 0
BEGIN
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
END
return;
will exit a method in C#.
See code snippet below
using System;
namespace Exercise_strings
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input string separated by -");
var stringInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(stringInput))
{
Console.WriteLine("Nothing entered");
return;
}
}
So in this case if a user enters a null string or whitespace, the use of the return method terminates the Main method elegantly.
The question is relatively old, but I hope this post still might be relevant for others.
TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;
Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.
Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.
First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<Button
android:id="@+id/sendNotifications"
android:onClick="onSendNotificationsButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Sending Notifications Every 2 Hours!" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onSendNotificationsButtonClick(View view) {
NotificationEventReceiver.setupAlarm(getApplicationContext());
}
}
and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.
Then let's create WakefulBroadcastReceiver
broadcast receiver, I called NotificationEventReceiver in code above.
Here, we'll set up AlarmManager
to fire PendingIntent
every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive()
method. In our case - wakefully start IntentService
, which we'll specify in the later steps. This IntentService
would generate notifications for us.
Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later
NB1! As I'm using WakefulBroadcastReceiver
, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />
NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService
's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.
NotificationEventReceiver.java
public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
alarmIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
startWakefulService(context, serviceIntent);
}
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Now let's create an IntentService
to actually create notifications.
There, we specify onHandleIntent()
which is responses on NotificationEventReceiver's intent we passed in startWakefulService
method.
If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder
we're composing new notification and showing it by NotificationManager.notify
. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.
NotificationIntentService.java
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_START);
return intent;
}
public static Intent createIntentDeleteNotification(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_DELETE);
return intent;
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
try {
String action = intent.getAction();
if (ACTION_START.equals(action)) {
processStartNotification();
}
if (ACTION_DELETE.equals(action)) {
processDeleteNotification(intent);
}
} finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processDeleteNotification(Intent intent) {
// Log something?
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification")
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText("This notification has been triggered by Notification Service")
.setSmallIcon(R.drawable.notification_icon);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID,
new Intent(this, NotificationActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).
NotificationServiceStarterReceiver.java
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
We need to also register all our services, broadcast receivers in AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="klogi.com.notificationbyschedule">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".notifications.NotificationIntentService"
android:enabled="true"
android:exported="false" />
<receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
<receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<activity
android:name=".NotificationActivity"
android:label="@string/title_activity_notification"
android:theme="@style/AppTheme.NoActionBar"/>
</application>
</manifest>
The source code for this project you can find here. I hope, you will find this post helpful.
SELECT DISTINCT
FIRST_VALUE(ID) OVER (Partition by Game ORDER BY Point) AS ID,
Game,
FIRST_VALUE(Point) OVER (Partition by Game ORDER BY Point) AS Point
FROM #T
to echo @friederbluemle, you can also just launch the SDK manager from the command line if you have the Android SDK tools installed:
$ android
and then in the UI that pops up, select the tools/repositories that need to be installed -- in your case the support library repo
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy
, then you could do the following:
...
strcpy( ... , (char[2]) { (char) c, '\0' } );
...
The (char[2]) { (char) c, '\0' }
part will temporarily generate null-terminated string out of a character c
.
This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.
This topic is old but if other people like me search a solution, this is a solution that I have found:
Public Function DBStats() As Boolean
On Error GoTo errorHandler
If Not IsNull(myBase.Version) Then
DBStats = True
End If
Exit Function
errorHandler:
DBStats = False
End Function
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
Using Html Agility Pack as suggested by SLaks, this becomes very easy:
string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");
You can create files in browser using Blob
and URL.createObjectURL
. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download
attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea
.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?
Just call Canvas.drawColor(Color.BLACK)
, or whatever color you want to clear your Canvas
with.
And: how can I update just a part of the screen ?
There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas
, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.
So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor()
method.
With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property
and source='field'
raise an error.
class Foo(models.Model):
. . .
def foo(self):
return 'stuff'
. . .
class FooSerializer(ModelSerializer):
foo = serializers.ReadOnlyField()
class Meta:
model = Foo
fields = ('foo',)
require 5.013002; # or better: use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";
See perl5132delta:
The substitution operator now supports a
/r
option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.
my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'
Try adding the line c = cv.WaitKey(10)
at the bottom of your repeat()
method.
This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so time.sleep(10)
may also work.
In regards to the camera index, you could do something like this:
for i in range(3):
capture = cv.CaptureFromCAM(i)
if capture: break
This will find the index of the first "working" capture device, at least for indices from 0-2. It's possible there are multiple devices in your computer recognized as a proper capture device. The only way I know of to confirm you have the right one is manually looking at your light. Maybe get an image and check its properties?
To add a user prompt to the process, you could bind a key to switching cameras in your repeat loop:
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
if(c=="n"): #in "n" key is pressed while the popup window is in focus
camera_index += 1 #try the next camera index
capture = cv.CaptureFromCAM(camera_index)
if not capture: #if the next camera index didn't work, reset to 0.
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
while True:
repeat()
disclaimer: I haven't tested this so it may have bugs or just not work, but might give you at least an idea of a workaround.
I noticed there are two ways to change/specify legend.title for ggboxplot():
library(ggpubr)
bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco")
# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco", legend.title="Dose (mg)")
# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <- bxp.defaultLegend + labs(color = "Dose (mg)") +
theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))
ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3, common.legend = TRUE)
The code is modified based on the example from GitHub.
please check the below edited code:-
#!/bin/bash
export num1=(3.17648*e-22)
export num2=1.5
st=$((`echo "$num1 < $num2"| bc`))
if [ $st -eq 1 ]
then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
this works well.
An application that I've found indispensible as an alternative is DTerm, which actually opens a mini terminal right in your application. Plus it works with just about everything out there - Finder, XCode, PhotoShop, etc.
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
In some cases you might end up having chain of observables, wherein your observable would return another observable. 'flatmap' kind of unwraps the second observable which is buried in the first one and let you directly access the data second observable is spitting out while subscribing.
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".
sys.argv
is the list of arguments passed to the Python program. The first argument, sys.argv[0]
, is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0]
exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1]
is thus the first argument you actually pass to the program.
Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1]
.
Since I landed here when looking for a solution to my own problem, I'll share my solution here, in case others land here as well.
I was connecting fine to SQL Server until my machine was moved to another office on another domain. Then, after the switch, I was getting this error regarding the target principal name. What fixed it was connecting using a fully qualified name such as: server.domain.com. And actually, once I connected to the first server that way, I could connect to other servers using just the server name (without the full qualification), but your mileage may vary.
Your original attempt to span both tables creates an implicit JOIN. This is frowned upon by most experienced SQL programmers because it separates the tables to be combined with the condition of how.
The UNION
is a good solution for the tables as they are, but there should be no reason they can't be put into the one table with decent indexing. I've seen adding the correct index to a large table increase query speed by three orders of magnitude.
es6 for...in
for(const index in [15, 64, 78]) {
console.log(index);
}
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
As an addendum: Before HTML 5 while a div inside a li is valid, a div inside a dl, dd, or dt is not!
The original answer of ????? ???????? had an issue, so on the last cell collection view was scrolling to the beginning
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
targetContentOffset.pointee = scrollView.contentOffset
var indexes = yourCollectionView.indexPathsForVisibleItems
indexes.sort()
var index = indexes.first!
// if velocity.x > 0 && (Get the number of items from your data) > index.row + 1 {
if velocity.x > 0 && yourCollectionView.numberOfItems(inSection: 0) > index.row + 1 {
index.row += 1
} else if velocity.x == 0 {
let cell = yourCollectionView.cellForItem(at: index)!
let position = yourCollectionView.contentOffset.x - cell.frame.origin.x
if position > cell.frame.size.width / 2 {
index.row += 1
}
}
yourCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
}
By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as
An instance variable would probably be the way to do what you want. You could make it static to persist the same value for the life of the program (or thread depending on your static memory model), or make it an ordinary instance var to control it over the life of an object instance. If that instance is a singleton, they'll behave the same way.
#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif
void foo()
{
// ...
#if DEBUG
if (s_bDoDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
#endif
// ...
}
Just to be complete, pragmas (preprocessor directives) are considered a bit of a kludge to use to control program flow. .NET has a built-in answer for half of this problem, using the "Conditional" attribute.
private /*static*/ bool doDebugOnlyCode = false;
[Conditional("DEBUG")]
void foo()
{
// ...
if (doDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
// ...
}
No pragmas, much cleaner. The downside is that Conditional can only be applied to methods, so you'll have to deal with a boolean variable that doesn't do anything in a release build. As the variable exists solely to be toggled from the VS execution host, and in a release build its value doesn't matter, it's pretty harmless.
Try something like this... jsfiddle demo
HTML
<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>
JS
$(document).ready(function () {
$("#source").change(function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
One addendum to the excellent answers above, on a point that confused me even after I had read Stroustrup and thought I understood the rvalue/lvalue distinction. When you see
int&& a = 3
,
it's very tempting to read the int&&
as a type and conclude that a
is an rvalue. It's not:
int&& a = 3;
int&& c = a; //error: cannot bind 'int' lvalue to 'int&&'
int& b = a; //compiles
a
has a name and is ipso facto an lvalue. Don't think of the &&
as part of the type of a
; it's just something telling you what a
is allowed to bind to.
This matters particularly for T&&
type arguments in constructors. If you write
Foo::Foo(T&& _t) : t{_t} {}
you will copy _t
into t
. You need
Foo::Foo(T&& _t) : t{std::move(_t)} {}
if you want to move. Would that my compiler warned me when I left out the move
!
Another thing to mention is that atan2
is more stable when computing tangents using an expression like atan(y / x)
and x
is 0 or close to 0.
Since there are so many ways to delete a word, let's illustrate them.
Assuming you edit:
foo-bar quux
and invoke a command while the cursor is on the 'a' in 'bar':
foo-bquux # dw: letters then spaces right of cursor
foo-quux # daw: letters on both sides of cursor then spaces on the right
foo- quux # diw: letters on both sides of cursor
foo-bquux # dW: non-whitespace then spaces right of cursor
quux # daW: non-whitespace on both sides of cursor then spaces on the right
quux # diW: non-whitespace on both sides of cursor
The errors in ASP.Net are saved on the Server.GetLastError property,
Or i would put a label on the asp.net page for displaying the error.
try
{
do something
}
catch (YourException ex)
{
errorLabel.Text = ex.Message;
errorLabel.Visible = true;
}
using System;
using System.Text;
public static class Base64Conversions
{
public static string EncodeBase64(this string text, Encoding encoding = null)
{
if (text == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = encoding.GetBytes(text);
return Convert.ToBase64String(bytes);
}
public static string DecodeBase64(this string encodedText, Encoding encoding = null)
{
if (encodedText == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = Convert.FromBase64String(encodedText);
return encoding.GetString(bytes);
}
}
Usage
var text = "Sample Text";
var base64 = text.EncodeBase64();
base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding
http://sourceforge.net/projects/javacsv/
https://github.com/pupi1985/JavaCSV-Reloaded
(fork of the previous library that will allow the generated output to have Windows line terminators \r\n
when not running Windows)
http://opencsv.sourceforge.net/
Can you recommend a Java library for reading (and possibly writing) CSV files?
I was having the same issue, this worked for me https://github.com/webpack/webpack/issues/1468
Yes, as said by Thanakron Tandavas,
Recursion is good when you are solving a problem that can be solved by divide and conquer technique.
For example: Towers of Hanoi
Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri
documentation for the array index method:
--------------------------------------------------------------- Array#[]
array[index] -> obj or nil
array[start, length] -> an_array or nil
array[range] -> an_array or nil
array.slice(index) -> obj or nil
array.slice(start, length) -> an_array or nil
array.slice(range) -> an_array or nil
------------------------------------------------------------------------
Element Reference---Returns the element at index, or returns a
subarray starting at start and continuing for length elements, or
returns a subarray specified by range. Negative indices count
backward from the end of the array (-1 is the last element).
Returns nil if the index (or starting index) are out of range.
a = [ "a", "b", "c", "d", "e" ]
a[2] + a[0] + a[1] #=> "cab"
a[6] #=> nil
a[1, 2] #=> [ "b", "c" ]
a[1..3] #=> [ "b", "c", "d" ]
a[4..7] #=> [ "e" ]
a[6..10] #=> nil
a[-3, 3] #=> [ "c", "d", "e" ]
# special cases
a[5] #=> nil
a[6, 1] #=> nil
a[5, 1] #=> []
a[5..10] #=> []
Button won't submit form on its own.It is a simple button which is used to perform some operation by using javascript whereas Submit is a kind of button which by default submit the form whenever user clicks on submit button.
What you have is correct, but this is more consice:
^[A-Z]{3}$
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
As @avp says the bash line pip install seaborn
should work
I just had the same problem and and restarting the notebook didn't seem to work but running the command as jupyter line magic was a neat way to fix the problem without restarting the notebook
Jupyter Code-Cell:
%%bash
pip install seaborn
I just tried it, commenting super(); does the same thing without commenting it as @Mark Peters said
package javaapplication6;
/**
*
* @author sborusu
*/
public class Super_Test {
Super_Test(){
System.out.println("This is super class, no object is created");
}
}
class Super_sub extends Super_Test{
Super_sub(){
super();
System.out.println("This is sub class, object is created");
}
public static void main(String args[]){
new Super_sub();
}
}
Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.
After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):
index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.
from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.
EDIT 10/20/2014 - More information
I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:
If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...
Ordinarily, you can achieve this behavior using the index_col option.
There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...
They are the same. Boolean helps simplify conversion back and forth between C# and VB.Net. Most C# programmers tend to prefer 'bool', but if you are in a shop where there's a lot of both VB.Net and C# then you may prefer Boolean because it works in both places.
Decode it with the unicode-escape
codec:
>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…
This is because for a non-unicode string the \u2026
is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'
). You need to decode the escapes, and the unicode-escape
codec can do that for you.
Note that you can get unicode
to recognise it in the same way by specifying the codec argument:
>>> unicode(a, 'unicode-escape')
u'Hello\u2026'
But the a.decode()
way is nicer.
On newer versions of OS X you should find ALL JREs (and JDKs) under
/Library/Java/JavaVirtualMachines/
/System/Library/Java/JavaVirtualMachines/
the old path
/System/Library/Frameworks/JavaVM.framework/
has been deprecated.
Here is the official deprecation note:
git reset --hard && git clean -dfx
or, zsh provides a 'gpristine' alias:
alias gpristine='git reset --hard && git clean -dfx'
Which is really handy. (warning: The "-x" will also delete 'git ignored' files, so remove this if it is not what you want)
If working on a forked repo, make sure to fetch and reset from the correct repo/branch, for example:
git fetch upstream && git reset --hard upstream/master && git clean -df
Firstly, I would try a non-secure websocket connection. So remove one of the s
's from the connection address:
conn = new WebSocket('ws://localhost:8080');
If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080
both in TCP_IN
and TCP_OUT
.
You could put it in a function.
String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);
private Runnable createRunnable(final String paramStr){
Runnable aRunnable = new Runnable(){
public void run(){
someFunc(paramStr);
}
};
return aRunnable;
}
(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)
Don't mutate the state in place. It can cause unexpected results. I have learned my lesson! Always work with a copy/clone, Object.assign()
is a good one:
item = Object.assign({}, this.state.items[1], {name: 'newName'});
items[1] = item;
this.setState({items: items});
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
I had this same error, even when I only had one child under the TouchableHighlight
. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/
This question has already great answers, but here it appears that there is a slight confusion between using single equal (=
) and double equals (==
) in
if [ "$s1" == "$s2" ]
The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash
in the starting of the script and save your script as filename.bash
. To execute, use bash filename.bash
- then you have to use ==
.
If you are using sh then use #!/bin/sh
and save your script as filename.sh
. To execute use sh filename.sh
- then you have to use single =
. Avoid intermixing them.
Check to make sure there is a film release date; if the date is missing you will not be able to format on a non-object.
if ($info['Film_Release']){ //check if the date exists
$dateFromDB = $info['Film_Release'];
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y');
} else {
$newDate = "none";
}
or
$newDate = ($info['Film_Release']) ? DateTime::createFromFormat("l dS F Y", $info['Film_Release'])->format('d/m/Y'): "none"
Mock data:
df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]
Group Apple Orange
0 A 0.465636 0.537723
1 A 0.560537 0.727238
2 A 0.268154 0.648927
3 B 0.722644 0.115550
4 C 0.586346 0.042896
5 B 0.562881 0.369686
6 B 0.395236 0.672477
7 C 0.577949 0.358801
8 A 0.764069 0.642724
9 C 0.731076 0.302369
You can use the Seaborn library for these plots. First melt
the dataframe to format data and then create the boxplot of your choice.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')
In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &
An example of doing this in a partial package.json file:
{
"name": "npm-scripts-forking-example",
"scripts": {
"bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
"serve": "http-server -c 1 -a localhost",
"serve-bundle": "npm run bundle & npm run serve &"
}
You'd then execute them both in parallel via npm run serve-bundle
. You can enhance the scripts to output the pids of the forked process to a file like so:
"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",
Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:
If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:
Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs
to streams
.
I ran into this annoying issue with the Play framework. It would be nice if there was some way of knowing what build errors Eclipse is unhappy about, but it's not going to tell you. With one project, I was able to close the project, rebuild the Eclipse configuration with sbt eclipse
, and reopen. With an almost identical project, that didn't work. But deleting the project, rebuilding the Eclipse configuration with sbt eclipse
, and importing, did the trick.
++i
is a pre-increment; i++
is post-increment.
The downside of post-increment is that it generates an extra value; it returns a copy of the old value while modifying i
. Thus, you should avoid it when possible.
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'the_username',
password: 'the_password'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
Similarly you can do post, such as:
axios({
method: 'post',
url: 'https://your.service.org/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Similarly you can use SuperAgent.
superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
And if you want to do basic authentication:
superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
use this css.
.roundbutton{_x000D_
display:block;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
border-radius: 50%;_x000D_
border: 1px solid red;_x000D_
_x000D_
}
_x000D_
<a class="roundbutton" href="#"><i class="ion-ios-arrow-down"></i></a>
_x000D_
Both the answers provided above work fine.
You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.
A simple example:
=IF(B1=0;"";A1/B1)
This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.
In your case of running an average, you could check to see whether or not your data set has a value:
=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))
If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.
I think your assignment is backwards:
a[i] = b[i];
should be:
b[i] = a[i];
To get something like this
with Bootstrap 3 and Jquery use the following HTML code:
<div class="btn-group">
<input id="searchinput" type="search" class="form-control">
<span id="searchclear" class="glyphicon glyphicon-remove-circle"></span>
</div>
and some CSS:
#searchinput {
width: 200px;
}
#searchclear {
position: absolute;
right: 5px;
top: 0;
bottom: 0;
height: 14px;
margin: auto;
font-size: 14px;
cursor: pointer;
color: #ccc;
}
and Javascript:
$("#searchclear").click(function(){
$("#searchinput").val('');
});
Of course you have to write more Javascript for whatever functionality you need, e.g. to hide the 'x' if the input is empty, make Ajax requests and so on. See http://www.bootply.com/121508
We can use another way to edit files inside working containers (this won't work if container is stoped).
Logic is to:
-)copy file from container to host
-)edit file on host using its host editor
-)copy file back to container
We can do all this steps manualy, but i have written simple bash script to make this easy by one call.
/bin/dmcedit:
#!/bin/sh
set -e
CONTAINER=$1
FILEPATH=$2
BASE=$(basename $FILEPATH)
DIR=$(dirname $FILEPATH)
TMPDIR=/tmp/m_docker_$(date +%s)/
mkdir $TMPDIR
cd $TMPDIR
docker cp $CONTAINER:$FILEPATH ./$DIR
mcedit ./$FILEPATH
docker cp ./$FILEPATH $CONTAINER:$FILEPATH
rm -rf $TMPDIR
echo 'END'
exit 1;
Usage example:
dmcedit CONTAINERNAME /path/to/file/in/container
The script is very easy, but it's working fine for me.
Any suggestions are appreciated.
If you are creating an array then there is no difference, however, the following is neater:
String[] suit = {
"spades",
"hearts",
"diamonds",
"clubs"
};
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"});
myMethod({"spades", "hearts"}); //won't compile!
If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:
protected static function getMethod($name) {
$class = new ReflectionClass('MyClass');
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
public function testFoo() {
$foo = self::getMethod('foo');
$obj = new MyClass();
$foo->invokeArgs($obj, array(...));
...
}
If you already have filled columns and have added new one or you want to fill out old column with new mock values , do this:
public function up()
{
DB::table('foydabars')->update(
array(
'status' => '0'
)
);
}
What would be wrong with doing;
<div className="" key={index}>
{i.title}
</div>
[/*Use IIFE */]
{(function () {
if (child.children && child.children.length !== 0) {
let menu = createMenu(child.children);
console.log("nested menu", menu);
return menu;
}
})()}
I am a big fan of DB4O for both .Net and Java.
Performance has become much better since the early releases. The licensing model isnt too bad, either. I particularly like the options available for querying your objects. Query by example is very powerful and easy to get used to.