Difference between null and empty ("") Java String
The empty string is distinct from a
null reference in that in an
object-oriented programming language a
null reference to a string type
doesn't point to a string object and
will cause an error were one to try to
perform any operation on it. The empty
string is still a string upon which
string operations may be attempted.
From the wikipedia article on empty string.
How to modify existing, unpushed commit messages?
On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I'll write down in detail how I did this especially for people who have no experience in Vim!
I wanted to change my five latest commits that I already pushed to the server. This is quite 'dangerous' because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:
Let's say you want to change your five latest commits, and then you type this in the terminal:
git rebase -i HEAD~5
*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).
This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:
pick <commit hash> commit message
Instead of pick
you need to write reword
. You can do this in Vim by typing in i
. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword
instead of pick
.
Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :
. The command to save and quit is wq
. So if you type in :wq
you’re on the right track.
Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!
Then, if you already pushed your wrong commits, you need to git push --force
to overwrite them. Remember that git push --force
is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!
Now you have changed your commit messages!
(As you see, I'm not that experienced in Vim, so if I used the wrong 'lingo' to explain what's happening, feel free to correct me!)
How do you find what version of libstdc++ library is installed on your linux machine?
The mechanism I tend to use is a combination of readelf -V
to dump the .gnu.version
information from libstdc++, and then a lookup table that matches the largest GLIBCXX_
value extracted.
readelf -sV /usr/lib/libstdc++.so.6 | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1
if your version of sort
is too old to have the -V
option (which sorts by version number) then you can use:
tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'
instead of the sort -u -V
, to sort by up to 4 version digits.
In general, matching the ABI version should be good enough.
If you're trying to track down the libstdc++.so.<VERSION>
, though, you can use a little bash like:
file=/usr/lib/libstdc++.so.6
while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}
so for my system this yielded 6.0.10
.
If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the libstdc++.so that was used for the application, and then having a run script that does an:
export LD_LIBRARY_PATH=<directory of stashed libstdc++.so>
exec application.bin "$@"
generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.
How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?
I found the following worked for me in a user defined function I created. I concatenated the cell range reference and worksheet name as a string and then used in an Evaluate statement (I was using Evaluate on Sumproduct).
For example:
Function SumRange(RangeName as range)
Dim strCellRef, strSheetName, strRngName As String
strCellRef = RangeName.Address
strSheetName = RangeName.Worksheet.Name & "!"
strRngName = strSheetName & strCellRef
Then refer to strRngName in the rest of your code.
JavaScript pattern for multiple constructors
Answering because this question is returned first in
google but the answers are now outdated.
You can use Destructuring objects as constructor parameters in ES6
Here's the pattern:
You can't have multiple constructors, but you can use destructuring and default values to do what you want.
export class myClass {
constructor({ myArray = [1, 2, 3], myString = 'Hello World' }) {
// ..
}
}
And you can do this if you want to support a 'parameterless' constructor.
export class myClass {
constructor({myArray = [1, 2, 3], myString = 'Hello World'} = {}) {
// ..
}
}
How do JavaScript closures work?
A closure is something many JavaScript developers use all the time, but we take it for granted. How it works is not that complicated. Understanding how to use it purposefully is complex.
At its simplest definition (as other answers have pointed out), a closure is basically a function defined inside another function. And that inner function has access to variables defined in the scope of the outer function. The most common practice that you'll see using closures is defining variables and functions in the global scope, and having access to those variables in the function scope of that function.
var x = 1;
function myFN() {
alert(x); //1, as opposed to undefined.
}
// Or
function a() {
var x = 1;
function b() {
alert(x); //1, as opposed to undefined.
}
b();
}
So what?
A closure isn't that special to a JavaScript user until you think about what life would be like without them. In other languages, variables used in a function get cleaned up when that function returns. In the above, x would have been a "null pointer", and you'd need to establish a getter and setter and start passing references. Doesn't sound like JavaScript right? Thank the mighty closure.
Why should I care?
You don't really have to be aware of closures to use them. But as others have also pointed out, they can be leveraged to create faux private variables. Until you get to needing private variables, just use them like you always have.
How to view file diff in git before commit
I think this is the perfect use case warranting a GUI. - Although I totally understand that it can also be achieved well enough within the command line.
Personally, every commit of mine, I do from the git-gui. In which I can make multiple atomic commits with separate hunks/lines if it makes sense to do so.
Gut Gui enables viewing of the diffs in a well formatted colored interface, is rather light. Looks like this is something you should checkout too.
In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
How to format a QString?
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn't require changing the format string, e.g.
// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
How can I set selected option selected in vue.js 2?
You simply need to remove v-bind (:) from selected and required attributes.
Like this :-
_x000D_
_x000D_
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
_x000D_
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
How to avoid "Permission denied" when using pip with virtualenv
In my case, I was using mkvirtualenv
, but didn't tell it I was going to be using python3. I got this error:
mkvirtualenv hug
pip3 install hug -U
....
error: could not create '/usr/lib/python3.4/site-packages': Permission denied
It worked after specifying python3:
mkvirtualenv --python=/usr/bin/python3 hug
pip3 install hug -U
Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project
I suddenly started receiving this error when attempting to push changes from VS2017 to a VSTS Git repository. This functionality had worked the day before.
I checked my git.log file and saw a different exception :-
19:43:57.116665 ...zureAuthority.cs:184 trace: [ValidateCredentials] server returned: 'Unable to connect to the remote server.
I downloaded the latest Git CredentialManager source from Gits Credential Manager repo and debugged it.
Once authenticated, the following exception occurred :-
No connection could be made because the target machine actively refused it 127.0.0.1:8888
I then realised that I had recently setup Fiddler to act as a proxy for all services as per the article capturing-traffic-from-.net-services-with-fiddler
Once I ran Fiddler, I was able to successfully connect.
How to declare local variables in postgresql?
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
Why does javascript replace only first instance when using replace?
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here.
Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
In C#, how to check whether a string contains an integer?
You can check if string contains numbers only:
Regex.IsMatch(myStringVariable, @"^-?\d+$")
But number can be bigger than Int32.MaxValue
or less than Int32.MinValue
- you should keep that in mind.
Another option - create extension method and move ugly code there:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
That will make your code more clean:
if (myStringVariable.IsInteger())
// ...
How do I sort an NSMutableArray with custom objects in it?
I did this in iOS 4 using a block.
Had to cast the elements of my array from id to my class type.
In this case it was a class called Score with a property called points.
Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame
, however in my code I though an exception.
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
Score *s1 = obj1;
Score *s2 = obj2;
if (s1.points > s2.points) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1.points < s2.points) {
return (NSComparisonResult)NSOrderedDescending;
}
}
// TODO: default is the same?
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
PS: This is sorting in descending order.
Difference between Hive internal tables and external tables?
The only difference in behaviour (not the intended usage) based on my limited research and testing so far (using Hive 1.1.0 -cdh5.12.0) seems to be that when a table is dropped
- the data of the Internal (Managed) tables gets deleted from the HDFS file system
- while the data of the External tables does NOT get deleted from the HDFS file system.
(NOTE: See Section 'Managed and External Tables' in https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL which list some other difference which I did not completely understand)
I believe Hive chooses the location where it needs to create the table based on the following precedence from top to bottom
- Location defined during the Table Creation
- Location defined in the Database/Schema Creation in which the table is created.
- Default Hive Warehouse Directory (Property hive.metastore.warehouse.dir in hive.site.xml)
When the "Location" option is not used during the "creation of a hive table", the above precedence rule is used. This is applicable for both Internal and External tables. This means an Internal table does not necessarily have to reside in the Warehouse directory and can reside anywhere else.
Note: I might have missed some scenarios, but based on my limited exploration, the behaviour of both Internal and Extenal table seems to be the same except for the one difference (data deletion) described above. I tried the following scenarios for both Internal and External tables.
- Creating table with and without Location option
- Creating table with and without Partition Option
- Adding new data using the Hive Load and Insert Statements
- Adding data files to the Table location outside of Hive (using HDFS commands) and refreshing the table using the "MSCK REPAIR TABLE command
- Dropping the tables
Why does viewWillAppear not get called when an app comes back from the background?
Swift
Short answer
Use a NotificationCenter
observer rather than viewWillAppear
.
override func viewDidLoad() {
super.viewDidLoad()
// set observer for UIApplication.willEnterForegroundNotification
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
// my selector that was defined above
@objc func willEnterForeground() {
// do stuff
}
Long answer
To find out when an app comes back from the background, use a NotificationCenter
observer rather than viewWillAppear
. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)
import UIKit
class ViewController: UIViewController {
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
// add notification observers
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
print("view will appear")
}
override func viewDidAppear(_ animated: Bool) {
print("view did appear")
}
// MARK: - Notification oberserver methods
@objc func didBecomeActive() {
print("did become active")
}
@objc func willEnterForeground() {
print("will enter foreground")
}
}
On first starting the app, the output order is:
view did load
view will appear
did become active
view did appear
After pushing the home button and then bringing the app back to the foreground, the output order is:
will enter foreground
did become active
So if you were originally trying to use viewWillAppear
then UIApplication.willEnterForegroundNotification
is probably what you want.
Note
As of iOS 9 and later, you don't need to remove the observer. The documentation states:
If your app targets iOS 9.0 and later or macOS 10.11 and later, you
don't need to unregister an observer in its dealloc
method.
Font is not available to the JVM with Jasper Reports
I tried installing mscorefonts, but the package was installed and up-to-date.
sudo apt-get update
sudo apt-get install ttf-mscorefonts-installer
I tried searching for the font in the filesystem, with:
ls /usr/share/fonts/truetype/msttcorefonts/
This folder just had the README, with the correct instructions on how to install.
cat /usr/share/fonts/truetype/msttcorefonts/README
You need an internet connection for this:
sudo apt-get install --reinstall ttf-mscorefonts-installer
I re-installed ttf-mscorefonts-installer
(as shown above, making sure to accept the EULA!) and the problem was solved.
Formatting MM/DD/YYYY dates in textbox in VBA
This is the same concept as Siddharth Rout's answer. But I wanted a date picker which could be fully customized so that the look and feel could be tailored to whatever project it's being used in.
You can click this link to download the custom date picker I came up with. Below are some screenshots of the form in action.
To use the date picker, simply import the CalendarForm.frm file into your VBA project. Each of the calendars above can be obtained with one single function call. The result just depends on the arguments you use (all of which are optional), so you can customize it as much or as little as you want.
For example, the most basic calendar on the left can be obtained by the following line of code:
MyDateVariable = CalendarForm.GetDate
That's all there is to it. From there, you just include whichever arguments you want to get the calendar you want. The function call below will generate the green calendar on the right:
MyDateVariable = CalendarForm.GetDate( _
SelectedDate:=Date, _
DateFontSize:=11, _
TodayButton:=True, _
BackgroundColor:=RGB(242, 248, 238), _
HeaderColor:=RGB(84, 130, 53), _
HeaderFontColor:=RGB(255, 255, 255), _
SubHeaderColor:=RGB(226, 239, 218), _
SubHeaderFontColor:=RGB(55, 86, 35), _
DateColor:=RGB(242, 248, 238), _
DateFontColor:=RGB(55, 86, 35), _
SaturdayFontColor:=RGB(55, 86, 35), _
SundayFontColor:=RGB(55, 86, 35), _
TrailingMonthFontColor:=RGB(106, 163, 67), _
DateHoverColor:=RGB(198, 224, 180), _
DateSelectedColor:=RGB(169, 208, 142), _
TodayFontColor:=RGB(255, 0, 0), _
DateSpecialEffect:=fmSpecialEffectRaised)
Here is a small taste of some of the features it includes. All options are fully documented in the userform module itself:
- Ease of use. The userform is completely self-contained, and can be imported into any VBA project and used without much, if any additional coding.
- Simple, attractive design.
- Fully customizable functionality, size, and color scheme
- Limit user selection to a specific date range
- Choose any day for the first day of the week
- Include week numbers, and support for ISO standard
- Clicking the month or year label in the header reveals selectable comboboxes
- Dates change color when you mouse over them
Horizontal scroll css?
I figured it this way:
* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }
.red { background: red }
.blue { background: blue }
.yellow { background: yellow }
.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }
<div class="header red"></div>
<div class="wrapper">
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
</div>
I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.
Redirect Windows cmd stdout and stderr to a single file
There is, however, no guarantee that the output of SDTOUT
and STDERR
are interweaved line-by-line in timely order, using the POSIX
redirect merge syntax.
If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.
A dedicated console output logger (I.e. the "StdOut/StdErr Logger"
by 'LoRd MuldeR'
) may be more reliable for such a task.
See: MuldeR's OpenSource Projects
How to find the socket connection state in C?
The only way to reliably detect if a socket is still connected is to periodically try to send data. Its usually more convenient to define an application level 'ping' packet that the clients ignore, but if the protocol is already specced out without such a capability you should be able to configure tcp sockets to do this by setting the SO_KEEPALIVE socket option. I've linked to the winsock documentation, but the same functionality should be available on all BSD-like socket stacks.
How to install Flask on Windows?
First install flask using pip,
pip install Flask
* If pip is not installed then install pip
Then copy below program (hello.py)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Now, run the program
python hello.py
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Just copy paste the above address line in your browser.
Reference: http://flask.pocoo.org/
How to write subquery inside the OUTER JOIN Statement
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output
What does "var" mean in C#?
It means the data type is derived (implied) from the context.
From http://msdn.microsoft.com/en-us/library/bb383973.aspx
Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. An
implicitly typed local variable is
strongly typed just as if you had
declared the type yourself, but the
compiler determines the type. The
following two declarations of i are
functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
var
is useful for eliminating keyboard typing and visual noise, e.g.,
MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();
becomes
var x = new MyReallyReallyLongClassName();
but can be overused to the point where readability is sacrificed.
Java LinkedHashMap get first or last entry
One more way to get first and last entry of a LinkedHashMap is to use toArray()
method of Set interface.
But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.
The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")
].
Here is a small example to demonstrate the usage of toArray()
method:
public static void main(final String[] args) {
final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
orderMap.put(6, "Six");
orderMap.put(7, "Seven");
orderMap.put(3, "Three");
orderMap.put(100, "Hundered");
orderMap.put(10, "Ten");
final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
final int maplength = mapValues.size();
final Entry<Integer,String>[] test = new Entry[maplength];
mapValues.toArray(test);
System.out.print("First Key:"+test[0].getKey());
System.out.println(" First Value:"+test[0].getValue());
System.out.print("Last Key:"+test[maplength-1].getKey());
System.out.println(" Last Value:"+test[maplength-1].getValue());
}
// the output geneated is :
First Key:6 First Value:Six
Last Key:10 Last Value:Ten
Avoid synchronized(this) in Java?
Avoid using synchronized(this)
as a locking mechanism: This locks the whole class instance and can cause deadlocks. In such cases, refactor the code to lock only a specific method or variable, that way whole class doesn't get locked. Synchronised
can be used inside method level.
Instead of using synchronized(this)
, below code shows how you could just lock a method.
public void foo() {
if(operation = null) {
synchronized(foo) {
if (operation == null) {
// enter your code that this method has to handle...
}
}
}
}
How to merge multiple dicts with same key or different key?
To supplement the two-list solutions, here is a solution for processing a single list.
A sample list (NetworkX-related; manually formatted here for readability):
ec_num_list = [((src, tgt), ec_num['ec_num']) for src, tgt, ec_num in G.edges(data=True)]
print('\nec_num_list:\n{}'.format(ec_num_list))
ec_num_list:
[((82, 433), '1.1.1.1'),
((82, 433), '1.1.1.2'),
((22, 182), '1.1.1.27'),
((22, 3785), '1.2.4.1'),
((22, 36), '6.4.1.1'),
((145, 36), '1.1.1.37'),
((36, 154), '2.3.3.1'),
((36, 154), '2.3.3.8'),
((36, 72), '4.1.1.32'),
...]
Note the duplicate values for the same edges (defined by the tuples). To collate those "values" to their corresponding "keys":
from collections import defaultdict
ec_num_collection = defaultdict(list)
for k, v in ec_num_list:
ec_num_collection[k].append(v)
print('\nec_num_collection:\n{}'.format(ec_num_collection.items()))
ec_num_collection:
[((82, 433), ['1.1.1.1', '1.1.1.2']), ## << grouped "values"
((22, 182), ['1.1.1.27']),
((22, 3785), ['1.2.4.1']),
((22, 36), ['6.4.1.1']),
((145, 36), ['1.1.1.37']),
((36, 154), ['2.3.3.1', '2.3.3.8']), ## << grouped "values"
((36, 72), ['4.1.1.32']),
...]
If needed, convert that list to dict:
ec_num_collection_dict = {k:v for k, v in zip(ec_num_collection, ec_num_collection)}
print('\nec_num_collection_dict:\n{}'.format(dict(ec_num_collection)))
ec_num_collection_dict:
{(82, 433): ['1.1.1.1', '1.1.1.2'],
(22, 182): ['1.1.1.27'],
(22, 3785): ['1.2.4.1'],
(22, 36): ['6.4.1.1'],
(145, 36): ['1.1.1.37'],
(36, 154): ['2.3.3.1', '2.3.3.8'],
(36, 72): ['4.1.1.32'],
...}
References
Placing a textview on top of imageview in android
Try this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src=//source of image />
<TextView
android:id="@+id/ImageViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/ImageView"
android:layout_alignTop="@id/ImageView"
android:layout_alignRight="@id/ImageView"
android:layout_alignBottom="@id/ImageView"
android:text=//u r text here
android:gravity="center"
/>
Hope this could help you.
Set HTML dropdown selected option using JSTL
In Servlet do:
String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);
Then in JSP do:
<select name="roleName">
<c:forEach items="${roleNames}" var="role">
<option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
</c:forEach>
</select>
It will print the selected
attribute of the HTML <option>
element so that you end up like:
<select name="roleName">
<option value="cat">cat</option>
<option value="rat" selected>rat</option>
<option value="unicorn">unicorn</option>
</select>
Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.
How to get JSON from URL in JavaScript?
this morning, i also had the same doubt and now its cleared
i had just used JSON with 'open-weather-map'(https://openweathermap.org/) api and got data from the URL in the index.html file,
the code looks like this:-
_x000D_
_x000D_
//got location_x000D_
var x = document.getElementById("demo");_x000D_
if (navigator.geolocation) {_x000D_
navigator.geolocation.getCurrentPosition(weatherdata);_x000D_
} else { _x000D_
x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
}_x000D_
//fetch openweather map url with api key_x000D_
function weatherdata(position) {_x000D_
//put corrdinates to get weather data of that location_x000D_
fetch('https://api.openweathermap.org/data/2.5/weather?lat='+position.coords.latitude+'&lon='+position.coords.longitude+'&appid=b2c336bb5abf01acc0bbb8947211fbc6')_x000D_
.then(response => response.json())_x000D_
.then(data => {_x000D_
console.log(data);_x000D_
document.getElementById("demo").innerHTML = _x000D_
'<br>wind speed:-'+data.wind.speed + _x000D_
'<br>humidity :-'+data.main.humidity + _x000D_
'<br>temprature :-'+data.main.temp _x000D_
});_x000D_
}
_x000D_
<div id="demo"></div>
_x000D_
_x000D_
_x000D_
i had give api key openly because i had free subscription, just have a free subscriptions in beginning.
you can find some good free api's and keys at "rapidapi.com"
How to understand nil vs. empty vs. blank in Ruby
nil?
can be used on any object. It determines if the object has any value or not, including 'blank' values.
For example:
example = nil
example.nil? # true
"".nil? # false
Basically nil?
will only ever return true if the object is in fact equal to 'nil'.
empty?
is only called on objects that are considered a collection. This includes things like strings (a collection of characters), hashes (a collection of key/value pairs) and arrays (a collection of arbitrary objects). empty?
returns true is there are no items in the collection.
For example:
"".empty? # true
"hi".empty? # false
{}.empty? # true
{"" => ""}.empty? # false
[].empty? # true
[nil].empty? # false
nil.empty? # NoMethodError: undefined method `empty?' for nil:NilClass
Notice that empty?
can't be called on nil objects as nil objects are not a collection and it will raise an exception.
Also notice that even if the items in a collection are blank, it does not mean a collection is empty.
blank?
is basically a combination of nil?
and empty?
It's useful for checking objects that you assume are collections, but could also be nil.
Switch: Multiple values in one case?
1 - 8 = -7
9 - 15 = -6
16 - 100 = -84
You have:
case -7:
...
break;
case -6:
...
break;
case -84:
...
break;
Either use:
case 1:
case 2:
case 3:
etc, or (perhaps more readable) use:
if(age >= 1 && age <= 8) {
...
} else if (age >= 9 && age <= 15) {
...
} else if (age >= 16 && age <= 100) {
...
} else {
...
}
etc
How to check if anonymous object has a method?
You want hasOwnProperty()
:
_x000D_
_x000D_
var myObj1 = { _x000D_
prop1: 'no',_x000D_
prop2: function () { return false; }_x000D_
}_x000D_
var myObj2 = { _x000D_
prop1: 'no'_x000D_
}_x000D_
_x000D_
console.log(myObj1.hasOwnProperty('prop2')); // returns true_x000D_
console.log(myObj2.hasOwnProperty('prop2')); // returns false_x000D_
_x000D_
_x000D_
_x000D_
References: Mozilla, Microsoft, phrogz.net.
Git checkout: updating paths is incompatible with switching branches
I suspect there is no remote branch named remote-name, but that you've inadvertently created a local branch named origin/remote-name.
Is it possible you at some point typed:
git branch origin/remote-name
Thus creating a local branch named origin/remote-name? Type this command:
git checkout origin/remote-name
You'll either see:
Switched to branch "origin/remote-name"
which means it's really a mis-named local branch, or
Note: moving to "origin/rework-isscoring" which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b
which means it really is a remote branch.
Extract file name from path, no matter what the os/path format
In your example you will also need to strip slash from right the right side to return c
:
>>> import os
>>> path = 'a/b/c/'
>>> path = path.rstrip(os.sep) # strip the slash from the right side
>>> os.path.basename(path)
'c'
Second level:
>>> os.path.filename(os.path.dirname(path))
'b'
update: I think lazyr
has provided the right answer. My code will not work with windows-like paths on unix systems and vice versus with unix-like paths on windows system.
There is already an open DataReader associated with this Command which must be closed first
It appears that you're calling DateLastUpdated from within an active query using the same EF context and DateLastUpdate issues a command to the data store itself. Entity Framework only supports one active command per context at a time.
You can refactor your above two queries into one like this:
return accounts.AsEnumerable()
.Select((account, index) => new AccountsReport()
{
RecordNumber = FormattedRowNumber(account, index + 1),
CreditRegistryId = account.CreditRegistryId,
DateLastUpdated = (
from h in context.AccountHistory
where h.CreditorRegistryId == creditorRegistryId
&& h.AccountNo == accountNo
select h.LastUpdated).Max(),
AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
})
.OrderBy(c=>c.FormattedRecordNumber)
.ThenByDescending(c => c.StateChangeDate);
I also noticed you're calling functions like FormattedAccountNumber and FormattedRecordNumber in the queries. Unless these are stored procs or functions you've imported from your database into the entity data model and mapped correct, these will also throw excepts as EF will not know how to translate those functions in to statements it can send to the data store.
Also note, calling AsEnumerable doesn't force the query to execute. Until the query execution is deferred until enumerated. You can force enumeration with ToList or ToArray if you so desire.
java: use StringBuilder to insert at the beginning
Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder
Filtering Pandas Dataframe using OR statement
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
Initialize class fields in constructor or at declaration?
Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you.
Conda version pip install -r requirements.txt --target ./lib
You can always try this:
/home/user/anaconda3/bin/pip install -r requirements.txt
This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command
conda install pip
Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?
Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.
You can find creation/deletion of environments in the Anaconda documentation.
Hope this helped.
onKeyPress Vs. onKeyUp and onKeyDown
Just wanted to share a curiosity:
when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!
For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !
Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!
Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK
and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.
Finding Variable Type in JavaScript
Here is the Complete solution.
You can also use it as a Helper class in your Projects.
_x000D_
_x000D_
"use strict";_x000D_
/**_x000D_
* @description Util file_x000D_
* @author Tarandeep Singh_x000D_
* @created 2016-08-09_x000D_
*/_x000D_
_x000D_
window.Sys = {};_x000D_
_x000D_
Sys = {_x000D_
isEmptyObject: function(val) {_x000D_
return this.isObject(val) && Object.keys(val).length;_x000D_
},_x000D_
/** This Returns Object Type */_x000D_
getType: function(val) {_x000D_
return Object.prototype.toString.call(val);_x000D_
},_x000D_
/** This Checks and Return if Object is Defined */_x000D_
isDefined: function(val) {_x000D_
return val !== void 0 || typeof val !== 'undefined';_x000D_
},_x000D_
/** Run a Map on an Array **/_x000D_
map: function(arr, fn) {_x000D_
var res = [],_x000D_
i = 0;_x000D_
for (; i < arr.length; ++i) {_x000D_
res.push(fn(arr[i], i));_x000D_
}_x000D_
arr = null;_x000D_
return res;_x000D_
},_x000D_
/** Checks and Return if the prop is Objects own Property */_x000D_
hasOwnProp: function(obj, val) {_x000D_
return Object.prototype.hasOwnProperty.call(obj, val);_x000D_
},_x000D_
/** Extend properties from extending Object to initial Object */_x000D_
extend: function(newObj, oldObj) {_x000D_
if (this.isDefined(newObj) && this.isDefined(oldObj)) {_x000D_
for (var prop in oldObj) {_x000D_
if (this.hasOwnProp(oldObj, prop)) {_x000D_
newObj[prop] = oldObj[prop];_x000D_
}_x000D_
}_x000D_
return newObj;_x000D_
} else {_x000D_
return newObj || oldObj || {};_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
// This Method will create Multiple functions in the Sys object that can be used to test type of_x000D_
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']_x000D_
.forEach(_x000D_
function(name) {_x000D_
Sys['is' + name] = function(obj) {_x000D_
return toString.call(obj) == '[object ' + name + ']';_x000D_
};_x000D_
}_x000D_
);
_x000D_
<h1>Use the Helper JavaScript Methods..</h1>_x000D_
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>
_x000D_
_x000D_
_x000D_
For Exportable CommonJs Module or RequireJS Module....
"use strict";
/*** Helper Utils ***/
/**
* @description Util file :: From Vault
* @author Tarandeep Singh
* @created 2016-08-09
*/
var Sys = {};
Sys = {
isEmptyObject: function(val){
return this.isObject(val) && Object.keys(val).length;
},
/** This Returns Object Type */
getType: function(val){
return Object.prototype.toString.call(val);
},
/** This Checks and Return if Object is Defined */
isDefined: function(val){
return val !== void 0 || typeof val !== 'undefined';
},
/** Run a Map on an Array **/
map: function(arr,fn){
var res = [], i=0;
for( ; i<arr.length; ++i){
res.push(fn(arr[i], i));
}
arr = null;
return res;
},
/** Checks and Return if the prop is Objects own Property */
hasOwnProp: function(obj, val){
return Object.prototype.hasOwnProperty.call(obj, val);
},
/** Extend properties from extending Object to initial Object */
extend: function(newObj, oldObj){
if(this.isDefined(newObj) && this.isDefined(oldObj)){
for(var prop in oldObj){
if(this.hasOwnProp(oldObj, prop)){
newObj[prop] = oldObj[prop];
}
}
return newObj;
}else {
return newObj || oldObj || {};
}
}
};
/**
* This isn't Required but just makes WebStorm color Code Better :D
* */
Sys.isObject
= Sys.isArguments
= Sys.isFunction
= Sys.isString
= Sys.isArray
= Sys.isUndefined
= Sys.isDate
= Sys.isNumber
= Sys.isRegExp
= "";
/** This Method will create Multiple functions in the Sys object that can be used to test type of **/
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
function(name) {
Sys['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
}
);
module.exports = Sys;
Currently in Use on a public git repo.
Github Project
Now you can import this Sys code in a Sys.js file.
then you can use this Sys object functions to find out the type of JavaScript Objects
you can also check is Object is Defined or type is Function or the Object is Empty... etc.
- Sys.isObject
- Sys.isArguments
- Sys.isFunction
- Sys.isString
- Sys.isArray
- Sys.isUndefined
- Sys.isDate
- Sys.isNumber
- Sys.isRegExp
For Example
var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);
console.log(Sys.isDefined(jQuery));
How to determine whether code is running in DEBUG / RELEASE build?
For a solution in Swift please refer to this thread on SO.
Basically the solution in Swift would look like this:
#if DEBUG
println("I'm running in DEBUG mode")
#else
println("I'm running in a non-DEBUG mode")
#endif
Additionally you will need to set the DEBUG
symbol in Swift Compiler - Custom Flags
section for the Other Swift Flags
key via a -D DEBUG
entry. See the following screenshot for an example:
How to validate phone number using PHP?
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
How to write DataFrame to postgres table?
Faster option:
The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.
Create an engine based on your DB specifications.
Create a table in your postgres DB that has equal number of columns as the Dataframe (df).
Data in DF will get inserted in your postgres table.
from sqlalchemy import create_engine
import psycopg2
import io
if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
How to add title to seaborn boxplot
sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation
you can add title using 'set' method as below:
sns.boxplot('Day', 'Count', data=gg).set(title='lalala')
you can also add other parameters like xlabel, ylabel to the set method.
sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')
There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.
A generic error occurred in GDI+, JPEG Image to MemoryStream
I found that if one of the parent folders where I was saving the file had a trailing space then GDI+ would throw the generic exception.
In other words, if I tried to save to "C:\Documents and Settings\myusername\Local Settings\Temp\ABC DEF M1 Trended Values \Images\picture.png" then it threw the generic exception.
My folder name was being generated from a file name that happened to have a trailing space so it was easy to .Trim() that and move on.
How to get nth jQuery element
if you have control over the query which builds the jQuery object, use :eq()
$("div:eq(2)")
If you don't have control over it (for example, it's being passed from another function or something), then use .eq()
var $thirdElement = $jqObj.eq(2);
Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()
var $third4th5thElements = $jqObj.slice(2, 5);
How to print Unicode character in C++?
To represent the character you can use Universal Character Names (UCNs). The character '?' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.
// both of these assume that the character can be represented with
// a single char in the execution encoding
char b = '\u0444';
char a = '?'; // this line additionally assumes that the source character encoding supports this character
Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:
#include <iostream>
int main() {
std::cout << "Hello, ? or \u0444!\n";
}
This program does not require that '?' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).
Things are harder with Windows and there are different possibilities with different tradeoffs.
Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"Hello, \u0444!\n";
}
Portable code is more difficult.
File upload along with other object in Jersey restful web service
You can access the Image File and data from a form using MULTIPART FORM DATA By using the below code.
@POST
@Path("/UpdateProfile")
@Consumes(value={MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})
@Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response updateProfile(
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
@FormDataParam("ProfileInfo") String ProfileInfo,
@FormDataParam("registrationId") String registrationId) {
String filePath= "/filepath/"+contentDispositionHeader.getFileName();
OutputStream outputStream = null;
try {
int read = 0;
byte[] bytes = new byte[1024];
outputStream = new FileOutputStream(new File(filePath));
while ((read = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch(Exception ex) {}
}
}
}
nginx showing blank PHP pages
For reference, I am attaching my location
block for catching files with the .php
extension:
location ~ \.php$ {
include /path/to/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
Double-check the /path/to/fastcgi-params
, and make sure that it is present and readable by the nginx user.
Purpose of "%matplotlib inline"
Provided you are running IPython, the %matplotlib inline
will make your plot outputs appear and be stored within the notebook.
According to documentation
To set this up, before any plotting or import of matplotlib
is
performed you must execute the %matplotlib magic command
. This
performs the necessary behind-the-scenes setup for IPython to work
correctly hand in hand with matplotlib
; it does not, however,
actually execute any Python import commands, that is, no names are
added to the namespace.
A particularly interesting backend, provided by IPython, is the
inline
backend. This is available only for the Jupyter Notebook and
the Jupyter QtConsole. It can be invoked as follows:
%matplotlib inline
With this backend, the output of plotting commands is displayed inline
within frontends like the Jupyter notebook, directly below the code
cell that produced it. The resulting plots will then also be stored in
the notebook document.
Converting between java.time.LocalDateTime and java.util.Date
Here is what I came up with ( and like all Date Time conundrums it is probably going to be disproved based on some weird timezone-leapyear-daylight adjustment :D )
Round-tripping: Date
<<->> LocalDateTime
Given: Date date = [some date]
(1) LocalDateTime
<< Instant
<< Date
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
(2) Date
<< Instant
<< LocalDateTime
Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Example:
Given:
Date date = new Date();
System.out.println(date + " long: " + date.getTime());
(1) LocalDateTime
<< Instant
<< Date
:
Create Instant
from Date
:
Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("Instant from Date:\n" + instant);
Create Date
from Instant
(not necessary,but for illustration):
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
Create LocalDateTime
from Instant
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println("LocalDateTime from Instant:\n" + ldt);
(2) Date
<< Instant
<< LocalDateTime
Create Instant
from LocalDateTime
:
instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println("Instant from LocalDateTime:\n" + instant);
Create Date
from Instant
:
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
The output is:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
Instant from Date:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
LocalDateTime from Instant:
2013-11-01T14:13:04.574
Instant from LocalDateTime:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
What is the difference between public, private, and protected?
Public
: is a default state when you declare a variable or method, can be accessed by anything directly to the object.
Protected
: Can be accessed only within the object and subclasses.
Private
: Can be referenced only within the object, not subclasses.
Update a column value, replacing part of a string
You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.
LIKE ('...//domain1.com/images/%');
means all records that BEGIN with "...//domain1.com/images/"
and have anything AFTER (that's the %
for...)
Another example:
LIKE ('%http://domain1.com/images/%')
which means all records that contains "http://domain1.com/images/"
in any part of the string...
How to remove illegal characters from path and filenames?
If you have to use the method in many places in a project, you could also make an extension method and call it anywhere in the project for strings.
public static class StringExtension
{
public static string RemoveInvalidChars(this string originalString)
{
string finalString=string.Empty;
if (!string.IsNullOrEmpty(originalString))
{
return string.Concat(originalString.Split(Path.GetInvalidFileNameChars()));
}
return finalString;
}
}
You can call the above extension method as:
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
string afterIllegalChars = illegal.RemoveInvalidChars();
Width equal to content
By default p
tags are block
elements, which means they take 100% of the parent width
.
You can change their display property with:
#container p {
display:inline-block;
}
But it puts the elements side by side.
To keep each element on its own line you can use:
#container p {
clear:both;
float:left;
}
(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)
Demo: http://jsfiddle.net/CvJ3W/5/
Edit
If you go for the solution with display:inline-block
but want to keep each item in one line, you can just add a <br>
tag after each one:
<div id="container">
<p>Sample Text 1</p><br/>
<p>Sample Text 2</p><br/>
<p>Sample Text 3</p><br/>
</div>
New demo: http://jsfiddle.net/CvJ3W/7/
Mongoose, update values in array of objects
For each document, the update operator $set
can set multiple values, so rather than replacing the entire object in the items
array, you can set the name
and value
fields of the object individually.
{'$set': {'items.$.name': update.name , 'items.$.value': update.value}}
Angular 2: How to call a function after get a response from subscribe http.post
Update your get_categories()
method to return the total (wrapped in an observable):
// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
return this.http.post( url, body, {headers: headers, withCredentials:true})
.map(response => response.json());
}
In search_categories()
, you can subscribe the observable returned by get_categories()
(or you could keep transforming it by chaining more RxJS operators):
// send_categories() is now called after get_categories().
search_categories() {
this.get_categories(1)
// The .subscribe() method accepts 3 callbacks
.subscribe(
// The 1st callback handles the data emitted by the observable.
// In your case, it's the JSON data extracted from the response.
// That's where you'll find your total property.
(jsonData) => {
this.send_categories(jsonData.total);
},
// The 2nd callback handles errors.
(err) => console.error(err),
// The 3rd callback handles the "complete" event.
() => console.log("observable complete")
);
}
Note that you only subscribe ONCE, at the end.
Like I said in the comments, the .subscribe()
method of any observable accepts 3 callbacks like this:
obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
They must be passed in this order. You don't have to pass all three. Many times only the nextCallback
is implemented:
obs.subscribe(nextCallback);
How do I delete a local repository in git?
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.
if checkbox is checked, do this
Check this code:
<!-- script to check whether checkbox checked or not using prop function -->
<script>
$('#change_password').click(function(){
if($(this).prop("checked") == true){ //can also use $(this).prop("checked") which will return a boolean.
alert("checked");
}
else if($(this).prop("checked") == false){
alert("Checkbox is unchecked.");
}
});
</script>
What is "overhead"?
The meaning of the word can differ a lot with context. In general, it's resources (most often memory and CPU time) that are used, which do not contribute directly to the intended result, but are required by the technology or method that is being used. Examples:
- Protocol overhead: Ethernet frames, IP packets and TCP segments all have headers, TCP connections require handshake packets. Thus, you cannot use the entire bandwidth the hardware is capable of for your actual data. You can reduce the overhead by using larger packet sizes and UDP has a smaller header and no handshake.
- Data structure memory overhead: A linked list requires at least one pointer for each element it contains. If the elements are the same size as a pointer, this means a 50% memory overhead, whereas an array can potentially have 0% overhead.
- Method call overhead: A well-designed program is broken down into lots of short methods. But each method call requires setting up a stack frame, copying parameters and a return address. This represents CPU overhead compared to a program that does everything in a single monolithic function. Of course, the added maintainability makes it very much worth it, but in some cases, excessive method calls can have a significant performance impact.
Convert Promise to Observable
import { from } from 'rxjs';
from(firebase.auth().createUserWithEmailAndPassword(email, password))
.subscribe((user: any) => {
console.log('test');
});
Here is a shorter version using a combination of some of the answers above to convert your code from a promise to an observable.
How to inflate one view with a layout
Try this code :
- If you just want to inflate your layout :
_x000D_
_x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout_x000D_
RelativeLayout item = view.findViewById(R.id.item);
_x000D_
_x000D_
_x000D_
- If you want to inflate your layout in container(parent layout) :
_x000D_
_x000D_
LinearLayout parent = findViewById(R.id.container); //parent layout._x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); _x000D_
RelativeLayout item = view.findViewById(R.id.item); //initialize layout & By this you can also perform any event._x000D_
parent.addView(view); //adding your inflated layout in parent layout.
_x000D_
_x000D_
_x000D_
Exit a Script On Error
If you put set -e
in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.
The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.
Commands whose status is tested by a conditional (such as if
, &&
or ||
) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true
. You can also turn set -e
off for a part of the script with set +e
.
How to Apply Corner Radius to LinearLayout
Layout
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@drawable/rounded_edge">
</LinearLayout>
Drawable folder rounded_edge.xml
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@android:color/darker_gray">
</solid>
<stroke
android:width="0dp"
android:color="#424242">
</stroke>
<corners
android:topLeftRadius="100dip"
android:topRightRadius="100dip"
android:bottomLeftRadius="100dip"
android:bottomRightRadius="100dip">
</corners>
</shape>
Are there any disadvantages to always using nvarchar(MAX)?
firstly I thought about this, but then thought again. There are performance implications, but equally it does serve as a form of documentation to have an idea what size the fields really are. And it does enforce when that database sits in a larger ecosystem. In my opinion the key is to be permissive but only within reason.
ok, here's my feelings simply on the issue of business and data layer logic. It depends, if your DB is a shared resource between systems that share business logic then of course it seems a natural place to enforce such logic, but its not the BEST way to do it, the BEST way is to provide an API, this allows the interaction to be tested and keeps business logic where it belongs, it keeps systems decoupled, it keeps your tiers within a system decoupled. If however your database is supposed to be serving only one application, then lets get AGILE in thinking, what's true now? design for now. If and when such access is needed, provide an API to that data.
obviously though, this is just the ideal, if you are working with an existing system the likelyhood is that you will need to do it differently at least in the short term.
How to create a new instance from a class object in Python
This is how you can dynamically create a class named Child
in your code, assuming Parent
already exists... even if you don't have an explicit Parent
class, you could use object
...
The code below defines __init__()
and then associates it with the class.
>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
# Initialization for the Child class
self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>
Twitter Bootstrap Button Text Word Wrap
Try this: add white-space: normal; to the style definition of the Bootstrap Button or you can replace the code you displayed with the one below
<div class="col-lg-3"> <!-- FIRST COL -->
<div class="panel panel-default">
<div class="panel-body">
<h4>Posted on</h4>
<p>22nd September 2013</p>
<h4>Tags</h4>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
</div>
</div>
</div>
I have updated your fiddle here to show how it comes out.
Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell
I wanted a solution to copy files modified after a certain date and time which mean't I need to use Get-ChildItem piped through a filter. Below is what I came up with:
$SourceFolder = "C:\Users\RCoode\Documents\Visual Studio 2010\Projects\MyProject"
$ArchiveFolder = "J:\Temp\Robin\Deploy\MyProject"
$ChangesStarted = New-Object System.DateTime(2013,10,16,11,0,0)
$IncludeFiles = ("*.vb","*.cs","*.aspx","*.js","*.css")
Get-ChildItem $SourceFolder -Recurse -Include $IncludeFiles | Where-Object {$_.LastWriteTime -gt $ChangesStarted} | ForEach-Object {
$PathArray = $_.FullName.Replace($SourceFolder,"").ToString().Split('\')
$Folder = $ArchiveFolder
for ($i=1; $i -lt $PathArray.length-1; $i++) {
$Folder += "\" + $PathArray[$i]
if (!(Test-Path $Folder)) {
New-Item -ItemType directory -Path $Folder
}
}
$NewPath = Join-Path $ArchiveFolder $_.FullName.Replace($SourceFolder,"")
Copy-Item $_.FullName -Destination $NewPath
}
How to set the width of a RaisedButton in Flutter?
As said in documentation here
Raised buttons have a minimum size of 88.0 by 36.0 which can be
overidden with ButtonTheme.
You can do it like that
ButtonTheme(
minWidth: 200.0,
height: 100.0,
child: RaisedButton(
onPressed: () {},
child: Text("test"),
),
);
Proper Linq where clauses
when i run
from c in Customers
where c.CustomerID == 1
where c.CustomerID == 2
where c.CustomerID == 3
select c
and
from c in Customers
where c.CustomerID == 1 &&
c.CustomerID == 2 &&
c.CustomerID == 3
select c customer table in linqpad
against my Customer table it output the same sql query
-- Region Parameters
DECLARE @p0 Int = 1
DECLARE @p1 Int = 2
DECLARE @p2 Int = 3
-- EndRegion
SELECT [t0].[CustomerID], [t0].[CustomerName]
FROM [Customers] AS [t0]
WHERE ([t0].[CustomerID] = @p0) AND ([t0].[CustomerID] = @p1) AND ([t0].[CustomerID] = @p2)
so in translation to sql there is no difference and you already have seen in other answers how they will be converted to lambda expressions
How can I open the interactive matplotlib window in IPython notebook?
If all you want to do is to switch from inline plots to interactive and back (so that you can pan/zoom), it is better to use %matplotlib magic.
#interactive plotting in separate window
%matplotlib qt
and back to html
#normal charts inside notebooks
%matplotlib inline
%pylab magic imports a bunch of other things and may even result in a conflict. It does "from pylab import *".
You also can use new notebook backend (added in matplotlib 1.4):
#interactive charts inside notebooks, matplotlib 1.4+
%matplotlib notebook
If you want to have more interactivity in your charts, you can look at mpld3 and bokeh. mpld3 is great, if you don't have ton's of data points (e.g. <5k+) and you want to use normal matplotlib syntax, but more interactivity, compared to %matplotlib notebook . Bokeh can handle lots of data, but you need to learn it's syntax as it is a separate library.
Also you can check out pivottablejs (pip install pivottablejs)
from pivottablejs import pivot_ui
pivot_ui(df)
However cool interactive data exploration is, it can totally mess with reproducibility. It has happened to me, so I try to use it only at the very early stage and switch to pure inline matplotlib/seaborn, once I got the feel for the data.
Java method: Finding object in array list given a known attribute value
You have to loop through the entire array, there's no changing that. You can however, do it a little easier
for (Dog dog : list) {
if (dog.getId() == id) {
return dog; //gotcha!
}
}
return null; // dog not found.
or without the new for loop
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId() == id) {
return list.get(i);
}
}
How to capture no file for fs.readFileSync()?
You have to catch the error and then check what type of error it is.
try {
var data = fs.readFileSync(...)
} catch (err) {
// If the type is not what you want, then just throw the error again.
if (err.code !== 'ENOENT') throw err;
// Handle a file-not-found error
}
Oracle SQL Developer spool output?
I have found that if I save my query(spool_script_file.sql) and call it using this
@c:\client\queries\spool_script_file.sql as script(F5)
My output now is just the results with out the commands at the top.
I found this solution on the oracle forums.
What's the yield keyword in JavaScript?
Simplifying/elaborating on Nick Sotiros' answer (which I think is awesome), I think it's best to describe how one would start coding with yield
.
In my opinion, the biggest advantage of using yield
is that it will eliminate all the nested callback problems we see in code. It's hard to see how at first, which is why I decided to write this answer (for myself, and hopefully others!)
The way it does it is by introducing the idea of a co-routine, which is a function that can voluntarily stop/pause until it gets what it needs. In javascript, this is denoted by function*
. Only function*
functions can use yield
.
Here's some typical javascript:
loadFromDB('query', function (err, result) {
// Do something with the result or handle the error
})
This is clunky because now all of your code (which obviously needs to wait for this loadFromDB
call) needs to be inside this ugly looking callback. This is bad for a few reasons...
- All of your code is indented one level in
- You have this end
})
which you need to keep track of everywhere
- All this extra
function (err, result)
jargon
- Not exactly clear that you're doing this to assign a value to
result
On the other hand, with yield
, all of this can be done in one line with the help of the nice co-routine framework.
function* main() {
var result = yield loadFromDB('query')
}
And so now your main function will yield where necessary when it needs to wait for variables and things to load. But now, in order to run this, you need to call a normal (non-coroutine function). A simple co-routine framework can fix this problem so that all you have to do is run this:
start(main())
And start is defined (from Nick Sotiro' answer)
function start(routine, data) {
result = routine.next(data);
if(!result.done) {
result.value(function(err, data) {
if(err) routine.throw(err); // continue next iteration of routine with an exception
else start(routine, data); // continue next iteration of routine normally
});
}
}
And now, you can have beautiful code that is much more readable, easy to delete, and no need to fiddle with indents, functions, etc.
An interesting observation is that in this example, yield
is actually just a keyword you can put before a function with a callback.
function* main() {
console.log(yield function(cb) { cb(null, "Hello World") })
}
Would print "Hello World". So you can actually turn any callback function into using yield
by simply creating the same function signature (without the cb) and returning function (cb) {}
, like so:
function yieldAsyncFunc(arg1, arg2) {
return function (cb) {
realAsyncFunc(arg1, arg2, cb)
}
}
Hopefully with this knowledge you can write cleaner, more readable code that is easy to delete!
can't start MySql in Mac OS 10.6 Snow Leopard
Along with making sure you install the 64bit version, also check to make sure that the symbolic link of '/usr/local/mysql' is pointing to the correct version of your installation:
lrwxr-xr-x 1 root wheel 27B Aug 29 01:24 mysql -> mysql-5.1.37-osx10.5-x86_64
drwxr-xr-x 3 root wheel 102B Aug 29 01:25 mysql-5.1.30-osx10.5-x86
drwxr-xr-x 11 root wheel 374B Aug 29 15:59 mysql-5.1.37-osx10.5-x86_64
drwxr-xr-x 17 root wheel 578B Jul 13 22:06 mysql-5.1.37-osx10.5-x86_64.old
Alos, I found that after my installation, even though I used the pkg file from MySQL various other libraries would not build against the installation. The solution was to follow the steps to build MySQL from source found here. You can manually start it as root with the command:
/usr/loca/mysql/bin/mysqld_safe [whatever options you use]
Now ... to get the preference pane working I did the following:
- Installed 64bit version of MySQL Server packet from mysql.com
- Moved the package from mysql-5.1.37-osx10.5-x86_64 to mysql-5.1.37-osx10.5-x86_64.old
- Did a manual compile and installation of MySQL as per these instructions
Executed the following command:
sudo cp -R /usr/local/mysql-5.1.37-osx10.5-x86_64.old/support-files /usr/local/mysql/.
Opened up the MySQL Preference Pane and tada! it works
Using BeautifulSoup to search HTML for string
The following line is looking for the exact NavigableString 'Python':
>>> soup.body.findAll(text='Python')
[]
Note that the following NavigableString is found:
>>> soup.body.findAll(text='Python Jobs')
[u'Python Jobs']
Note this behaviour:
>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]
So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.
How to get everything after a certain character?
strtok
is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE
value for $allTheRest
which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?
The .cer and .crt file should be interchangable as far as importing them into a keystore.
Take a look at the contents of the .cer file. Erase anything before the -----BEGIN CERTIFICATE-----
line and after the -----END CERTIFICATE-----
line. You'll be left with the BEGIN/END lines with a bunch of Base64-encoded stuff between them.
-----BEGIN CERTIFICATE-----
MIIDQTCCAqqgAwIBAgIJALQea21f1bVjMA0GCSqGSIb3DQEBBQUAMIG1MQswCQYD
...
pfDACIDHTrwCk5OefMwArfEkSBo/
-----END CERTIFICATE-----
Then just import it into your keyfile using keytool.
keytool -import -alias myalias -keystore my.keystore -trustcacerts -file mycert.cer
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Relative paths based on file location instead of current working directory
@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.
This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:
Linux / GNU readlink
solution:
If your script needs to run on Linux only or you know that GNU readlink
is in the $PATH
, use readlink -f
, which conveniently resolves a symlink to its ultimate target:
scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
Note that GNU readlink
has 3 related options for resolving a symlink to its ultimate target's full path: -f
(--canonicalize
), -e
(--canonicalize-existing
), and -m
(--canonicalize-missing
) - see man readlink
.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f
here, because it is the most well-known one.
Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):
If your script must run on any platform that:
has a readlink
utility, but lacks the -f
option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.
- macOS uses an older version of the BSD implementation of
readlink
; note that recent versions of FreeBSD/PC-BSD do support -f
.
does not even have readlink
, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).
The following solution, inspired by https://stackoverflow.com/a/1116890/45375,
defines helper shell function, rreadlink()
, which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink
's -e
option, which is similar to the -f
option, except that the ultimate target must exist.
Note: The function is a bash
function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh
), see here.
If readlink
is available, it is used (without options) - true on most modern platforms.
Otherwise, the output from ls -l
is parsed, which is the only POSIX-compliant way to determine a symlink's target.
Caveat: this will break if a filename or path contains the literal substring ->
- which is unlikely, however.
(Note that platforms that lack readlink
may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find
utility supporting the %l
format char. with its -printf
primary; in the interest of brevity the function does NOT try to detect such cases.)
An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink
in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink
; on other platforms (assuming they have bash
), follow the manual installation instructions.
If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.
#!/usr/bin/env bash
# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...
local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH=
# Since we'll be using `command` below for a predictable execution
# environment, we make sure that it has its original meaning.
{ \unalias command; \unset -f command; } &>/dev/null
while :; do # Resolve potential symlinks until the ultimate target is found.
[[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
if [[ -L $fname ]]; then
# Extract [next] target path, which is defined
# relative to the symlink's own directory.
if [[ -n $readlinkexe ]]; then # Use `readlink`.
target=$("$readlinkexe" -- "$fname")
else # `readlink` utility not available.
# Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant
# way to determine a symlink's target. Hypothetically, this can break with
# filenames containig literal ' -> ' and embedded newlines.
target=$(command ls -l -- "$fname")
target=${target#* -> }
fi
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we
# have a normalized path.
if [[ $fname == '.' ]]; then
command printf '%s\n' "${targetDir%/}"
elif [[ $fname == '..' ]]; then
# Caveat: something like /var/.. will resolve to /private (assuming
# /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
Windows Batch: How to add Host-Entries?
Create a new addHostEntry.bat file with the following content in it:
@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END
:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1 mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END
:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT
Hope this helps!
How to detect if numpy is installed
Option 1:
Use following command in python ide.:
import numpy
Option 2:
Go to Python -> site-packages folder. There you should be able to find numpy and the numpy distribution info folder.
If any of the above is true then you installed numpy successfully.
what is the unsigned datatype?
In C and C++
unsigned = unsigned int (Integer type)
signed = signed int (Integer type)
An unsigned integer containing n bits can have a value between 0 and
(2^n-1) , which is 2^n different values.
An unsigned integer is either positive or zero.
Signed integers are stored in a computer using 2's complement.
Using getline() with file input in C++
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
Fatal error: Cannot use object of type stdClass as array in
Sorry.Though it is a bit late but hope it would help others as well .
Always use the stdClass object.e.g
$getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");
foreach($getvidids->result() as $key=>$myids)
{
$vidid[$key] = $myids->videoid; // better methodology to retrieve and store multiple records in arrays in loop
}
Convert ndarray from float64 to integer
While astype
is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr
in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
The int*
functions from NumPy
>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
The NumPy *array
functions themselves:
>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
The astype
method (that was already mentioned but for completeness sake):
>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int
as dtype to astype
or array
will default to a default integer type that depends on your platform. For example on Windows it will be int32
, on 64bit Linux with 64bit Python it's int64
. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32
or np.int64
.
Absolute and Flexbox in React Native
Ok, solved my problem, if anyone is passing by here is the answer:
Just had to add left: 0,
and top: 0,
to the styles, and yes, I'm tired.
position: 'absolute',
left: 0,
top: 0,
How to get the onclick calling object?
The easiest way is to pass this to the click123 function or
you can also do something like this(cross-browser):
function click123(e){
e = e || window.event;
var src = e.target || e.srcElement;
//src element is the eventsource
}
How to debug in Django, the good way?
One of your best option to debug Django code is via wdb:
https://github.com/Kozea/wdb
wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer!
Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled)
In other words it's a very enhanced version of pdb directly in your browser with nice features.
Install and run the server, and in your code add:
import wdb
wdb.set_trace()
According to the author, main differences with respect to pdb
are:
For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as:
- Source syntax highlighting
- Visual breakpoints
- Interactive code completion using jedi
- Persistent breakpoints
- Deep objects inspection using mouse Multithreading / Multiprocessing support
- Remote debugging
- Watch expressions
- In debugger code edition
- Popular web servers integration to break on error
- In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance
- Breaking in currently running programs through code injection (on supported systems)
It has a great browser-based user interface. A joy to use! :)
Creating a segue programmatically
First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:
1). Define all your views with class file and also storyboard id in identity inspector.
2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller
3). In your first class, import the "secondClass.h"
#import "ViewController.h
#import "secondController.h"
4). Add this command in the IBAction that has to perform the segue
secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];
5). @"second"
is secondview controller class, storyboard id.
How to clear a chart from a canvas so that hover events cannot be triggered?
This worked for me.
Add a call to clearChart, at the top oF your updateChart()
`function clearChart() {
event.preventDefault();
var parent = document.getElementById('parent-canvas');
var child = document.getElementById('myChart');
parent.removeChild(child);
parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';
return;
}`
How to jquery alert confirm box "yes" & "no"
This plugin can help you,
craftpip/jquery-confirm
Its easy to setup and has great set of features.
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
$.alert('Confirmed!');
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'], // trigger when enter or shift is pressed
action: function(){
$.alert('Something else?');
}
}
}
});
Other than this you can also load your content from a remote url.
$.confirm({
content: 'url:hugedata.html' // location of your hugedata.html.
});
If a DOM Element is removed, are its listeners also removed from memory?
regarding jQuery:
the .remove() method takes elements out of the
DOM. Use .remove() when you want to remove the element itself, as well
as everything inside it. In addition to the elements themselves, all
bound events and jQuery data associated with the elements are removed.
To remove the elements without removing data and events, use .detach()
instead.
Reference: http://api.jquery.com/remove/
jQuery v1.8.2 .remove()
source code:
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
}
apparently jQuery uses node.removeChild()
According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,
The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.
ie event listeners might get removed, but node
still exists in memory.
What are database constraints?
Constraints dictate what values are valid for data in the database. For example, you can enforce the a value is not null (a NOT NULL
constraint), or that it exists as a unique constraint in another table (a FOREIGN KEY
constraint), or that it's unique within this table (a UNIQUE
constraint or perhaps PRIMARY KEY
constraint depending on your requirements). More general constraints can be implemented using CHECK
constraints.
The MSDN documentation for SQL Server 2008 constraints is probably your best starting place.
OraOLEDB.Oracle provider is not registered on the local machine
If you can't change compile use x64, try uninstall x64 version of odac and install 32bit version. Then, don't forget to add install directory like C:\oracle and also the child directory C:\oracle\bin to the PATH environment variable. This worked out for me in .net 4 application.
What does Ruby have that Python doesn't, and vice versa?
python has named optional arguments
def func(a, b=2, c=3):
print a, b, c
>>> func(1)
1 2 3
>>> func(1, c=4)
1 2 4
AFAIK Ruby has only positioned arguments because b=2 in the function declaration is an affectation that always append.
Adding text to a cell in Excel using VBA
You need to use Range
and Valu
e functions.
Range
would be the cell where you want the text you want
Value
would be the text that you want in that Cell
Range("A1").Value="whatever text"
Connect to docker container as user other than root
The only way I am able to make it work is by:
docker run -it -e USER=$USER -v /etc/passwd:/etc/passwd -v `pwd`:/siem mono bash
su - magnus
So I have to both specify $USER environment variable as well a point the /etc/passwd file. In this way, I can compile in /siem folder and retain ownership of files there not as root.
Live search through table rows
Here's a version that searches both columns.
$("#search").keyup(function () {
var value = this.value.toLowerCase().trim();
$("table tr").each(function (index) {
if (!index) return;
$(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
});
demo: http://jsfiddle.net/rFGWZ/369/
Inner Joining three tables
Just do the same thing agin but then for TableC
SELECT *
FROM dbo.tableA A
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common
Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
- It's not doing a soft transition on the height attribute. At time zero the element already has the 100% of its height producing a sudden glitch on the elements below it.
- When sliding out/up, the element does a
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.
You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
How can I print variable and string on same line in Python?
Python is a very versatile language. You may print variables by different methods. I have listed below five methods. You may use them according to your convenience.
Example:
a = 1
b = 'ball'
Method 1:
print('I have %d %s' % (a, b))
Method 2:
print('I have', a, b)
Method 3:
print('I have {} {}'.format(a, b))
Method 4:
print('I have ' + str(a) + ' ' + b)
Method 5:
print(f'I have {a} {b}')
The output would be:
I have 1 ball
Is Unit Testing worth the effort?
One great thing about unit tests is that they serve as documentation for how your code is meant to behave. Good tests are kind of like a reference implementation, and teammates can look at them to see how to integrate their code with yours.
Hide vertical scrollbar in <select> element
Chrome (and maybe other webkit browsers) only:
_x000D_
_x000D_
/* you probably want to specify the size if you're going to disable the scrollbar */_x000D_
select[size]::-webkit-scrollbar {_x000D_
display: none;_x000D_
}
_x000D_
<select size=4>_x000D_
<option>Mango</option>_x000D_
<option>Peach</option>_x000D_
<option>Orange</option>_x000D_
<option>Banana</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
Vue.js toggle class on click
If you need more than 1 class
You can do this:
<i id="icon"
v-bind:class="{ 'fa fa-star': showStar }"
v-on:click="showStar = !showStar"
>
</i>
data: {
showStar: true
}
Notice the single quotes ' around the classes!
Thanks to everyone else's solutions.
SQL exclude a column using SELECT * [except columnA] FROM tableA?
If you're using PHP you just do your query and then you can unset an specific element:
$sql = "SELECT * FROM ........ your query";
$result = $conection->query($sql); // execute your query
$row_cnt = $result->num_rows;
if ($row_cnt > 0) {
while ($row = $result->fetch_object()) {
unset($row->your_column_name); // Exclude column from your fetch
$data[] = $row;
}
echo json_encode($data); // or whatever
Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively
If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).
==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.
I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!
Hope this helps to make things even clearer!
SHA1 vs md5 vs SHA256: which to use for a PHP login?
Use SHA256
. It is not perfect, as SHA512
would be ideal for a fast hash, but out of the options, its the definite choice. As per any hashing technology, be sure to salt the hash for added security.
As an added note, FRKT, please show me where someone can easily crack a salted SHA256 hash? I am truly very interested to see this.
Important Edit:
Moving forward please use bcrypt
as a hardened hash. More information can be found here.
Edit on Salting:
Use a random number, or random byte stream etc. You can use the unique field of the record in your database as the salt too, this way the salt is different per user.
C# 'or' operator?
just like in C and C++, the boolean or operator is ||
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
MVC 4 client side validation not working
In Global.asax.cs, Application_Start() method add:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));
Dropping Unique constraint from MySQL table
my table name is buyers which has a unique constraint column emp_id now iam going to drop the emp_id
step 1: exec sp_helpindex buyers, see the image file
step 2: copy the index address
step3: alter table buyers drop constraint [UQ__buyers__1299A860D9793F2E]
alter table buyers
drop column emp_id
note:
Blockquote
instead of buyers change it to your table name :)
Blockquote
thats all column name emp_id with constraints is dropped!
How do I drop a function if it already exists?
You have two options to drop and recreate the procedure in SQL Server 2016.
Starting from SQL Server 2016 - use IF EXISTS
DROP FUNCTION [ IF EXISTS ] { [ schema_name. ] function_name } [ ,...n ] [;]
Starting from SQL Server 2016 SP1 - use OR ALTER
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
How to Query Database Name in Oracle SQL Developer?
Edit: Whoops, didn't check your question tags before answering.
Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).
If so, try runnung those queries with F5
Export table data from one SQL Server to another
Just to show yet another option (for SQL Server 2008 and above):
- right-click on Database -> select 'Tasks' -> select 'Generate Scripts'
- Select specific database objects you want to copy. Let's say one or more tables. Click Next
- Click Advanced and scroll down to 'Types of Data to script' and choose 'Schema and Data'. Click OK
- Choose where to save generated script and proceed by clicking Next
Concept of void pointer in C programming
I want to make this function generic,
without using ifs; is it possible?
The only simple way I see is to use overloading .. which is not available in C programming langage AFAIK.
Did you consider the C++ programming langage for your programm ? Or is there any constraint that forbids its use?
How to create nested directories using Mkdir in Golang?
An utility method like the following can be used to solve this.
import (
"os"
"path/filepath"
"log"
)
func ensureDir(fileName string) {
dirName := filepath.Dir(fileName)
if _, serr := os.Stat(dirName); serr != nil {
merr := os.MkdirAll(dirName, os.ModePerm)
if merr != nil {
panic(merr)
}
}
}
func main() {
_, cerr := os.Create("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
log.Println("created file in a sub-directory.")
}
How to get a value inside an ArrayList java
You haven't shown your Car
type, but assuming you'd want the price of the first car, you could use:
public static void processCars(ArrayList<Car> cars) {
Car car = cars.get(0);
System.out.println(car.getPrice());
}
Note that I've changed the name of the list from car
to cars
- this is a list of cars, not a single car. (I've changed the method name in a similar way.)
If you only want the method to process a single car, you should change the parameter to be of type Car
:
public static void processCar(Car car)
and then call it like this:
// In the main method
processCar(cars.get(0));
If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car>
- it's unlikely that you'll really require that it's an ArrayList<Car>
.
How to detect incoming calls, in an Android device?
You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED
This will call your received whenever the phone-state changes from idle, ringing, offhook so from the previous value and the new value you can detect if this is an incoming/outgoing call.
Required permission would be:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But if you also want to receive the EXTRA_INCOMING_NUMBER in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"
And the code something like this:
val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive")
}
}
override fun onResume() {
val filter = IntentFilter()
filter.addAction("android.intent.action.PHONE_STATE")
registerReceiver(receiver, filter)
super.onResume()
}
override fun onPause() {
unregisterReceiver(receiver)
super.onPause()
}
and in receiver class, we can get current state by reading intent like this:
intent.extras["state"]
the result of extras could be:
RINGING -> If your phone is ringing
OFFHOOK -> If you are talking with someone (Incoming or Outcoming
call)
IDLE -> if call ended (Incoming or Outcoming call)
With PHONE_STATE broadcast we don't need to use PROCESS_OUTGOING_CALLS permission or deprecated NEW_OUTGOING_CALL action.
How do I get a div to float to the bottom of its container?
I know that this stuff is old, but I recently ran into this problem.
use absolute position divs advice is really silly, because the whole float thing kind of loses point with absolute positions..
now, I did not find an universal solution, but in a lot of cases prople use floating divs just to display something in a row, like a series of span elements. and you can't vertically align that.
to achieve a similar effect you can do this: do not make the div float, but set it's display property to inline-block
. then you can align it vertically however it pleases you. you just need to set parent's div property vertical-align
to either top
, bottom
, middle
or baseline
i hope that helps someone
How to implement reCaptcha for ASP.NET MVC?
Step 1: Client site integration
Paste this snippet before the closing </head>
tag on your HTML template:
<script src='https://www.google.com/recaptcha/api.js'></script>
Paste this snippet at the end of the <form>
where you want the reCAPTCHA widget to appear:
<div class="g-recaptcha" data-sitekey="your-site-key"></div>
Step 2: Server site integration
When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:
URL : https://www.google.com/recaptcha/api/siteverify
secret : your secret key
response : The value of 'g-recaptcha-response'.
Now in action of your MVC app:
// return ActionResult if you want
public string RecaptchaWork()
{
// Get recaptcha value
var r = Request.Params["g-recaptcha-response"];
// ... validate null or empty value if you want
// then
// make a request to recaptcha api
using (var wc = new WebClient())
{
var validateString = string.Format(
"https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
"your_secret_key", // secret recaptcha key
r); // recaptcha value
// Get result of recaptcha
var recaptcha_result = wc.DownloadString(validateString);
// Just check if request make by user or bot
if (recaptcha_result.ToLower().Contains("false"))
{
return "recaptcha false";
}
}
// Do your work if request send from human :)
}
How to refer to Excel objects in Access VBA?
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
Remove attribute "checked" of checkbox
Try this to check
$('#captureImage').attr("checked",true).checkboxradio("refresh");
and uncheck
$('#captureImage').attr("checked",false).checkboxradio("refresh");
Getting the last n elements of a vector. Is there a better way than using the length() function?
Here is a function to do it and seems reasonably fast.
endv<-function(vec,val)
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}
USAGE:
test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)
BENCHMARK:
test replications elapsed relative
1 expression(tail(x, 5)) 100000 5.24 6.469
2 expression(x[seq.int(to = length(x), length.out = 5)]) 100000 0.98 1.210
3 expression(x[length(x) - (4:0)]) 100000 0.81 1.000
4 expression(endv(x, 5)) 100000 1.37 1.691
How do I authenticate a WebClient request?
This helped me to call API that was using cookie authentication. I have passed authorization in header like this:
request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
complete code:
// utility method to read the cookie value:
public static string ReadCookie(string cookieName)
{
var cookies = HttpContext.Current.Request.Cookies;
var cookie = cookies.Get(cookieName);
if (cookie != null)
return cookie.Value;
return null;
}
// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
// WebClient:
var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };
using (var webClient = new WebClient()) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = requestData.Length;
request.ContentType = "application/json";
request.Expect = "application/json";
request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
request.GetRequestStream().Write(requestData, 0, requestData.Length);
using (var response = (HttpWebResponse)request.GetResponse()) {
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd(); // objText will have the value
}
}
HTML5 Pre-resize images before uploading
Correction to above:
<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>
function handleFiles()
{
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
document.getElementById('image').src = dataurl;
}
// Load files into file reader
reader.readAsDataURL(file);
// Post the data
/*
var fd = new FormData();
fd.append("name", "some_filename.jpg");
fd.append("image", dataurl);
fd.append("info", "lah_de_dah");
*/
}</script>
Html table with button on each row
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
How to convert OutputStream to InputStream?
The library io-extras may be useful. For example if you want to gzip an InputStream
using GZIPOutputStream
and you want it to happen synchronously (using the default buffer size of 8192):
InputStream is = ...
InputStream gz = IOUtil.pipe(is, o -> new GZIPOutputStream(o));
Note that the library has 100% unit test coverage (for what that's worth of course!) and is on Maven Central. The Maven dependency is:
<dependency>
<groupId>com.github.davidmoten</groupId>
<artifactId>io-extras</artifactId>
<version>0.1</version>
</dependency>
Be sure to check for a later version.
How do you declare string constants in C?
The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.
Just disable scroll not hide it?
I have made this one function, that solves this problem with JS.
This principle can be easily extended and customized that is a big pro for me.
Using this js DOM API function:
const handleWheelScroll = (element) => (event) => {
if (!element) {
throw Error("Element for scroll was not found");
}
const { deltaY } = event;
const { clientHeight, scrollTop, scrollHeight } = element;
if (deltaY < 0) {
if (-deltaY > scrollTop) {
element.scrollBy({
top: -scrollTop,
behavior: "smooth",
});
event.stopPropagation();
event.preventDefault();
}
return;
}
if (deltaY > scrollHeight - clientHeight - scrollTop) {
element.scrollBy({
top: scrollHeight - clientHeight - scrollTop,
behavior: "smooth",
});
event.stopPropagation();
event.preventDefault();
return;
}
};
In short, this function will stop event propagation and default behavior if the scroll would scroll something else then the given element (the one you want to scroll in).
Then you can hook and unhook this up like this:
const wheelEventHandler = handleWheelScroll(elementToScrollIn);
window.addEventListener("wheel", wheelEventHandler, {
passive: false,
});
window.removeEventListener("wheel", wheelEventHandler);
Watch out for that it is a higher order function so you have to keep a reference to the given instance.
I hook the addEventListener
part in mouse enter and unhook the removeEventListener
in mouse leave events in jQuery, but you can use it as you like.
Create normal zip file programmatically
You should look into Zip Packages
They are a more structured version of normal ZIP archives, requiring some meta stuff in the root. So other ZIP tools can open a package, but the Sysytem.IO.Packaging API can not open all ZIP files.
Default value in an asp.net mvc view model
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
CSV in Python adding an extra carriage return, on Windows
Python 3:
The official csv
documentation recommends open
ing the file with newline=''
on all platforms to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
...
The CSV writer terminates each line with the lineterminator
of the dialect, which is \r\n
for the default excel
dialect on all platforms.
Python 2:
On Windows, always open your files in binary mode ("rb"
or "wb"
), before passing them to csv.reader
or csv.writer
.
Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n
separating records. If that separator is written in text mode, the Python runtime replaces the \n
with \r\n
, hence the \r\r\n
observed in the file.
See this previous answer.
How to get the sizes of the tables of a MySQL database?
Try the following shell command (replace DB_NAME
with your database name):
mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head
For Drupal/drush solution, check the following example script which will display the biggest tables in use:
#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20