changing the owner of folder in linux
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also
You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
How to determine if a string is a number with C++?
bool is_number(const string& s, bool is_signed)
{
if (s.empty()) return false;
if (is_signed && (s.front() == '+' || s.front() == '-'))
{
return is_number(s.substr(1, s.length() - 1), false);
}
auto non_digit = std::find_if(s.begin(), s.end(), [](const char& c) { return !std::isdigit(c); });
return non_digit == s.end();
}
How to convert string to char array in C++?
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0'; // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0'; // before C++11 (safe)
It's a better practice to avoid C in C++, so std::string::copy should be the choice instead of strcpy.
How to open adb and use it to send commands
In Windows 10 while installing Android SDK, by default latest SDK gets installed.
Platform List is part of Android SDK and the best way to find the location is to open SDK manager and get the path.
It will be available at:
Android SDK Location: C:\Users\<User Name>\AppData\Local\Android\sdk\platform-tools\
In SDK Manager, SDK path can be found by following the below
Appearance & Behaviour --> System Settings --> Android SDK
You can get the path where SDK is installed and can edit the location as well.
Adding to the classpath on OSX
If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions
.
Or, if you want to do it for every Java application, but only when your Mac OS X account runs them, then use ~/Library/Java/Extensions
instead.
EDIT: If you want to do this only for a particular application, as Thorbjørn asked, then you will need to tell us more about how the application is packaged.
How can I link to a specific glibc version?
In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:
Just build on the system with the oldest GLIBC you still want to support.
This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:
Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.
Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.
With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.
How to launch a Google Chrome Tab with specific URL using C#
// open in default browser
Process.Start("http://www.stackoverflow.net");
// open in Internet Explorer
Process.Start("iexplore", @"http://www.stackoverflow.net/");
// open in Firefox
Process.Start("firefox", @"http://www.stackoverflow.net/");
// open in Google Chrome
Process.Start("chrome", @"http://www.stackoverflow.net/");
what is Segmentation fault (core dumped)?
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
get everything between <tag> and </tag> with php
function contentDisplay($text)
{
//replace UTF-8
$convertUT8 = array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6");
$to = array("'", "'", '"', '"', '-', '--', '...');
$text = str_replace($convertUT8,$to,$text);
//replace Windows-1252
$convertWin1252 = array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133));
$to = array("'", "'", '"', '"', '-', '--', '...');
$text = str_replace($convertWin1252,$to,$text);
//replace accents
$convertAccents = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'Ð', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', '?', '?', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', '?', '?', 'L', 'l', 'N', 'n', 'N', 'n', 'N', 'n', '?', 'O', 'o', 'O', 'o', 'O', 'o', 'Œ', 'œ', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'Š', 'š', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Ÿ', 'Z', 'z', 'Z', 'z', 'Ž', 'ž', '?', 'ƒ', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', '?', '?', '?', '?', '?', '?');
$to = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
$text = str_replace($convertAccents,$to,$text);
//Encode the characters
$text = htmlentities($text);
//normalize the line breaks (here because it applies to all text)
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
//decode the <code> tags
$codeOpen = htmlentities('<').'code'.htmlentities('>');
if (strpos($text, $codeOpen))
{
$text = str_replace($codeOpen, html_entity_decode(htmlentities('<')) . "code" . html_entity_decode(htmlentities('>')), $text);
}
$codeOpen = htmlentities('<').'/code'.htmlentities('>');
if (strpos($text, $codeOpen))
{
$text = str_replace($codeOpen, html_entity_decode(htmlentities('<')) . "/code" . html_entity_decode(htmlentities('>')), $text);
}
//match everything between <code> and </code>, the msU is what makes this work here, ADD this to REGEX archive
$regex = '/<code>(.*)<\/code>/msU';
$code = preg_match($regex, $text, $matches);
if ($code == 1)
{
if (is_array($matches) && count($matches) >= 2)
{
$newcode = $matches[1];
$newcode = nl2br($newcode);
}
//remove <code>and this</code> from $text;
$text = str_replace('<code>' . $matches[1] . '</code>', 'PLACEHOLDERCODE1', $text);
//convert the line breaks to paragraphs
$text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
$text = str_replace("\n" , '<br />', $text);
$text = str_replace('</p><p>', '</p>' . "\n\n" . '<p>', $text);
$text = str_replace('PLACEHOLDERCODE1', '<code>'.$newcode.'</code>', $text);
}
else
{
$code = false;
}
if ($code == false)
{
//convert the line breaks to paragraphs
$text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
$text = str_replace("\n" , '<br />', $text);
$text = str_replace('</p><p>', '</p>' . "\n\n" . '<p>', $text);
}
return $text;
}
How to press back button in android programmatically?
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
That would only result to finish()
being called, though ;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
Java 8 Lambda filter by Lists
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
python max function using 'key' and lambda expression
max
function is used to get the maximum out of an iterable
.
The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
So, the key=func
basically allows us to pass an optional argument key
to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.
lambda
is a python keyword that acts as a pseudo function. So, when you pass player
object to it, it will return player.totalScore
. Thus, the iterable passed over to function max
will sort according to the key
totalScore of the player
objects given to it & will return the player
who has maximum totalScore
.
If no key
argument is provided, the maximum is returned according to default Python orderings.
Examples -
max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7
people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')
Adding and using header (HTTP) in nginx
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
Difference between filter and filter_by in SQLAlchemy
It is a syntax sugar for faster query writing. Its implementation in pseudocode:
def filter_by(self, **kwargs):
return self.filter(sql.and_(**kwargs))
For AND you can simply write:
session.query(db.users).filter_by(name='Joe', surname='Dodson')
btw
session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))
can be written as
session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))
Also you can get object directly by PK via get
method:
Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)
When using get
case its important that object can be returned without database request from identity map
which can be used as cache(associated with transaction)
When should you use constexpr capability in C++11?
From Stroustrup's speech at "Going Native 2012":
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
An example of how to use getopts in bash
The example packaged with getopt
(my distro put it in /usr/share/getopt/getopt-parse.bash
) looks like it covers all of your cases:
#!/bin/bash
# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh
# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'
# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
-n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done
Python Dictionary Comprehension
The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.
Instead of writing
l = []
for n in range(1, 11):
l.append(n)
or
l = [n for n in range(1, 11)]
you should write only
l = range(1, 11)
In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.
To get a new dictionary with all keys set to the same value based on another dict, do this:
old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}
You're receiving a SyntaxError because when you write
d = {}
d[i for i in range(1, 11)] = True
you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like
d[[i for i in range(1, 11)]] = True
and not
d[i for i in range(1, 11)] = True
but lists are not hashable, so you can't use them as dict keys.
YAML mapping values are not allowed in this context
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
How to enable scrolling on website that disabled scrolling?
In a browser like Chrome etc.:
- Inspect the code (for e.g. in Chrome press
ctrl + shift + c
);
- Set
overflow: visible
on body element (for e.g., <body style="overflow: visible">
)
- Find/Remove any JavaScripts that may routinely be checking for removal of the
overflow
property:
- To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit
backspace
on your keyboard to remove it.
- If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press
ctrl + z
to undo whatever code you delete, or hit refresh to start over).
Good luck!
How to refresh page on back button click?
The hidden input solution wasn't working for me in Safari. The solution below works, and came from here.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
How to "z-index" to make a menu always on top of the content
You most probably don't need z-index to do that. You can use relative and absolute positioning.
I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute;
to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)
Edit: Just to be clear, positioning is not a replacement for them and I do use z-index
. I just try to avoid using them. Using z-indexes
everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes
.
Cross browser JavaScript (not jQuery...) scroll to top animation
Adapted from this answer:
function scroll(y, duration) {
var initialY = document.documentElement.scrollTop || document.body.scrollTop;
var baseY = (initialY + y) * 0.5;
var difference = initialY - baseY;
var startTime = performance.now();
function step() {
var normalizedTime = (performance.now() - startTime) / duration;
if (normalizedTime > 1) normalizedTime = 1;
window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
if (normalizedTime < 1) window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
This should allow you to smoothly scroll (cosine function) from anywhere to the specified "y".
jQuery add required to input fields
I have found that the following implementations are effective:
$('#freeform_first_name').removeAttr('required');
$('#freeform_first_name').attr('required', 'required');
These commands (attr, removeAttr, prop) behave differently depending on the version of JQuery you are using. Please reference the documentation here: https://api.jquery.com/attr/
How to use sed to remove the last n lines of a file
Just for completeness I would like to add my solution.
I ended up doing this with the standard ed
:
ed -s sometextfile <<< $'-2,$d\nwq'
This deletes the last 2 lines using in-place editing (although it does use a temporary file in /tmp
!!)
How to verify a Text present in the loaded page through WebDriver
Below code is most suitable way to verify a text on page. You can use any one out of 8 locators as per your convenience.
String Verifytext= driver.findElement(By.tagName("body")).getText().trim();
Assert.assertEquals(Verifytext, "Paste the text here which needs to be verified");
latex tabular width the same as the textwidth
The tabularx
package gives you
- the total width as a first parameter, and
- a new column type
X
, all X
columns will grow to fill up the total width.
For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
Purpose of returning by const value?
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
Though any optimizer would most likely optimize it out anyway...
Measure the time it takes to execute a t-sql query
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
How to import a csv file into MySQL workbench?
If the server resides on a remote machine, make sure the file in in the remote machine and not in your local machine.
If the file is in the same machine where the mysql server is, make sure the mysql user has permissions to read/write the file, or copy teh file into the mysql schema directory:
In my case in ubuntu it was: /var/lib/mysql/db_myschema/myfile.csv
Also, not relative to this problem, but if you have problems with the new lines, use sublimeTEXT to change the line endings to WINDOWS format, save the file and retry.
AngularJS Error: $injector:unpr Unknown Provider
Spent a few hours trying to solve the same. This is how I did it:
app.js:
var myApp = angular.module( 'myApp', ['ngRoute', 'ngResource', 'CustomServices'] );
CustomServices is a new module I created and placed in a separate file called services.js
_Layout.cshtml:
<script src="~/Scripts/app.js"></script>
<script src="~/Scripts/services/services.js"></script>
services.js:
var app = angular.module('CustomServices', []);
app.factory( 'GetPeopleList', ['$http', '$log','$q', function ( $http, $log, $q )
{
//Your code here
}
app.js
myApp.controller( 'mainController', ['$scope', '$http', '$route', '$routeParams', '$location', 'GetPeopleList', function ( $scope, $http, $route, $routeParams, $location, GetPeopleList )
You have to bind your service to your new module in the services.js file AND of course you have to use that new module in the creation of your main app module (app.js) AND also declare the use of the service in the controller you want to use it in.
Disable eslint rules for folder
YAML version :
overrides:
- files: *-tests.js
rules:
no-param-reassign: 0
Example of specific rules for mocha tests :
You can also set a specific env for a folder, like this :
overrides:
- files: test/*-tests.js
env:
mocha: true
This configuration will fix error message about describe
and it
not defined, only for your test folder:
/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef
How can I bind a background color in WPF/XAML?
The xaml code:
<Grid x:Name="Message2">
<TextBlock Text="This one is manually orange."/>
</Grid>
The c# code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
CreateNewColorBrush();
}
private void CreateNewColorBrush()
{
SolidColorBrush my_brush = new SolidColorBrush(Color.FromArgb(255, 255, 215, 0));
Message2.Background = my_brush;
}
This one works in windows 8 store app. Try and see. Good luck !
Inverse dictionary lookup in Python
No, you can not do this efficiently without looking in all the keys and checking all their values. So you will need O(n)
time to do this. If you need to do a lot of such lookups you will need to do this efficiently by constructing a reversed dictionary (can be done also in O(n)
) and then making a search inside of this reversed dictionary (each search will take on average O(1)
).
Here is an example of how to construct a reversed dictionary (which will be able to do one to many mapping) from a normal dictionary:
for i in h_normal:
for j in h_normal[i]:
if j not in h_reversed:
h_reversed[j] = set([i])
else:
h_reversed[j].add(i)
For example if your
h_normal = {
1: set([3]),
2: set([5, 7]),
3: set([]),
4: set([7]),
5: set([1, 4]),
6: set([1, 7]),
7: set([1]),
8: set([2, 5, 6])
}
your h_reversed
will be
{
1: set([5, 6, 7]),
2: set([8]),
3: set([1]),
4: set([5]),
5: set([8, 2]),
6: set([8]),
7: set([2, 4, 6])
}
OAuth2 and Google API: access token expiration time?
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
- It is a parameter in the response (
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
Java 8: Lambda-Streams, Filter by Method with Exception
To properly add IOException (to RuntimeException) handling code, your method will look like this:
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> { try { return a.isActive(); }
catch (IOException e) { throw new RuntimeException(e); }});
Stream<String> ss = s.map(a -> { try { return a.getNumber() }
catch (IOException e) { throw new RuntimeException(e); }});
return ss.collect(Collectors.toSet());
The problem now is that the IOException
will have to be captured as a RuntimeException
and converted back to an IOException
-- and that will add even more code to the above method.
Why use Stream
when it can be done just like this -- and the method throws IOException
so no extra code is needed for that too:
Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
if(a.isActive()){
set.add(a.getNumber());
}
}
return set;
Which Android IDE is better - Android Studio or Eclipse?
From the Android Studio download page:
Caution: Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plugin).
How to reverse an std::string?
I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse()
. std::reverse()
operates in place, so you may want to make a copy of the string first:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string foo("foo");
std::string copy(foo);
std::cout << foo << '\n' << copy << '\n';
std::reverse(copy.begin(), copy.end());
std::cout << foo << '\n' << copy << '\n';
}
curl_init() function not working
This worked for me with raspian:
sudo apt update && sudo apt upgrade
sudo apt install php-curl
finally:
sudo systemctl restart apache2
or:
sudo systemctl restart nginx
How to reset or change the passphrase for a GitHub SSH key?
- Log in to your github account.
- Go to the "Settings" page (the "wrench and screwdriver" icon in the top right corner of the page).
- Go to "SSH keys" page.
- Generate a new SSH key (probably studying the links provided by github on that page).
- Add your new key using the "Add SSH key" link.
- Verify your new key works.
- Make gitub forget your old key by using the "Delete" link next to it in the list of known keys.
How to get past the login page with Wget?
I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:
wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'
(This is one line, though it likely wraps on your browser)
If you want the output saved to a file, change -O -
to -O /some/file/name.ext
CSS3 transitions inside jQuery .css()
Step 1) Remove the semi-colon, it's an object you're creating...
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out';
});
to
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out'
});
Step 2) Vendor-prefixes... no browsers use transition
since it's the standard and this is an experimental feature even in the latest browsers:
a(this).next().css({
left : c,
WebkitTransition : 'opacity 1s ease-in-out',
MozTransition : 'opacity 1s ease-in-out',
MsTransition : 'opacity 1s ease-in-out',
OTransition : 'opacity 1s ease-in-out',
transition : 'opacity 1s ease-in-out'
});
Here is a demo: http://jsfiddle.net/83FsJ/
Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:
$('a').on('click', function () {
var myTransition = ($.browser.webkit) ? '-webkit-transition' :
($.browser.mozilla) ? '-moz-transition' :
($.browser.msie) ? '-ms-transition' :
($.browser.opera) ? '-o-transition' : 'transition',
myCSSObj = { opacity : 1 };
myCSSObj[myTransition] = 'opacity 1s ease-in-out';
$(this).next().css(myCSSObj);
});?
Here is a demo: http://jsfiddle.net/83FsJ/1/
Also note that if you specify in your transition
declaration that the property to animate is opacity
, setting a left
property won't be animated.
What is a race condition?
You don't always want to discard a race condition. If you have a flag which can be read and written by multiple threads, and this flag is set to 'done' by one thread so that other thread stop processing when flag is set to 'done', you don't want that "race condition" to be eliminated. In fact, this one can be referred to as a benign race condition.
However, using a tool for detection of race condition, it will be spotted as a harmful race condition.
More details on race condition here, http://msdn.microsoft.com/en-us/magazine/cc546569.aspx.
How do I read any request header in PHP
This work if you have an Apache server
PHP Code:
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
Result:
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive
Convert char array to a int number in C
Why not just use atoi? For example:
char myarray[4] = {'-','1','2','3'};
int i = atoi(myarray);
printf("%d\n", i);
Gives me, as expected:
-123
Update: why not - the character array is not null terminated. Doh!
CFLAGS vs CPPFLAGS
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
Why does the arrow (->) operator in C exist?
Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:
(*(*(*a).b).c).d
a->b->c->d
But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.
Selenium Webdriver submit() vs click()
I was a great fan of submit()
but not anymore.
In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit()
, password textbox is cleared (becomes empty) and login keeps failing.
After breaking my head for sometime, when I replaced usernametextbox.submit()
with loginbutton.click()
, it worked like a magic.
How do I iterate over the words of a string?
// adapted from a "regular" csv parse
std::string stringIn = "my csv is 10233478 NOTseparated by commas";
std::vector<std::string> commaSeparated(1);
int commaCounter = 0;
for (int i=0; i<stringIn.size(); i++) {
if (stringIn[i] == " ") {
commaSeparated.push_back("");
commaCounter++;
} else {
commaSeparated.at(commaCounter) += stringIn[i];
}
}
in the end you will have a vector of strings with every element in the sentence separated by spaces. only non-standard resource is std::vector (but since an std::string is involved, i figured it would be acceptable).
empty strings are saved as a separate items.
Change the jquery show()/hide() animation?
There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...
https://api.jquery.com/category/effects/
You can use slideDown just like this:
$("test").slideDown("slow");
And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.
Force to open "Save As..." popup open at text link click for PDF in HTML
Generally it happens, because some browsers settings or plug-ins directly open PDF in the same window like a simple web page.
The following might help you. I have done it in PHP a few years back. But currently I'm not working on that platform.
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
}
else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
Save the above as download.php.
Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.
You can use it like so:
Add the following link to your HTML file.
<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>
Reference from: This blog
How to stop event bubbling on checkbox click
replace
event.preventDefault();
return false;
with
event.stopPropagation();
event.stopPropagation()
Stops the bubbling of an event to
parent elements, preventing any parent
handlers from being notified of the
event.
event.preventDefault()
Prevents the browser from executing
the default action. Use the method
isDefaultPrevented to know whether
this method was ever called (on that
event object).
EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType
By Changing The DbContext As Below;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
Just adding in OnModelCreating
method call to base.OnModelCreating(modelBuilder); and it becomes fine. I am using EF6.
Special Thanks To #The Senator
Show an image preview before upload
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
Here's a quick example that makes use of the FileReader
class to read an image as DataURL and renders a thumbnail by setting the src
attribute of an image tag to a data URL:
The html code:
<input type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
Here's a good article on using the File APIs in JavaScript.
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_
Google Maps API Multiple Markers with Infowindows
You could use a closure. Just modify your code like this:
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
Here is the DEMO
Converting pfx to pem using openssl
Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.
openssl pkcs12 -in file.pfx -out file.pem -nodes
Then you can configure HAProxy to use the file.pem file.
This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.
openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
- The 1st step prompts you for the password to open the PFX.
- The 2nd step prompts you for that plus also to make up a passphrase for the key.
- The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
- The 4th puts it all together into 1 file.
Then you can configure HAProxy to use the file.combo.pem file.
The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.
Get first n characters of a string
If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
In this case, $preview
will be "Knowledge is a natural right of every human being"
.
Live code example:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713
Shell equality operators (=, ==, -eq)
It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test
.
If you use ((
…))
, you are testing arithmetic equality with ==
as in C:
$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1
(Note: 0
means true
in the Unix sense and a failed test results in a non-zero number.)
Using -eq
inside of double parentheses is a syntax error.
If you are using [
…]
(or single brackets) or [[
…]]
(or double brackets), or test
you can use one of -eq
, -ne
, -lt
, -le
, -gt
, or -ge
as an arithmetic comparison.
$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0
The ==
inside of single or double brackets (or the test
command) is one of the string comparison operators:
$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1
As a string operator, =
is equivalent to ==
. Also, note the whitespace around =
or ==
: it’s required.
While you can do [[ 1 == 1 ]]
or [[ $(( 1+1 )) == 2 ]]
it is testing the string equality — not the arithmetic equality.
So -eq
produces the result probably expected that the integer value of 1+1
is equal to 2
even though the right-hand side is a string and has a trailing space:
$ [[ $(( 1+1 )) -eq "2 " ]]; echo $?
0
While a string comparison of the same picks up the trailing space and therefore the string comparison fails:
$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1
And a mistaken string comparison can produce a completely wrong answer. 10
is lexicographically less than 2
, so a string comparison returns true
or 0
. So many are bitten by this bug:
$ [[ 10 < 2 ]]; echo $?
0
The correct test for 10
being arithmetically less than 2
is this:
$ [[ 10 -lt 2 ]]; echo $?
1
In comments, there is a question about the technical reason why using the integer -eq
on strings returns true for strings that are not the same:
$ [[ "yes" -eq "no" ]]; echo $?
0
The reason is that Bash is untyped. The -eq
causes the strings to be interpreted as integers if possible including base conversion:
$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0
And 0
if Bash thinks it is just a string:
$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1
So [[ "yes" -eq "no" ]]
is equivalent to [[ 0 -eq 0 ]]
Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]]
and ((...))
or ==
.
Unable to create a constant value of type Only primitive types or enumeration types are supported in this context
It's worth adding, since the OP's code sample doesn't provide enough context to prove otherwise, but I received this error as well on the following code:
public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
return GetQueryable()
.FirstOrDefault(x => x.RefersToRetailSaleId.Equals(refersToRetailSaleId));
}
Apparently, I cannot use Int32.Equals
in this context to compare an Int32 with a primitive int; I had to (safely) change to this:
public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
return GetQueryable()
.FirstOrDefault(x => x.RefersToRetailSaleId == refersToRetailSaleId);
}
Laravel where on relationship object
@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events
if each Event
has 'participants'
with IdUser
of 1
.
But if you want to get all Events
with all 'participants'
provided that all 'participants'
have a IdUser
of 1, then you should do something like this :
Event::with(["participants" => function($q){
$q->where('participants.IdUser', '=', 1);
}])
N.B:
in where
use your table name, not Model name.
Android Eclipse - Could not find *.apk
In my case this worked :
Delete R.Java file in /Gen folder
+
Delete all "R.Android" imports that Eclipse added to some of my java classes !!!
and rebuild the project.
What is causing "Unable to allocate memory for pool" in PHP?
I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.
The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:
usermod -a -G vhost-user-group apache-user
Then I had to restart apache for the change to take effect:
apachectl restart
Or
sudo /etc/init.d/httpd restart
Or whatever your system uses to restart apache.
If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?
How to convert jsonString to JSONObject in Java
No need to use any external library.
You can use this class instead :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
Compare two columns using pandas
Use np.select
if you have multiple conditions to be checked from the dataframe and output a specific choice in a different column
conditions=[(condition1),(condition2)]
choices=["choice1","chocie2"]
df["new column"]=np.select=(condtion,choice,default=)
Note: No of conditions and no of choices should match, repeat text in choice if for two different conditions you have same choices
When to use RabbitMQ over Kafka?
One critical difference that you guys forgot is RabbitMQ is push based messaging system whereas Kafka is pull based messaging system. This is important in the scenario where messaging system has to satisfy disparate types of consumers with different processing capabilities. With Pull based system the consumer can consume based on their capability where push systems will push the messages irrespective of the state of consumer thereby putting consumer at high risk.
Displaying a Table in Django from Database
$ pip install django-tables2
settings.py
INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'
models.py
class hotel(models.Model):
name = models.CharField(max_length=20)
views.py
from django.shortcuts import render
def people(request):
istekler = hotel.objects.all()
return render(request, 'list.html', locals())
list.html
{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{% static
'ticket/static/css/screen.css' %}" />
</head>
<body>
{% render_table istekler %}
</body>
</html>
Difference between SelectedItem, SelectedValue and SelectedValuePath
To answer a little more conceptually:
SelectedValuePath
defines which property (by its name) of the objects bound to the ListBox's ItemsSource
will be used as the item's SelectedValue
.
For example, if your ListBox is bound to a collection of Person
objects, each of which has Name
, Age
, and Gender
properties, SelectedValuePath=Name
will cause the value of the selected Person
's Name
property to be returned in SelectedValue
.
Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath
cannot be used.
SelectedItem
, meanwhile, returns the entire Person
object currently selected.
(Here's a further example from MSDN, using TreeView)
Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:
Note that these values are distinct from DisplayMemberPath
(which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath
: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.
C++ How do I convert a std::chrono::time_point to long and back
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
This is a great place for auto
:
auto now = std::chrono::system_clock::now();
Since you want to traffic at millisecond
precision, it would be good to go ahead and covert to it in the time_point
:
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
now_ms
is a time_point
, based on system_clock
, but with the precision of milliseconds
instead of whatever precision your system_clock
has.
auto epoch = now_ms.time_since_epoch();
epoch
now has type std::chrono::milliseconds
. And this next statement becomes essentially a no-op (simply makes a copy and does not make a conversion):
auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
Here:
long duration = value.count();
In both your and my code, duration
holds the number of milliseconds
since the epoch of system_clock
.
This:
std::chrono::duration<long> dur(duration);
Creates a duration
represented with a long
, and a precision of seconds
. This effectively reinterpret_cast
s the milliseconds
held in value
to seconds
. It is a logic error. The correct code would look like:
std::chrono::milliseconds dur(duration);
This line:
std::chrono::time_point<std::chrono::system_clock> dt(dur);
creates a time_point
based on system_clock
, with the capability of holding a precision to the system_clock
's native precision (typically finer than milliseconds). However the run-time value will correctly reflect that an integral number of milliseconds are held (assuming my correction on the type of dur
).
Even with the correction, this test will (nearly always) fail though:
if (dt != now)
Because dt
holds an integral number of milliseconds
, but now
holds an integral number of ticks finer than a millisecond
(e.g. microseconds
or nanoseconds
). Thus only on the rare chance that system_clock::now()
returned an integral number of milliseconds
would the test pass.
But you can instead:
if (dt != now_ms)
And you will now get your expected result reliably.
Putting it all together:
int main ()
{
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
std::chrono::milliseconds dur(duration);
std::chrono::time_point<std::chrono::system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Personally I find all the std::chrono
overly verbose and so I would code it as:
int main ()
{
using namespace std::chrono;
auto now = system_clock::now();
auto now_ms = time_point_cast<milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
milliseconds dur(duration);
time_point<system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Which will reliably output:
Success.
Finally, I recommend eliminating temporaries to reduce the code converting between time_point
and integral type to a minimum. These conversions are dangerous, and so the less code you write manipulating the bare integral type the better:
int main ()
{
using namespace std::chrono;
// Get current time with precision of milliseconds
auto now = time_point_cast<milliseconds>(system_clock::now());
// sys_milliseconds is type time_point<system_clock, milliseconds>
using sys_milliseconds = decltype(now);
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
sys_milliseconds dt{milliseconds{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
The main danger above is not interpreting integral_duration
as milliseconds
on the way back to a time_point
. One possible way to mitigate that risk is to write:
sys_milliseconds dt{sys_milliseconds::duration{integral_duration}};
This reduces risk down to just making sure you use sys_milliseconds
on the way out, and in the two places on the way back in.
And one more example: Let's say you want to convert to and from an integral which represents whatever duration system_clock
supports (microseconds, 10th of microseconds or nanoseconds). Then you don't have to worry about specifying milliseconds as above. The code simplifies to:
int main ()
{
using namespace std::chrono;
// Get current time with native precision
auto now = system_clock::now();
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
system_clock::time_point dt{system_clock::duration{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
This works, but if you run half the conversion (out to integral) on one platform and the other half (in from integral) on another platform, you run the risk that system_clock::duration
will have different precisions for the two conversions.
Get the length of a String
in Swift 2.x the following is how to find the length of a string
let findLength = "This is a string of text"
findLength.characters.count
returns 24
Can I have multiple primary keys in a single table?
Yes, Its possible in SQL,
but we can't set more than one primary keys in MsAccess.
Then, I don't know about the other databases.
CREATE TABLE CHAPTER (
BOOK_ISBN VARCHAR(50) NOT NULL,
IDX INT NOT NULL,
TITLE VARCHAR(100) NOT NULL,
NUM_OF_PAGES INT,
PRIMARY KEY (BOOK_ISBN, IDX)
);
How to find out what type of a Mat object is with Mat::type() in OpenCV
I've added some usability to the function from the answer by @Octopus, for debugging purposes.
void MatType( Mat inputMat )
{
int inttype = inputMat.type();
string r, a;
uchar depth = inttype & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (inttype >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; a = "Mat.at<uchar>(y,x)"; break;
case CV_8S: r = "8S"; a = "Mat.at<schar>(y,x)"; break;
case CV_16U: r = "16U"; a = "Mat.at<ushort>(y,x)"; break;
case CV_16S: r = "16S"; a = "Mat.at<short>(y,x)"; break;
case CV_32S: r = "32S"; a = "Mat.at<int>(y,x)"; break;
case CV_32F: r = "32F"; a = "Mat.at<float>(y,x)"; break;
case CV_64F: r = "64F"; a = "Mat.at<double>(y,x)"; break;
default: r = "User"; a = "Mat.at<UKNOWN>(y,x)"; break;
}
r += "C";
r += (chans+'0');
cout << "Mat is of type " << r << " and should be accessed with " << a << endl;
}
How to define hash tables in Bash?
This is what I was looking for here:
declare -A hashmap
hashmap["key"]="value"
hashmap["key2"]="value2"
echo "${hashmap["key"]}"
for key in ${!hashmap[@]}; do echo $key; done
for value in ${hashmap[@]}; do echo $value; done
echo hashmap has ${#hashmap[@]} elements
This did not work for me with bash 4.1.5:
animals=( ["moo"]="cow" )
Opening port 80 EC2 Amazon web services
Some quick tips:
- Disable the inbuilt firewall on your Windows instances.
- Use the IP address rather than the DNS entry.
- Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
- Check that you can actually ping your server. This may also necessitate some Security Group modification.
When should null values of Boolean be used?
Wow, what on earth? Is it just me or are all these answers wrong or at least misleading?
The Boolean class is a wrapper around the boolean primitive type. The use of this wrapper is to be able to pass a boolean in a method that accepts an object or generic. Ie vector.
A Boolean object can NEVER have a value of null. If your reference to a Boolean is null, it simply means that your Boolean was never created.
You might find this useful: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Boolean.java
A null Boolean reference should only be used to trigger similar logic to which you have any other null reference. Using it for three state logic is clumsy.
EDIT: notice, that Boolean a = true;
is a misleading statement. This really equals something closer to Boolean a = new Boolean(true);
Please see autoboxing here: http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Autoboxing
Perhaps this is where much of the confusion comes from.
EDIT2: Please read comments below.
If anyone has an idea of how to restructure my answer to incorporate this, please do so.
AltGr key not working, instead I have to use Ctrl+AltGr
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
JQuery: detect change in input field
You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.
$('#myTextbox').on('input', function() {
// do something
});
If you use the change
handler, this will only fire after the user deselects the input box, which may not be what you want.
There is an example of both here: http://jsfiddle.net/6bSX6/
Add vertical scroll bar to panel
Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.
panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;
// here you'd be adding controls
int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
// this example uses textbox control
TextBox txt = new TextBox();
txt.Location = new System.Drawing.Point(x, y);
// add whatever details you need for this control
// before adding it to the panel
panelUserInput.Controls.Add(txt);
height = y + txt.Height;
y += 25;
}
if (height > panelUserInput.Height)
{
VScrollBar bar = new VScrollBar();
bar.Dock = DockStyle.Right;
bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value = bar.Value; };
bar.Top = 0;
bar.Left = panelUserInput.Width - bar.Width;
bar.Height = panelUserInput.Height;
bar.Visible = true;
panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();
// then update the form
this.PerformLayout();
AngularJS sorting rows by table header
I'm just getting my feet wet with angular, but I found this great tutorial.
Here's a working plunk I put together with credit to Scott Allen and the above tutorial. Click search to display the sortable table.
For each column header you need to make it clickable - ng-click on a link will work. This will set the sortName of the column to sort.
<th>
<a href="#" ng-click="sortName='name'; sortReverse = !sortReverse">
<span ng-show="sortName == 'name' && sortReverse" class="glyphicon glyphicon-triangle-bottom"></span>
<span ng-show="sortName == 'name' && !sortReverse" class="glyphicon glyphicon-triangle-top"></span>
Name
</a>
</th>
Then, in the table body you can pipe in that sortName in the orderBy filter orderBy:sortName:sortReverse
<tr ng-repeat="repo in repos | orderBy:sortName:sortReverse | filter:searchRepos">
<td>{{repo.name}}</td>
<td class="tag tag-primary">{{repo.stargazers_count | number}}</td>
<td>{{repo.language}}</td>
</tr>
How to search a string in a single column (A) in excel using VBA
Below are two methods that are superior to looping. Both handle a "no-find" case.
- The VBA equivalent of a normal function
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)
VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
Convert Word doc, docx and Excel xls, xlsx to PDF with PHP
Step 1. Install "Apache_OpenOffice_4.1.2" in your system
Step 2. Download "unoconv" library from github or any where else.
-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory
-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder
-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf
-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.
If pdf not created than last step is
Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop
Create sample .php file and put below code and run on wamp or xampp server
$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);
This code working for me in windows-8 operating system
Convert Xml to Table SQL Server
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
1
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
2.
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html
http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx
How to redirect stdout to both file and console with scripting?
Based on Amith Koujalgi's answer, here's a simple module you can use for logging -
transcript.py:
"""
Transcript - direct print output to a file, in addition to terminal.
Usage:
import transcript
transcript.start('logfile.log')
print("inside file")
transcript.stop()
print("outside file")
"""
import sys
class Transcript(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.logfile = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def start(filename):
"""Start transcript, appending print output to given filename"""
sys.stdout = Transcript(filename)
def stop():
"""Stop transcript and return print functionality to normal"""
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Reverse of JSON.stringify?
How about this
var parsed = new Function('return ' + stringifiedJSON )();
This is a safer alternative for eval
.
_x000D_
_x000D_
var stringifiedJSON = '{"hello":"world"}';_x000D_
var parsed = new Function('return ' + stringifiedJSON)();_x000D_
alert(parsed.hello);
_x000D_
_x000D_
_x000D_
Conversion of a datetime2 data type to a datetime data type results out-of-range value
For me I have had a Devexpress DateEdit component, which was binded to nullable datetime MSSQL column thru the Nullable model property. All I had to do was setting AllowNullInput = True on DateEdit. Having it "Default" caused that the date 1.1.0001 appeared - ONLY BEFORE leaving the DateEdit - and then I got this conversion error message because of subsequent instructions mentioned above.
Using grep to search for hex strings in a file
We tried several things before arriving at an acceptable solution:
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
Then found we could get usable results with
xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd
Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
--------------------^^
So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).
The final result seems to be
xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex
0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03 .$.q............
--------------------------------------------^^
ObjectiveC Parse Integer from String
If I understood you correctly, you need to convert your NSString
to int
? Try this peace of code:
NSString *stringWithNumberInside = [_returnedArguments objectAtIndex:2];
int number;
sscanf([stringWithNumberInside UTF8String], "%x", &flags);
Sending email with gmail smtp with codeigniter email library
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$result = $this->email->send();
From the CodeIgniter Forums
How to add "active" class to wp_nav_menu() current menu item (simple way)
In header.php
insert this code to show menu:
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-one',
'walker' => new Custom_Walker_Nav_Menu_Top
)
);
?>
In functions.php
use this:
class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$is_current_item = '';
if(array_search('current-menu-item', $item->classes) != 0)
{
$is_current_item = ' class="active"';
}
echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
echo '</a></li>';
}
}
Genymotion Android emulator - adb access?
If you launch the VM with the the launchpad (genymotion binary where you download the VMs) and you set the Android SDK path into the application parameters the connection is automatic and you don't need to run adb connect
You can find the information in the Genymotion Docs.
Git commit date
If you like to have the timestamp without the timezone but local timezone do
git log -1 --format=%cd --date=local
Which gives this depending on your location
Mon Sep 28 12:07:37 2015
how to update the multiple rows at a time using linq to sql?
To update one column here are some syntax options:
Option 1
var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
}
db.SubmitChanges();
}
Update
As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status
at ones. We want to update name
and status
where the friendid
is matching. Here are some syntax options for that:
Option 1
var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
some.name=name;
}
db.SubmitChanges();
}
Update 2
In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:
db.SubmitChanges();
But for Entity Framework to commit the changes it is:
db.SaveChanges()
Java 8 forEach with index
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
How to create an Array, ArrayList, Stack and Queue in Java?
I am guessing you're confused with the parameterization of the types:
// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>();
// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();
fatal: 'origin' does not appear to be a git repository
This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.
I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER).
For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.
Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push
I got an error message similar to the one posted in the question.
The reason was, that I called push
from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.
When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.
Feel free to comment if my explanation can't be understood, or you find my post superfluous.
Equivalent of Math.Min & Math.Max for Dates?
How about a DateTime
extension method?
public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
return instance > dateTime ? instance : dateTime;
}
Usage:
var maxDate = date1.MaxOf(date2);
How to view/delete local storage in Firefox?
You can delete localStorage items one by one using Firebug (a useful web development extension) or Firefox's developer console.
Firebug Method
- Open Firebug (click on the tiny bug icon in the lower right)
- Go to the DOM tab
- Scroll down to and expand localStorage
- Right-click the item you wish to delete and press Delete Property
Developer Console Method
You can enter these commands into the console:
localStorage; // click arrow to view object's properties
localStorage.removeItem("foo");
localStorage.clear(); // remove all of localStorage's properties
Storage Inspector Method
Firefox now has a built in storage inspector, which you may need to manually enable. See rahilwazir's answer below.
Run script with rc.local: script works, but not at boot
I am using CentOS 7.
$ cd /etc/profile.d
$ vim yourstuffs.sh
Type the following into the yourstuffs.sh script.
type whatever you want here to execute
export LD_LIBRARY_PATH=/usr/local/cuda-7.0/lib64:$LD_LIBRARY_PATH
Save and reboot the OS.
Get dates from a week number in T-SQL
DECLARE @dayval int,
@monthval int,
@yearval int
SET @dayval = 1
SET @monthval = 1
SET @yearval = 2011
DECLARE @dtDateSerial datetime
SET @dtDateSerial = DATEADD(day, @dayval-1,
DATEADD(month, @monthval-1,
DATEADD(year, @yearval-1900, 0)
)
)
DECLARE @weekno int
SET @weekno = 53
DECLARE @weekstart datetime
SET @weekstart = dateadd(day, 7 * (@weekno -1) - datepart (dw, @dtDateSerial), @dtDateSerial)
DECLARE @weekend datetime
SET @weekend = dateadd(day, 6, @weekstart)
SELECT @weekstart, @weekend
Regex to validate password strength
You can use zero-length positive look-aheads to specify each of your constraints separately:
(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
If your regex engine doesn't support the \p
notation and pure ASCII is enough, then you can replace \p{Lu}
with [A-Z]
and \p{Ll}
with [a-z]
.
How to create a file in Linux from terminal window?
Depending on what you want the file to contain:
touch /path/to/file
for an empty file
somecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
Create an empty file
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
Create a file containing a newline and nothing else
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
Write text into a file
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
How to use RecyclerView inside NestedScrollView?
At least as far back as Material Components 1.3.0-alpha03, it doesn't matter if the RecyclerView is nested (in something other than a ScrollView or NestedScrollView). Just put app:layout_behavior="@string/appbar_scrolling_view_behavior"
on its top level parent that's a sibling of the AppBarLayout in the CoordinatorLayout.
This has been working for me when using a single Activity architecture with Jetpack Naviagation, where all Fragments are sharing the same AppBar from the Activity's layout. I make the FragmentContainer the direct child of the CoordinatorLayout that also contains the AppBarLayout, like below. The RecyclerViews in the various fragments are scrolling normally and the AppBar folds away and reappears as expected.
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:defaultNavHost="true"
app:navGraph="@navigation/mobile_navigation"/>
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:liftOnScroll="true">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
liftOnScroll
(used to for app bars to look like they have zero elevation when at the top of the page) works if each fragment passes the ID of its RecyclerView to AppBarLayout.liftOnScrollTargetViewId
in Fragment.onResume
. Or pass 0 if the Fragment doesn't scroll.
Python error "ImportError: No module named"
- You must have the file __ init__.py in the same directory where it's the file that you are importing.
- You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.
eg:
/etc/environment
PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2
/opt/folder1/foo
/opt/folder2/foo
And, if you are trying to import foo file, python will not know which one you want.
from foo import ... >>> importerror: no module named foo
Rendering JSON in controller
You'll normally be returning JSON either because:
A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.
or
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
Or, possibly, you are eating your own dogfood and doing both
In both cases render :json => some_data
will JSON-ify the provided data. The :callback
key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)
Why :callback
?
JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com
and you will be serving your application off of services.yoursite.com
your JavaScript will not (by default) be able to make XMLHttpRequest
(XHR - aka ajax) requests from services
to api
. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
Thus, a client-side JS application could create a script
tag pointing at api.yoursite.com/your/endpoint?name=John
and have the valueOfCallbackHere
function (which would have to be defined in the client-side JS) called with the data from this other origin.)
Why can't C# interfaces contain fields?
Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties
interface IEmployee
{
string Name
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
public static int numberOfEmployees;
private string _name;
public string Name // read-write instance property
{
get => _name;
set => _name = value;
}
private int _counter;
public int Counter // read-only instance property
{
get => _counter;
}
// constructor
public Employee() => _counter = ++numberOfEmployees;
}
What is the purpose of "pip install --user ..."?
pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4
). This requires root access.
--user
makes pip install packages in your home directory instead, which doesn't require any special privileges.
Maven: How to rename the war file for the project?
You need to configure the war plugin:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>bird.war</warName>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
More info here
How can I lookup a Java enum from its String value?
since java 8 you can initialize the map in a single line and without static block
private static Map<String, Verbosity> stringMap = Arrays.stream(values())
.collect(Collectors.toMap(Enum::toString, Function.identity()));
Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
Short ES6 code
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
Configure Apache .conf for Alias
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
How do I convert NSInteger to NSString datatype?
Modern Objective-C
An NSInteger
has the method stringValue
that can be used even with a literal
NSString *integerAsString1 = [@12 stringValue];
NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];
Very simple. Isn't it?
Swift
var integerAsString = String(integer)
Hive External Table Skip First Row
While you have your answer from Daniel, here are some customizations possible using OpenCSVSerde
:
CREATE EXTERNAL TABLE `mydb`.`mytable`(
`product_name` string,
`brand_id` string,
`brand` string,
`color` string,
`description` string,
`sale_price` string)
PARTITIONED BY (
`seller_id` string)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
'separatorChar' = '\t',
'quoteChar' = '"',
'escapeChar' = '\\')
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
'hdfs://namenode.com:port/data/mydb/mytable'
TBLPROPERTIES (
'serialization.null.format' = '',
'skip.header.line.count' = '1')
With this, you have total control over the separator, quote character, escape character, null handling and header handling.
Look here and here.
Java Loop every minute
You can use Timer
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
// do your work
}
}, 0, 60*1000);
When the times comes
timer.cancel();
To shut it down.
Java: Rotating Images
This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)
// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;
// Rotation information
double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
How can I remove the extension of a filename in a shell script?
You can also use parameter expansion:
$ filename=foo.txt
$ echo "${filename%.*}"
foo
Just be aware that if there is no file extension, it will look further back for dots, e.g.
- If the filename only starts with a dot (e.g.
.bashrc
) it will remove the whole filename.
- If there's a dot only in the path (e.g.
path.to/myfile
or ./myfile
), then it will trim inside the path.
The right way of setting <a href=""> when it's a local file
By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)
So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).
If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,
How to create PDF files in Python
I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.
It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).
How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?
No, there is no way to do this with git show
. But it would certainly be nice sometimes, and it would probably be relatively easy to implement in the git source code (after all, you just have to tell it to not trim out what it thinks is extraneous output), so the patch to do so would probably be accepted by the git maintainers.
Be careful what you wish for, though; merging a branch with a one-line change that was forked three months ago will still have a huge diff versus the mainline, and so such a full diff would be almost completely unhelpful. That's why git doesn't show it.
In plain English, what does "git reset" do?
Checkout points the head at a specific commit.
Reset points a branch at a specific commit. (A branch is a pointer to a commit.)
Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)
PHP is_numeric or preg_match 0-9 validation
is_numeric
checks more:
Finds whether the given variable is numeric. Numeric strings consist
of optional sign, any number of digits, optional decimal part and
optional exponential part. Thus +0123.45e6 is a valid numeric value.
Hexadecimal notation (0xFF) is allowed too but only without sign,
decimal and exponential part.
How to create an empty array in Swift?
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
Titlecase all entries into a form_for text field
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
How to convert between bytes and strings in Python 3?
This is a Python 101 type question,
It's a simple question but one where the answer is not so simple.
In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.
To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.
Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.
If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.
print(bytesThing)
Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.
JavaScript: how to change form action attribute value based on selection?
It's better to use
$('#search-form').setAttribute('action', '/controllerName/actionName');
rather than
$('#search-form').attr('action', '/controllerName/actionName');
So, based on trante's answer we have:
$('#search-form').submit(function() {
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").setAttribute("action", "/search/" + formAction);
});
Using setAttribute
can save you a lot of time potentially.
CSV parsing in Java - working example..?
I would recommend that you start by pulling your task apart into it's component parts.
- Read string data from a CSV
- Convert string data to appropriate format
Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.
If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.
DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation.
Integer.parseInt() will prase integers from strings.
Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).
How to Execute a Python File in Notepad ++?
No answer here, or plugin i found provided what i wanted. A minimalist method to launch my python code i wrote on Notepad++ with the press of a shortcut, with preferably no plugins.
I have Python 3.6 (64-bit), for Windows 8.1 x86_64 and Notepad++ 32bit. After you write your Python script in Notepad++ and save it, Hit F5 for Run
. Then write:
"C:\Path\to\Python\python.exe" -i "$(FULL_CURRENT_PATH)"
and hit the Run button. The i
flag forces the terminal to stay still after code execution has terminated, for you to inspect it. This command will launch the script in a cmd terminal and the terminal will still lie there, until you close it by typing exit()
.
You can save this to a shortcut for convenience (mine is CTRL + SHIFT + P).
What's the scope of a variable initialized in an if statement?
As Eli said, Python doesn't require variable declaration. In C you would say:
int x;
if(something)
x = 1;
else
x = 2;
but in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed.
The only reason that a statically typed language is limited to having to declare variables outside of if
statements in because of this problem. Embrace the dynamic!
How can I split a shell command over multiple lines when using an IF statement?
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space (
) or tabs (\t
) but also the carriage return (\r
).
I need to round a float to two decimal places in Java
You can make use of DecimalFormat
to give you the style you wish.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.
what is numeric(18, 0) in sql server 2008 r2
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
Get domain name
I know this is old. I just wanted to dump this here for anyone that was looking for an answer to getting a domain name. This is in coordination with Peter's answer. There "is" a bug as stated by Rich. But, you can always make a simple workaround for that. The way I can tell if they are still on the domain or not is by pinging the domain name. If it responds, continue on with whatever it was that I needed the domain for. If it fails, I drop out and go into "offline" mode. Simple string method.
string GetDomainName()
{
string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(_domain);
if (reply.Status == IPStatus.Success)
{
return _domain;
}
else
{
return reply.Status.ToString();
}
}
catch (PingException pExp)
{
if (pExp.InnerException.ToString() == "No such host is known")
{
return "Network not detected!";
}
return "Ping Exception";
}
}
Checking out Git tag leads to "detached HEAD state"
Okay, first a few terms slightly oversimplified.
In git
, a tag
(like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.
Now a branch
is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.
Your HEAD
is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD
will point to master
which in turn will point to a commit. When you then do something like git checkout experimental
, you switch the HEAD
to point to the experimental
branch which might point to a different commit.
Now the explanation.
When you do a git checkout v2.0
, you are switching to a commit that is not pointed to by a branch
. The HEAD
is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.
Usually, what you can do is to say git checkout -b v2.0-fixes v2.0
. This will create a new branch pointer at the commit pointed to by the treeish v2.0
(a tag in this case) and then shift your HEAD
to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes
branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0
code. If however, you want to make any alterations there which you want to track, you'll need a branch.
You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.
Is there a way to reduce the size of the git folder?
yes yes, git gc
is the solution, naturally,
and locally - you can just delete the local repository and clone it again,
but there is something more important here...
the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,
Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,
but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff,
you can still store the old git & externals somewhere, if you get nostalgic :]
but, at some point you really have to move along :]
your team will thank you!
Exception from HRESULT: 0x800A03EC Error
I got this error when calling this code: wks.Range[startCell, endCell]
where the startCell
Range and endCell
Range were pointing to different worksheet then the variable wks
.
cannot be cast to java.lang.Comparable
- the object which implements
Comparable
is Fegan
.
The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
- To actually do your sorting, you might want to make your
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.
jquery smooth scroll to an anchor?
works
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
$(this).on( "click", function() {
var hashname = $(this).attr('href').replace('#_', '');
if($(this).attr('href') == "#_") {
$('html, body').animate({ scrollTop: 0 }, 300);
}
else {
var target = $('a[name="' + hashname + '"], #' + hashname),
targetOffset = target.offset().top;
if(targetOffset >= 1) {
$('html, body').animate({ scrollTop: targetOffset-60 }, 300);
}
}
});
});
python's re: return True if string contains regex pattern
Match
objects are always true, and None
is returned if there is no match. Just test for trueness.
Code:
>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
...
'bar'
Output = bar
If you want search
functionality
>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
... m.group(0)
...
'bar'
and if regexp
not found than
>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
... else:
... print "no match"
...
no match
As @bukzor mentioned if st = foo bar
than match will not work. So, its more appropriate to use re.search
.
"Unable to locate tools.jar" when running ant
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
Easily measure elapsed time
The values printed by your second program are seconds, and microseconds.
0 26339 = 0.026'339 s = 26339 µs
4 45025 = 4.045'025 s = 4045025 µs
How to use z-index in svg elements?
As others here have said, z-index is defined by the order the element appears in the DOM. If manually reordering your html isn't an option or would be difficult, you can use D3 to reorder SVG groups/objects.
Use D3 to Update DOM Order and Mimic Z-Index Functionality
Updating SVG Element Z-Index With D3
At the most basic level (and if you aren't using IDs for anything else), you can use element IDs as a stand-in for z-index and reorder with those. Beyond that you can pretty much let your imagination run wild.
Examples in code snippet
_x000D_
_x000D_
var circles = d3.selectAll('circle')_x000D_
var label = d3.select('svg').append('text')_x000D_
.attr('transform', 'translate(' + [5,100] + ')')_x000D_
_x000D_
var zOrders = {_x000D_
IDs: circles[0].map(function(cv){ return cv.id; }),_x000D_
xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),_x000D_
yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),_x000D_
radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),_x000D_
customOrder: [3, 4, 1, 2, 5]_x000D_
}_x000D_
_x000D_
var setOrderBy = 'IDs';_x000D_
var setOrder = d3.descending;_x000D_
_x000D_
label.text(setOrderBy);_x000D_
circles.data(zOrders[setOrderBy])_x000D_
circles.sort(setOrder);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100"> _x000D_
<circle id="1" fill="green" cx="50" cy="40" r="20"/> _x000D_
<circle id="2" fill="orange" cx="60" cy="50" r="18"/>_x000D_
<circle id="3" fill="red" cx="40" cy="55" r="10"/> _x000D_
<circle id="4" fill="blue" cx="70" cy="20" r="30"/> _x000D_
<circle id="5" fill="pink" cx="35" cy="20" r="15"/> _x000D_
</svg>
_x000D_
_x000D_
_x000D_
The basic idea is:
Use D3 to select the SVG DOM elements.
var circles = d3.selectAll('circle')
Create some array of z-indices with a 1:1 relationship with your SVG elements (that you want to reorder). Z-index arrays used in the examples below are IDs, x & y position, radii, etc....
var zOrders = {
IDs: circles[0].map(function(cv){ return cv.id; }),
xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
customOrder: [3, 4, 1, 2, 5]
}
Then, use D3 to bind your z-indices to that selection.
circles.data(zOrders[setOrderBy]);
Lastly, call D3.sort to reorder the elements in the DOM based on the data.
circles.sort(setOrder);
Examples
- Or Specify an array to apply z-index for a specific ordering -- in my example code the array
[3,4,1,2,5]
moves/reorders the 3rd circle (in the original HTML order) to be 1st in the DOM, 4th to be 2nd, 1st to be 3rd, and so on...
ImportError: No module named - Python
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
Fastest way to Remove Duplicate Value from a list<> by lambda
The easiest way to get a new list would be:
List<long> unique = longs.Distinct().ToList();
Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.
Note that Distinct()
isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct()
for more information.
If you don't need it to be a List<long>
, you could just keep it as:
IEnumerable<long> unique = longs.Distinct();
At this point it will go through the de-duping each time you iterate over unique
though. Whether that's good or not will depend on your requirements.
Logical operators for boolean indexing in Pandas
TLDR; Logical Operators in Pandas are &
, |
and ~
, and parentheses (...)
is important!
Python's and
, or
and not
logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.
So the following in python (exp1
and exp2
are expressions which evaluate to a boolean result)...
exp1 and exp2 # Logical AND
exp1 or exp2 # Logical OR
not exp1 # Logical NOT
...will translate to...
exp1 & exp2 # Element-wise logical AND
exp1 | exp2 # Element-wise logical OR
~exp1 # Element-wise logical NOT
for pandas.
If in the process of performing logical operation you get a ValueError
, then you need to use parentheses for grouping:
(exp1) op (exp2)
For example,
(df['col1'] == x) & (df['col2'] == y)
And so on.
Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: &
for logical AND, |
for logical OR, and ~
for logical NOT.
Consider the following setup:
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df
A B C
0 5 0 3
1 3 7 9
2 3 5 2
3 4 7 6
4 8 8 1
Logical AND
For df
above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.
Overloaded Bitwise &
Operator
Before continuing, please take note of this particular excerpt of the docs, which state
Another common operation is the use of boolean vectors to filter the
data. The operators are: |
for or
, &
for and
, and ~
for not
. These
must be grouped by using parentheses, since by default Python will
evaluate an expression such as df.A > 2 & df.B < 3
as df.A > (2 &
df.B) < 3
, while the desired evaluation order is (df.A > 2) & (df.B <
3)
.
So, with this in mind, element wise logical AND can be implemented with the bitwise operator &
:
df['A'] < 5
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'] > 5
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
(df['A'] < 5) & (df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
And the subsequent filtering step is simply,
df[(df['A'] < 5) & (df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators <
and >
. See the section of Operator Precedence in the python docs.
If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as
df['A'] < 5 & df['B'] > 5
It is parsed as
df['A'] < (5 & df['B']) > 5
Which becomes,
df['A'] < something_you_dont_want > 5
Which becomes (see the python docs on chained operator comparison),
(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)
Which becomes,
# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2
Which throws
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
So, don't make that mistake!1
Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:
df['A'].lt(5)
0 True
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'].gt(5)
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
df['A'].lt(5) & df['B'].gt(5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
See the section on Flexible Comparisons.. To summarise, we have
+------------------------------+
¦ ¦ Operator ¦ Function ¦
¦----+------------+------------¦
¦ 0 ¦ > ¦ gt ¦
+----+------------+------------¦
¦ 1 ¦ >= ¦ ge ¦
+----+------------+------------¦
¦ 2 ¦ < ¦ lt ¦
+----+------------+------------¦
¦ 3 ¦ <= ¦ le ¦
+----+------------+------------¦
¦ 4 ¦ == ¦ eq ¦
+----+------------+------------¦
¦ 5 ¦ != ¦ ne ¦
+------------------------------+
Another option for avoiding parentheses is to use DataFrame.query
(or eval
):
df.query('A < 5 and B > 5')
A B C
1 3 7 9
3 4 7 6
I have extensively documented query
and eval
in Dynamic Expression Evaluation in pandas using pd.eval().
operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__
which corresponds to the bitwise operator.
import operator
operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
df[operator.and_(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
You won't usually need this, but it is useful to know.
Generalizing: np.logical_and
(and logical_and.reduce
)
Another alternative is using np.logical_and
, which also does not need parentheses grouping:
np.logical_and(df['A'] < 5, df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
Name: A, dtype: bool
df[np.logical_and(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
np.logical_and
is a ufunc (Universal Functions), and most ufuncs have a reduce
method. This means it is easier to generalise with logical_and
if you have multiple masks to AND. For example, to AND masks m1
and m2
and m3
with &
, you would have to do
m1 & m2 & m3
However, an easier option is
np.logical_and.reduce([m1, m2, m3])
This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):
import operator
cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]
m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m
# array([False, True, False, True, False])
df[m]
A B C
1 3 7 9
3 4 7 6
1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.
Logical OR
For the df
above, say you'd like to return all rows where A == 3 or B == 7.
Overloaded Bitwise |
df['A'] == 3
0 False
1 True
2 True
3 False
4 False
Name: A, dtype: bool
df['B'] == 7
0 False
1 True
2 False
3 True
4 False
Name: B, dtype: bool
(df['A'] == 3) | (df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[(df['A'] == 3) | (df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
If you haven't yet, please also read the section on Logical AND above, all caveats apply here.
Alternatively, this operation can be specified with
df[df['A'].eq(3) | df['B'].eq(7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
operator.or_
Calls Series.__or__
under the hood.
operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[operator.or_(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
np.logical_or
For two conditions, use logical_or
:
np.logical_or(df['A'] == 3, df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df[np.logical_or(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
For multiple masks, use logical_or.reduce
:
np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False, True, True, True, False])
df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
Logical NOT
Given a mask, such as
mask = pd.Series([True, True, False])
If you need to invert every boolean value (so that the end result is [False, False, True]
), then you can use any of the methods below.
Bitwise ~
~mask
0 False
1 False
2 True
dtype: bool
Again, expressions need to be parenthesised.
~(df['A'] == 3)
0 True
1 False
2 False
3 True
4 True
Name: A, dtype: bool
This internally calls
mask.__invert__()
0 False
1 False
2 True
dtype: bool
But don't use it directly.
operator.inv
Internally calls __invert__
on the Series.
operator.inv(mask)
0 False
1 False
2 True
dtype: bool
np.logical_not
This is the numpy variant.
np.logical_not(mask)
0 False
1 False
2 True
dtype: bool
Note, np.logical_and
can be substituted for np.bitwise_and
, logical_or
with bitwise_or
, and logical_not
with invert
.
Read and overwrite a file in Python
If you don't want to close and reopen the file, to avoid race conditions, you could truncate
it:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
The functionality will likely also be cleaner and safer using open
as a context manager, which will close the file handler, even if an error occurs!
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
Login to remote site with PHP cURL
This is how I solved this in ImpressPages:
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
Why doesn't importing java.util.* include Arrays and Lists?
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
What are Covering Indexes and Covered Queries in SQL Server?
If all the columns requested in the select
list of query, are available in the index, then the query engine doesn't have to lookup the table again which can significantly increase the performance of the query. Since all the requested columns are available with in the index, the index is covering the query. So, the query is called a covering query and the index is a covering index.
A clustered index can always cover a query, if the columns in the select list are from the same table.
The following links can be helpful, if you are new to index concepts:
How to get IP address of running docker container
For modern docker engines use this command :
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
and for older engines use :
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
What is "string[] args" in Main class for?
Besides the other answers. You should notice these args can give you the file path that was dragged and dropped on the .exe
file.
i.e if you drag and drop any file on your .exe
file then the application will be launched and the arg[0]
will contain the file path that was dropped onto it.
static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
this will print the path of the file dropped on the .exe
file. e.g
C:\Users\ABCXYZ\source\repos\ConsoleTest\ConsoleTest\bin\Debug\ConsoleTest.pdb
Hence, looping through the args
array will give you the path of all the files that were selected and dragged and dropped onto the .exe
file of your console app. See:
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadLine();
}
The code sample above will print all the file names that were dragged and dropped onto it, See I am dragging 5 files onto my ConsoleTest.exe
app.
And here is the output that I get after that:
How to add a new schema to sql server 2008?
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button
Methods vs Constructors in Java
Constructor is special function used to initialise the data member, where the methods are functions to perform specific task.
Constructor name is the same name as the class name, where the method name may or may not or be class name.
Constructor does not allow any return type, where methods allow return type.