Web link to specific whatsapp contact
You can use the following URL as per the WhatsApp FAQ:
https://wa.me/PHONENUMBERHERE
Add the country code in front of the number and don't add any plus (+) sign or any dashes (-) or any other characters in the number. Only integrers/numeric values.
You can also predefine a text message to start with:
https://wa.me/PHONENUMBERHERE/?text=urlencodedtext
How to mark-up phone numbers?
Although Apple recommends tel:
in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto:
just the same. So I recommend using callto:
on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.
Update (June 2013)
This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel:
and callto:
links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel:
links while mobile Android doesn't do anything with callto:
links. Even Google Chrome with the Google Talk plugin does not respond to tel:
links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel:
links to work on their computer.
If the site design dictated that I only provide one link, I'd use a tel:
link that I would try to change to callto:
on desktop browsers.
Open Facebook page from Android app?
Best answer I have found, it's working great.
Just go to your page on Facebook in the browser, right click, and click on "View source code", then find the page_id
attribute: you have to use page_id
here in this line after the last back-slash:
fb://page/pageID
For example:
Intent facebookAppIntent;
try {
facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/1883727135173361"));
startActivity(facebookAppIntent);
} catch (ActivityNotFoundException e) {
facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://facebook.com/CryOut-RadioTv-1883727135173361"));
startActivity(facebookAppIntent);
}
iOS Launching Settings -> Restrictions URL Scheme
Here is something else I found:
After I have the "prefs" URL Scheme defined, "prefs:root=Safari&path=ContentBlockers" is working on Simulator (iOS 9.1 English), but not working on Simulator (Simplified Chinese). It just jump to Safari, but not Content Blockers. If your app is international, be careful.
Update: Don't know why, now I can't jump into ContentBlockers anymore, the same code, the same version, doesn't work now. :(
On real devcies (mine is iPhone 6S & iPad mini 2), "Safari" should be "SAFARI", "Safari" not working on real device, "SAFARI" now working on simulator:
#if arch(i386) || arch(x86_64)
// Simulator
let url = NSURL(string: "prefs:root=Safari")!
#else
// Device
let url = NSURL(string: "prefs:root=SAFARI")!
#endif
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
So far, did not find any differences between iPhone and iPad.
AngularJS : ng-click not working
It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra
</div>
was placed in the html to prematurely close the div block that contains the ng-click.
Removed the extra
</div>
then everything is working fine.
Angular 2 How to redirect to 404 or other path if the path does not exist
For version v2.2.2 and newer
In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404'
instead of path: '/404'
:
{path: '404', component: NotFoundComponent},
{path: '**', redirectTo: '/404'}
For versions older than v2.2.2
you can use {path: '/*path', redirectTo: ['redirectPathName']}
:
{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},
{path: '/*path', redirectTo: ['NotFound']}
if no path matches then redirect to NotFound
path
Python, how to check if a result set is empty?
Notice: This is for MySQLdb module in Python.
For a SELECT
statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]
) for cursor.fetchall()
and None
for cursor.fetchone()
.
For any other statement, e.g. INSERT
or UPDATE
, that doesn't return a recordset, you can neither call fetchall()
nor fetchone()
on the cursor. Otherwise, an exception will be raised.
There's one way to distinguish between the above two types of cursors:
def yield_data(cursor):
while True:
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT, yield data
yield cursor.fetchall()
# Or yield column names with
# yield [col[0] for col in cursor.description]
# Go to the next recordset
if not cursor.nextset():
# End of recordsets
return
Remove CSS from a Div using JQuery
Put your CSS properties into a class, then do something like this:
$("#displayPanel div").live("click", function(){
$(this).addClass('someClass');
});
Then where your 'other functionalities' are do something like:
$("#myButton").click(function(){
$("#displayPanel div").removeClass('someClass');
});
CardView background color always white
You can do it either in XML or programmatically:
In XML:
card_view:cardBackgroundColor="@android:color/red"
Programmatically:
cardView.setCardBackgroundColor(Color.RED);
What are bitwise shift (bit-shift) operators and how do they work?
The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.
The Operators
>>
is the arithmetic (or signed) right shift operator.
>>>
is the logical (or unsigned) right shift operator.
<<
is the left shift operator, and meets the needs of both logical and arithmetic shifts.
All of these operators can be applied to integer values (int
, long
, possibly short
and byte
or char
). In some languages, applying the shift operators to any datatype smaller than int
automatically resizes the operand to be an int
.
Note that <<<
is not an operator, because it would be redundant.
Also note that C and C++ do not distinguish between the right shift operators. They provide only the >>
operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.
(In all mainstream C and C++ implementations including GCC and Clang/LLVM, >>
on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not undefined, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers is undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)
Left shift (<<)
Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int
would be:
00000000 00000000 00000000 00000110
Shifting this bit pattern to the left one position (6 << 1
) would result in the number 12:
00000000 00000000 00000000 00001100
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1
is equivalent to 6 * 2
, and 6 << 3
is equivalent to 6 * 8
. A good optimizing compiler will replace multiplications with shifts when possible.
Non-circular shifting
Please note that these are not circular shifts. Shifting this value to the left by one position (3,758,096,384 << 1
):
11100000 00000000 00000000 00000000
results in 3,221,225,472:
11000000 00000000 00000000 00000000
The digit that gets shifted "off the end" is lost. It does not wrap around.
Logical right shift (>>>)
A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:
00000000 00000000 00000000 00001100
to the right by one position (12 >>> 1
) will get back our original 6:
00000000 00000000 00000000 00000110
So we see that shifting to the right is equivalent to division by powers of 2.
Lost bits are gone
However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:
00111000 00000000 00000000 00000110
to the left 4 positions (939,524,102 << 4
), we get 2,147,483,744:
10000000 00000000 00000000 01100000
and then shifting back ((939,524,102 << 4) >>> 4
) we get 134,217,734:
00001000 00000000 00000000 00000110
We cannot get back our original value once we have lost bits.
Arithmetic right shift (>>)
The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.
For example, if we interpret this bit pattern as a negative number:
10000000 00000000 00000000 01100000
we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:
11111000 00000000 00000000 00000110
or the number -134,217,722.
So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.
How do I delete an entity from symfony2
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
Function to close the window in Tkinter
def quit(self):
self.root.destroy()
Add parentheses after destroy
to call the method.
When you use command=self.root.destroy
you pass the method to Tkinter.Button
without the parentheses because you want Tkinter.Button
to store the method for future calling, not to call it immediately when the button is created.
But when you define the quit
method, you need to call self.root.destroy()
in the body of the method because by then the method has been called.
Git update submodules recursively
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
How to copy a file to another path?
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo
, here's a sample:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
git-diff to ignore ^M
Why do you get these ^M
in your git diff
?
In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M
at the end of the lines I added in git diff
. I think the ^M
were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR
line endings, and in OS X it uses LF
line endings.
Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.
So what should we do about this?
You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.
If you go for this option, you should however fix the current files (because they're still using the CR
line endings). I did this by following these steps:
Remove all files from the repository, but not from your filesystem.
git rm --cached -r .
Add a .gitattributes
file that enforces certain files to use a LF
as line endings. Put this in the file:
*.ext text eol=crlf
Replace .ext
with the file extensions you want to match.
Add all the files again.
git add .
This will show messages like this:
warning: CRLF will be replaced by LF in <filename>.
The file will have its original line endings in your working directory.
You could remove the .gitattributes
file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.
Commit and push it all.
Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:
The file will have its original line endings in your working directory.
You can do something like this to remove the files:
git ls | grep ".ext$" | xargs rm -f
And then this to get them back with the correct line endings:
git ls | grep ".ext$" | xargs git checkout
Of course replacing .ext
with the extension you want.
Now your project only uses LF
characters for the line endings, and the nasty CR
characters won't ever come back :).
The other option is to enforce windows style line endings. You can also use the .gitattributes
file for this.
More info:
https://help.github.com/articles/dealing-with-line-endings/#platform-all
"Proxy server connection failed" in google chrome
- Open Google Chrome.
- Click Menu on the upper right side. Beside the STAR symbol (Bookmark).
- Click Show Advanced Settings.
- Scroll down and find Network.
- Click Change proxy settings.
- On the Connections tab, click LAN settings.
- Uncheck "Use a proxy server for your LAN."
- Then click OK.
Hope it helps .
Check if argparse optional argument is set or not
In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne
Unfortunately it doesn't work then the argument got it's default value
defined.
one can first check if the argument was provided by comparing it with the Namespace
object and providing the default=argparse.SUPPRESS
option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
Usage
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
Is it fine to have foreign key as primary key?
Short answer: DEPENDS.... In this particular case, it might be fine. However, experts will recommend against it just about every time; including your case.
Why?
Keys are seldomly unique in tables when they are foreign (originated in another table) to the table in question. For example, an item ID might be unique in an ITEMS table, but not in an ORDERS table, since the same type of item will most likely exist in another order. Likewise, order IDs might be unique (might) in the ORDERS table, but not in some other table like ORDER_DETAILS where an order with multiple line items can exist and to query against a particular item in a particular order, you need the concatenation of two FK (order_id and item_id) as the PK for this table.
I am not DB expert, but if you can justify logically to have an auto-generated value as your PK, I would do that. If this is not practical, then a concatenation of two (or maybe more) FK could serve as your PK. BUT, I cannot think of any case where a single FK value can be justified as the PK.
Stacked Bar Plot in R
A somewhat different approach using ggplot2:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
library(reshape2)
dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("\nType") +
ylab("Time\n") +
guides(fill = FALSE) +
theme_bw()
this gives:
When you want to include a legend, delete the guides(fill = FALSE)
line.
getContext is not a function
Your value:
this.element = $(id);
is a jQuery object, not a pure Canvas element.
To turn it back so you can call getContext()
, call this.element.get(0)
, or better yet store the real element and not the jQuery object:
function canvasLayer(location, id) {
this.width = $(window).width();
this.height = $(window).height();
this.element = document.createElement('canvas');
$(this.element)
.attr('id', id)
.text('unsupported browser')
.attr('width', this.width) // for pixels
.attr('height', this.height)
.width(this.width) // for CSS scaling
.height(this.height)
.appendTo(location);
this.context = this.element.getContext("2d");
}
See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.
how do I get eclipse to use a different compiler version for Java?
Eclipse uses it's own internal compiler that can compile to several Java versions.
From Eclipse Help > Java development user guide > Concepts > Java Builder
The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.
For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.
When you configure a project:
[project-name] > Properties > Java Compiler > Compiler compliance level
This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.
Host environment variables, eg JAVA_HOME etc, are not used.
The Oracle/Sun JDK compiler is not used.
Xcode 6 Storyboard the wrong size?
If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".
Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations.
Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"
Android selector & text color
And selector is the answer here as well.
Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as
android:textColor="@color/bright_text_dark_focused"
How to recover MySQL database from .myd, .myi, .frm files
I just discovered to solution for this. I am using MySQL 5.1 or 5.6 on Windows 7.
- Copy the .frm file and ibdata1 from the old file which was located on "C:\Program Data\MySQL\MSQLServer5.1\Data"
- Stop the SQL server instance in the current SQL instance
- Go to the datafolder located at "C:\Program Data\MySQL\MSQLServer5.1\Data"
- Paste the ibdata1 and the folder of your database which contains the .frm file from the file you want to recover.
- Start the MySQL instance.
No need to locate the .MYI and .MYD file for this recovery.
Difference between a class and a module
Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.
A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.
(This answer originally linked to http://www.rubycentral.com/pickaxe/classes.html
, but that link and its domain are no longer active.)
mailto using javascript
You can use the simple mailto
, see below for the simple markup.
<a href="mailto:[email protected]">Click here to mail</a>
Once clicked, it will open your Outlook or whatever email client you have set.
What REALLY happens when you don't free after malloc?
It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.
That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.
How to hide first section header in UITableView (grouped style)
Try this if you want to remove all section header completely
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
How can I add an item to a ListBox in C# and WinForms?
The way I do this - using the format Event
MyClass c = new MyClass();
listBox1.Items.Add(c);
private void listBox1_Format(object sender, ListControlConvertEventArgs e)
{
if(e.ListItem is MyClass)
{
e.Value = ((MyClass)e.ListItem).ToString();
}
else
{
e.Value = "Unknown item added";
}
}
e.Value being the Display Text
Then you can attempt to cast the SelectedItem to MyClass to get access to anything you had in there.
Also note, you can use anything (that inherits from object anyway(which is pretty much everything)) in the Items Collection.
How to delete multiple pandas (python) dataframes from memory to save RAM?
del
statement does not delete an instance, it merely deletes a name.
When you do del i
, you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected.
If you want to release memory, your dataframes has to be Garbage-Collected, i.e. delete all references to them.
If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection.
>>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]
>>> del lst # memory is released
If you created some variables, you have to delete them all.
>>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
>>> lst = [a, b, c]
>>> del a, b, c # dfs still in list
>>> del lst # memory release now
How to pick element inside iframe using document.getElementById
(this is to add to the chosen answer)
Make sure the iframe
is loaded before you
contentWindow.document
Otherwise, your getElementById
will be null
.
PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe
load before selecting the inner-iframe element.
SSH to Elastic Beanstalk instance
There is a handy 'Connect' option in the 'Instance Actions' menu for the EC2 instance. It will give you the exact SSH command to execute with the correct url for the instance. Jabley's overall instructions are correct.
T-SQL string replace in Update
The syntax for REPLACE:
REPLACE (string_expression,string_pattern,string_replacement)
So that the SQL you need should be:
UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')
Center icon in a div - horizontally and vertically
Horizontal centering is as easy as:
text-align: center
Vertical centering when the container is a known height:
height: 100px;
line-height: 100px;
vertical-align: middle
Vertical centering when the container isn't a known height AND you can set the image in the background:
background: url(someimage) no-repeat center center;
How to add a footer in ListView?
I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.
Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment
Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":
<RelativeLayout>
<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/>
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->
</RelativeLayout>
Opening Android Settings programmatically
This did it for me
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent);
When they press back it goes back to my app.
Android ImageView setImageResource in code
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
Is there a no-duplicate List implementation out there?
Off the top of my head, lists allow duplicates. You could quickly implement a UniqueArrayList
and override all the add
/ insert
functions to check for contains()
before you call the inherited methods. For personal use, you could only implement the add
method you use, and override the others to throw an exception in case future programmers try to use the list in a different manner.
Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'
As I understand it is because of rxjs
last update. They have changed some operators and syntax. Thereafter we should import rx
operators like this
import { map } from "rxjs/operators";
instead of this
import 'rxjs/add/operator/map';
And we need to add pipe around all operators like this
this.myObservable().pipe(map(data => {}))
Source is here
How do I make a <div> move up and down when I'm scrolling the page?
Here is the Jquery Code
$(document).ready(function () {
var el = $('#Container');
var originalelpos = el.offset().top; // take it where it originally is on the page
//run on scroll
$(window).scroll(function () {
var el = $('#Container'); // important! (local)
var elpos = el.offset().top; // take current situation
var windowpos = $(window).scrollTop();
var finaldestination = windowpos + originalelpos;
el.stop().animate({ 'top': finaldestination }, 1000);
});
});
Inserting an image with PHP and FPDF
Please note that you should not use any png when you are testing this , first work with jpg .
$myImage = "images/logos/mylogo.jpg"; // this is where you get your Image
$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);
How to compare two strings are equal in value, what is the best method?
You should use some form of the String#equals(Object)
method. However, there is some subtlety in how you should do it:
If you have a string literal then you should use it like this:
"Hello".equals(someString);
This is because the string literal "Hello"
can never be null, so you will never run into a NullPointerException
.
If you have a string and another object then you should use:
myString.equals(myObject);
You can make sure you are actually getting string equality by doing this. For all you know, myObject
could be of a class that always returns true
in its equals
method!
Start with the object less likely to be null because this:
String foo = null;
String bar = "hello";
foo.equals(bar);
will throw a NullPointerException
, but this:
String foo = null;
String bar = "hello";
bar.equals(foo);
will not. String#equals(Object)
will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.
Is try-catch like error handling possible in ASP Classic?
Been a while since I was in ASP land, but iirc there's a couple of ways:
try catch finally
can be reasonably simulated in VBS (good article here here) and there's an event called class_terminate
you can watch and catch exceptions globally in. Then there's the possibility of changing your scripting language...
Simple export and import of a SQLite database on Android
To export db rather it is SQLITE or ROOM:
Firstly, add this permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Secondly, we drive to code the db functions:
private void exportDB() {
try {
File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = DirectoryName + File.separator +
DATABASE_NAME + ".db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (IOException e) {
Log.e("dbBackup:", e.getMessage());
}
}
Create Folder on Daily basis with name of folder is Current date:
public void createBackup() {
sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
editor = sharedPref.edit();
String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
editor.commit();
}
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
folder = new File(DirectoryName);
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
exportDB();
}
} else {
Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
}
}
Assign the DATABASE_NAME without .db extension and its data type is string
Best Practice: Initialize JUnit class fields in setUp() or at declaration?
In addition to Alex B's answer.
It is even required to use the setUp method to instantiate resources in a certain state. Doing this in the constructor is not only a matter of timings, but because of the way JUnit runs the tests, each test state would be erased after running one.
JUnit first creates instances of the testClass for each test method and starts running the tests after each instance is created. Before running the test method, its setup method is ran, in which some state can be prepared.
If the database state would be created in the constructor, all instances would instantiate the db state right after each other, before running each tests. As of the second test, tests would run with a dirty state.
JUnits lifecycle:
- Create a different testclass instance for each test method
- Repeat for each testclass instance: call setup + call the testmethod
With some loggings in a test with two test methods you get: (number is the hashcode)
- Creating new instance: 5718203
- Creating new instance: 5947506
- Setup: 5718203
- TestOne: 5718203
- Setup: 5947506
- TestTwo: 5947506
Bootstrap Carousel image doesn't align properly
Insert this on the css parent div class where your carousel is.
<div class="parent_div">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="item active">
<img src="assets/img/slider_1.png" alt="">
<div class="carousel-caption">
</div>
</div>
</div>
</div>
</div>
CSS
.parent_div {
margin: 0 auto;
min-width: [desired width];
max-width: [desired width];
}
Java 8 lambdas, Function.identity() or t->t
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
How to crop an image in OpenCV using Python
here is some code for more robust imcrop ( a bit like in matlab )
def imcrop(img, bbox):
x1,y1,x2,y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
(np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
y1 += np.abs(np.minimum(0, y1))
y2 += np.abs(np.minimum(0, y1))
x1 += np.abs(np.minimum(0, x1))
x2 += np.abs(np.minimum(0, x1))
return img, x1, x2, y1, y2
Pointer vs. Reference
Consider C#'s out keyword. The compiler requires the caller of a method to apply the out keyword to any out args, even though it knows already if they are. This is intended to enhance readability. Although with modern IDEs I'm inclined to think that this is a job for syntax (or semantic) highlighting.
How to reset the use/password of jenkins on windows?
This is for windows environment:
I got the Initial Admin password under
C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password.
Then under Jenkins> people
I edited the password of the user and clicked on apply to reflect the changes.
How to add a vertical Separator?
This is not exactly what author asked, but still, it is very simple and works exactly as expected.
Rectangle does the job:
<StackPanel Grid.Column="2" Orientation="Horizontal">
<Button >Next</Button>
<Button >Prev</Button>
<Rectangle VerticalAlignment="Stretch" Width="1" Margin="2" Stroke="Black" />
<Button>Filter all</Button>
</StackPanel>
Difference between Big-O and Little-O Notation
The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than
another. To say that one function is asymptotically less than
another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).
Make a table fill the entire window
You can use position like this to stretch an element across the parent container.
<table style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;">
<tr style="height: 25%; font-size: 180px;">
<td>Region</td>
</tr>
<tr style="height: 75%; font-size: 540px;">
<td>100.00%</td>
</tr>
</table>
Checking for duplicate strings in JavaScript array
You could take a Set
and filter the values who are alreday seen.
_x000D_
_x000D_
var array = ["q", "w", "w", "e", "i", "u", "r"],_x000D_
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));_x000D_
_x000D_
console.log(seen);
_x000D_
_x000D_
_x000D_
Test if registry value exists
I would go with the function Get-RegistryValue
. In fact it gets requested values (so that it can be used not only for testing). As far as registry values cannot be null, we can use null result as a sign of a missing value. The pure test function Test-RegistryValue
is also provided.
# This function just gets $true or $false
function Test-RegistryValue($path, $name)
{
$key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
$key -and $null -ne $key.GetValue($name, $null)
}
# Gets the specified registry value or $null if it is missing
function Get-RegistryValue($path, $name)
{
$key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
if ($key) {
$key.GetValue($name, $null)
}
}
# Test existing value
Test-RegistryValue HKCU:\Console FontFamily
$val = Get-RegistryValue HKCU:\Console FontFamily
if ($val -eq $null) { 'missing value' } else { $val }
# Test missing value
Test-RegistryValue HKCU:\Console missing
$val = Get-RegistryValue HKCU:\Console missing
if ($val -eq $null) { 'missing value' } else { $val }
OUTPUT:
True
54
False
missing value
Typescript interface default values
It's best practice in case you have many parameters to let the user insert only few parameters and not in specific order.
For example, bad practice:
foo(a, b, c, d, e)
Good practice:
foo({d=3})
The way to do it is through interfaces.
You need to define the parameter as an interface like:
interface Arguments {
a?;
b?;
c?;
d?;
e?;
}
And define the function like:
foo(arguments: Arguments)
Now interfaces variables can't get default values, so how do we define default values?
Simple, we define default value for the whole interface:
foo({
a,
b=1,
c=99,
d=88,
e
}: Arguments)
Now if the user pass:
foo({d=3})
The actual parameters will be:
{
a,
b=1,
c=99,
d=3,
e
}
I understood it from the following link so big credit :)
https://medium.com/better-programming/named-parameters-in-typescript-e32c763d2b2e
postgresql sequence nextval in schema
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
What is a Windows Handle?
A HANDLE
is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLE
s.
For example, GetModuleHandle
returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle
to HeapDestroy
and expect it to do something sensible.
The HANDLE
itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE
returned by GetModuleHandle
is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).
HANDLE
s are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).
Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget
is a struct
.
Widget * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return w;
}
void * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<void *>(w);
}
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<HANDLE>(w);
}
The first example exposes the internal details about the API: it allows the user code to know that GetWidget
returns a pointer to a struct Widget
. This has a couple of consequences:
- the user code must have access to the header file that defines the
Widget
struct
- the user code could potentially modify internal parts of the returned
Widget
struct
Both of these consequences may be undesirable.
The second example hides this internal detail from the user code, by returning just void *
. The user code doesn't need access to the header that defines the Widget
struct.
The third example is exactly the same as the second, but we just call the void *
a HANDLE
instead. Perhaps this discourages user code from trying to figure out exactly what the void *
points to.
Why go through this trouble? Consider this fourth example of a newer version of this same API:
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
NewImprovedWidget *w;
w = findImprovedWidget(name);
return reinterpret_cast<HANDLE>(w);
}
Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget
struct instead.
The handles in these example are really just a new, presumably friendlier, name for void *
, which is exactly what a HANDLE
is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.
Please add a @Pipe/@Directive/@Component annotation. Error
I faced the same error when I used another class instead of component down the component decorator.
Component class must come just after the component decorator
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
export class SmsgtreconComponent implements OnInit {
After moving TodoItemNode to the top of component decorator it worked
Solution
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
export class SmsgtreconComponent implements OnInit {
CSS filter: make color image with transparency white
You can use
filter: brightness(0) invert(1);
_x000D_
_x000D_
html {_x000D_
background: red;_x000D_
}_x000D_
p {_x000D_
float: left;_x000D_
max-width: 50%;_x000D_
text-align: center;_x000D_
}_x000D_
img {_x000D_
display: block;_x000D_
max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
-webkit-filter: brightness(0) invert(1);_x000D_
filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
Original:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
Filter:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_
First, brightness(0)
makes all image black, except transparent parts, which remain transparent.
Then, invert(1)
makes the black parts white.
Stop absolutely positioned div from overlapping text
Short answer: There's no way to do it using CSS only.
Long(er) answer: Why? Because when you do position: absolute;
, that takes your element out of the document's regular flow, so there's no way for the text to have any positional-relationship with it, unfortunately.
One of the possible alternatives is to float: right;
your div
, but if that doesn't achieve what you want, you'll have to use JavaScript/jQuery, or just come up with a better layout.
How to set image name in Dockerfile?
Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build
. A sample docker-compose.yml would look like
version: '2'
services:
man:
build: .
image: dude/man:v2
That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:
docker build -t dude/man:v2 .
Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.
How to write a switch statement in Ruby
case...when
To add more examples to Chuck's answer:
With parameter:
case a
when 1
puts "Single value"
when 2, 3
puts "One of comma-separated values"
when 4..6
puts "One of 4, 5, 6"
when 7...9
puts "One of 7, 8, but not 9"
else
puts "Any other thing"
end
Without parameter:
case
when b < 3
puts "Little than 3"
when b == 3
puts "Equal to 3"
when (1..10) === b
puts "Something in closed range of [1..10]"
end
Please, be aware of "How to write a switch statement in Ruby" that kikito warns about.
counting the number of lines in a text file
In C if you implement count line it will never fail.
Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
TSQL Pivot without aggregate function
yes, but why !!??
Select CustomerID,
Min(Case DBColumnName When 'FirstName' Then Data End) FirstName,
Min(Case DBColumnName When 'MiddleName' Then Data End) MiddleName,
Min(Case DBColumnName When 'LastName' Then Data End) LastName,
Min(Case DBColumnName When 'Date' Then Data End) Date
From table
Group By CustomerId
How do you plot bar charts in gnuplot?
Simple bar graph:
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes
data.dat:
0 label 100
1 label2 450
2 "bar label" 75
If you want to style your bars differently, you can do something like:
set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"
set style fill solid
set boxwidth 0.5
plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
"data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2
If you want to do multiple bars for each entry:
data.dat:
0 5
0.5 6
1.5 3
2 7
3 8
3.5 1
gnuplot:
set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)
set boxwidth 0.5
set style fill solid
plot 'data.dat' every 2 using 1:2 with boxes ls 1,\
'data.dat' every 2::1 using 1:2 with boxes ls 2
If you want to be tricky and use some neat gnuplot tricks:
Gnuplot has psuedo-columns that can be used as the index to color:
plot 'data.dat' using 1:2:0 with boxes lc variable
Further you can use a function to pick the colors you want:
mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable
Note: you will have to add a couple other basic commands to get the same effect as the sample images.
Reference - What does this regex mean?
The Stack Overflow Regular Expressions FAQ
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
- Zero-or-more:
*
:greedy, *?
:reluctant, *+
:possessive
- One-or-more:
+
:greedy, +?
:reluctant, ++
:possessive
?
:optional (zero-or-one)
- Min/max ranges (all inclusive):
{n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n
- Differences between greedy, reluctant (a.k.a. "lazy", "ungreedy") and possessive quantifier:
Character Classes
Escape Sequences
Anchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input
\A
:start of input, \Z
:end of input php, perl, ruby
\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c
\G
:start of match php, perl, ruby
(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
Lookarounds
Modifiers
Other:
Common Tasks
Advanced Regex-Fu
- Strings and numbers:
- Other:
Flavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
- Java
- .NET
- Official documentation:
- Boost regex engine: General syntax, Perl syntax (used by TextPad, Sublime Text, UltraEdit, ...???)
- JavaScript 1.5 general info and RegExp object
- .NET MySQL Oracle Perl5 version 18.2
- PHP: pattern syntax,
preg_match
- Python: Regular expression operations,
search
vs match
, how-to
- Rust: crate
regex
, struct regex::Regex
- Splunk: regex terminology and syntax and regex command
- Tcl: regex syntax, manpage,
regexp
command
- Visual Studio Find and Replace
General information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
Best way to track onchange as-you-type in input type="text"?
Method 1: Add an event listener for input
:
element.addEventListener("input", myFunction);
Method 2: Define the oninput
property with JavaScript:
element.oninput = function()
{
myFunction();
};
Method 3: Define the oninput
property with HTML:
<input type="text" oninput="myFunction();">
Opening A Specific File With A Batch File?
If you are trying to open a file in the same directory it would be:
./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)
Or, if trying to backtrack from the same directory it would be:
../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)
Else, if you need a straight one from start, it would be:
(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd
How to toggle boolean state of react component?
Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState
which accepts as argument a function that returns a new state.
In your case:
this.setState(prevState => ({
check: !prevState.check
}));
See docs
Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):
If you are using the useState
hook, then use the following code (in case your new state depends on the previous state):
const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);
Creating Roles in Asp.net Identity MVC 5
the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.
string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
if(!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("user", "role1");
UserManager.AddToRole("user", "role2");
context.SaveChanges();
Could not insert new outlet connection: Could not find any information for the class named
Here are some things that can fix this (in increasing order of difficulty):
- Clean the project (Product > Clean)
Manually paste in
@IBOutlet weak var viewName: UIView!
// or
@IBAction func viewTapped(_ sender: Any) { }
and control drag to it. (Change type as needed.) Also see this.
Completely close Xcode and restart your project.
- Delete the Derived Data folder (Go to Xcode > Preferences > Locations and click the gray arrow by the Derived Data folder. Then delete your project folder.)
- Click delete on the class, remove reference (not Move to Trash), and add it back again. (see this answer)
vagrant login as root by default
Adding this to the Vagrantfile
worked for me. These lines are the equivalent of you entering sudo su -
every time you login. Please notice that this requires reprovisioning the VM.
config.vm.provision "shell", inline: <<-SHELL
echo "sudo su -" >> .bashrc
SHELL
Can Json.NET serialize / deserialize to / from a stream?
The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
Documentation: Deserialize JSON from a file stream
SELECT * FROM multiple tables. MySQL
In order to get rid of duplicates, you can group by drinks.id
. But that way you'll get only one photo for each drinks.id
(which photo you'll get depends on database internal implementation).
Though it is not documented, in case of MySQL, you'll get the photo with lowest id
(in my experience I've never seen other behavior).
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks.id
PHP - Getting the index of a element from a array
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
Uncaught TypeError: Cannot read property 'value' of null
I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:
var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
var str2 = document.getElementById("holiday").value;
var str3 = document.getElementById("cal_option").value;
There is either no element with the id cal_preview
, year
, holiday
, cal_option
, or some combination.
Therefore, JavaScript is unable to read the value of something that does not exist.
EDIT:
If you want to check that the element exists first, you could use an if statement for each:
var str,
element = document.getElementById('cal_preview');
if (element != null) {
str = element.value;
}
else {
str = null;
}
You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.
Write lines of text to a file in R
Short ways to write lines of text to a file in R could be realised with cat or writeLines as already shown in many answers. Some of the shortest possibilities might be:
cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")
In case you don't like the "\n" you could also use the following style:
cat("Hello
World", file="output.txt")
writeLines("Hello
World", "output.txt")
While writeLines
adds a newline at the end of the file what is not the case for cat
.
This behaviour could be adjusted by:
writeLines("Hello\nWorld", "output.txt", sep="") #No newline at end of file
cat("Hello\nWorld\n", file="output.txt") #Newline at end of file
cat("Hello\nWorld", file="output.txt", sep="\n") #Newline at end of file
But main difference is that cat
uses R objects and writeLines
a character vector as argument. So writing out e.g. the numbers 1:10 needs to be casted for writeLines while it can be used as it is in cat:
cat(1:10)
writeLines(as.character(1:10))
and cat
can take many objects but writeLines
only one vector:
cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))
<input type="file"> limit selectable files by extensions
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
How to get Month Name from Calendar?
This works for me:
String getMonthName(int monthNumber) {
String[] months = new DateFormatSymbols().getMonths();
int n = monthNumber-1;
return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}
To returns "September"
with one line:
String month = getMonthName(9);
How might I force a floating DIV to match the height of another floating DIV?
Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
Overlapping Views in Android
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
What's the difference between eval, exec, and compile?
The short answer, or TL;DR
Basically, eval
is used to evaluate a single dynamically generated Python expression, and exec
is used to execute dynamically generated Python code only for its side effects.
eval
and exec
have these two differences:
eval
accepts only a single expression, exec
can take a code block that has Python statements: loops, try: except:
, class
and function/method def
initions and so on.
An expression in Python is whatever you can have as the value in a variable assignment:
a_variable = (anything you can put within these parentheses is an expression)
eval
returns the value of the given expression, whereas exec
ignores the return value from its code, and always returns None
(in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).
In versions 1.0 - 2.7, exec
was a statement, because CPython needed to produce a different kind of code object for functions that used exec
for its side effects inside the function.
In Python 3, exec
is a function; its use has no effect on the compiled bytecode of the function where it is used.
Thus basically:
>>> a = 5
>>> eval('37 + a') # it is an expression
42
>>> exec('37 + a') # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47') # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47') # you cannot evaluate a statement
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 47
^
SyntaxError: invalid syntax
The compile
in 'exec'
mode compiles any number of statements into a bytecode that implicitly always returns None
, whereas in 'eval'
mode it compiles a single expression into bytecode that returns the value of that expression.
>>> eval(compile('42', '<string>', 'exec')) # code returns None
>>> eval(compile('42', '<string>', 'eval')) # code returns 42
42
>>> exec(compile('42', '<string>', 'eval')) # code returns 42,
>>> # but ignored by exec
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval
. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval')
This is where the difference really comes from.
If a code
object (which contains Python bytecode) is passed to exec
or eval
, they behave identically, excepting for the fact that exec
ignores the return value, still returning None
always. So it is possible use eval
to execute something that has statements, if you just compile
d it into bytecode before instead of passing it as a string:
>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>
works without problems, even though the compiled code contains statements. It still returns None
, because that is the return value of the code object returned from compile
.
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
The longer answer, a.k.a the gory details
exec
and eval
The exec
function (which was a statement in Python 2) is used for executing a dynamically created statement or program:
>>> program = '''
for i in range(3):
print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>>
The eval
function does the same for a single expression, and returns the value of the expression:
>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84
exec
and eval
both accept the program/expression to be run either as a str
, unicode
or bytes
object containing source code, or as a code
object which contains Python bytecode.
If a str
/unicode
/bytes
containing source code was passed to exec
, it behaves equivalently to:
exec(compile(source, '<string>', 'exec'))
and eval
similarly behaves equivalent to:
eval(compile(source, '<string>', 'eval'))
Since all expressions can be used as statements in Python (these are called the Expr
nodes in the Python abstract grammar; the opposite is not true), you can always use exec
if you do not need the return value. That is to say, you can use either eval('my_func(42)')
or exec('my_func(42)')
, the difference being that eval
returns the value returned by my_func
, and exec
discards it:
>>> def my_func(arg):
... print("Called with %d" % arg)
... return arg * 2
...
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>>
Of the 2, only exec
accepts source code that contains statements, like def
, for
, while
, import
, or class
, the assignment statement (a.k.a a = 42
), or entire programs:
>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Both exec
and eval
accept 2 additional positional arguments - globals
and locals
- which are the global and local variable scopes that the code sees. These default to the globals()
and locals()
within the scope that called exec
or eval
, but any dictionary can be used for globals
and any mapping
for locals
(including dict
of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the exec
uted code creates:
>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}
(If you display the value of the entire g
, it would be much longer, because exec
and eval
add the built-ins module as __builtins__
to the globals automatically if it is missing).
In Python 2, the official syntax for the exec
statement is actually exec code in globals, locals
, as in
>>> exec 'global a; a, b = 123, 42' in g, l
However the alternate syntax exec(code, globals, locals)
has always been accepted too (see below).
compile
The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
built-in can be used to speed up repeated invocations of the same code with exec
or eval
by compiling the source into a code
object beforehand. The mode
parameter controls the kind of code fragment the compile
function accepts and the kind of bytecode it produces. The choices are 'eval'
, 'exec'
and 'single'
:
'eval'
mode expects a single expression, and will produce bytecode that when run will return the value of that expression:
>>> dis.dis(compile('a + b', '<string>', 'eval'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 BINARY_ADD
7 RETURN_VALUE
'exec'
accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None
:
>>> dis.dis(compile('a + b', '<string>', 'exec'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 BINARY_ADD
7 POP_TOP <- discard result
8 LOAD_CONST 0 (None) <- load None on stack
11 RETURN_VALUE <- return top of stack
'single'
is a limited form of 'exec'
which accepts a source code containing a single statement (or multiple statements separated by ;
) if the last statement is an expression statement, the resulting bytecode also prints the repr
of the value of that expression to the standard output(!).
An if
-elif
-else
chain, a loop with else
, and try
with its except
, else
and finally
blocks is considered a single statement.
A source fragment containing 2 top-level statements is an error for the 'single'
, except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:
In Python 2.7.8:
>>> exec(compile('a = 5\na = 6', '<string>', 'single'))
>>> a
5
And in Python 3.4.2:
>>> exec(compile('a = 5\na = 6', '<string>', 'single'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 5
^
SyntaxError: multiple statements found while compiling a single statement
This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval
the resulting code.
Thus greatest distinction of exec
and eval
actually comes from the compile
function and its modes.
In addition to compiling source code to bytecode, compile
supports compiling abstract syntax trees (parse trees of Python code) into code
objects; and source code into abstract syntax trees (the ast.parse
is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)
); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.
While eval
only allows you to evaluate a string that contains a single expression, you can eval
a whole statement, or even a whole module that has been compile
d into bytecode; that is, with Python 2, print
is a statement, and cannot be eval
led directly:
>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print("Python is cool")
^
SyntaxError: invalid syntax
compile
it with 'exec'
mode into a code
object and you can eval
it; the eval
function will return None
.
>>> code = compile('for i in range(3): print("Python is cool")',
'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool
If one looks into eval
and exec
source code in CPython 3, this is very evident; they both call PyEval_EvalCode
with same arguments, the only difference being that exec
explicitly returns None
.
Syntax differences of exec
between Python 2 and Python 3
One of the major differences in Python 2 is that exec
is a statement and eval
is a built-in function (both are built-in functions in Python 3).
It is a well-known fact that the official syntax of exec
in Python 2 is exec code [in globals[, locals]]
.
Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec
statement in CPython 2 can be also used with syntax that looks exactly like the exec
function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals)
built-in function! And that built-in function was replaced with exec
statement somewhere before Python 1.0 release.
Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code
was a tuple of length 2 or 3, and globals
and locals
were not passed into the exec
statement otherwise, the code
would be interpreted as if the 2nd and 3rd element of the tuple were the globals
and locals
respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:
The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals)
is equivalent to exec expr in globals
, while the form exec(expr, globals, locals)
is equivalent to exec expr in globals, locals
. The tuple form of exec
provides compatibility with Python 3, where exec
is a function rather than a statement.
Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all),
when it actually had been there for backward-compatibility for two decades.
Thus while exec
is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,
>>> exec("print(a)", globals(), {'a': 42})
42
has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).
What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec
into a variable:
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
File "<stdin>", line 1
a = exec('print(42)')
^
SyntaxError: invalid syntax
(which wouldn't be useful in Python 3 either, as exec
always returns None
), or pass a reference to exec
:
>>> call_later(exec, 'print(42)', delay=1000)
File "<stdin>", line 1
call_later(exec, 'print(42)', delay=1000)
^
SyntaxError: invalid syntax
Which a pattern that someone might actually have used, though unlikely;
Or use it in a list comprehension:
>>> [exec(i) for i in ['print(42)', 'print(foo)']
File "<stdin>", line 1
[exec(i) for i in ['print(42)', 'print(foo)']
^
SyntaxError: invalid syntax
which is abuse of list comprehensions (use a for
loop instead!).
How to define a circle shape in an Android XML drawable file?
I couldn't draw a circle inside my ConstraintLayout for some reason, I just couldn't use any of the answers above.
What did work perfectly is a simple TextView with the text that comes out, when you press "Alt+7":
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0075bc"
android:textSize="40dp"
android:text="•"></TextView>
Bootstrap datepicker hide after selection
Having problem with clock still showing even if I i wrote format: 'YYYY-MM-DD',
I hade to set pickTime: false
and after change->hide I hade to focus->show
$('#VBS_RequiredDeliveryDate').datetimepicker({
format: 'YYYY-MM-DD',
pickTime: false
});
$('#VBS_RequiredDeliveryDate').on('change', function(){
$('.datepicker').hide();
});
$('#VBS_RequiredDeliveryDate').on('focus', function(){
$('.datepicker').show();
});
How to select an option from drop down using Selenium WebDriver C#?
If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.
if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
WaitForAjax();
Thread.Sleep(3000);
}
else
{
Console.WriteLine("Your comment here);
}
IE7 Z-Index Layering Issues
Z-index is not an absolute measurement. It is possible for an element with z-index: 1000 to be behind an element with z-index: 1 - as long as the respective elements belong to different stacking contexts.
When you specify z-index, you're specifying it relative to other elements in the same stacking context, and although the CSS spec's paragraph on Z-index says a new stacking context is only created for positioned content with a z-index other than auto (meaning your entire document should be a single stacking context), you did construct a positioned span: unfortunately IE7 interprets positioned content without z-index this as a new stacking context.
In short, try adding this CSS:
#envelope-1 {position:relative; z-index:1;}
or redesign the document such that your spans don't have position:relative any longer:
<html>
<head>
<title>Z-Index IE7 Test</title>
<style type="text/css">
ul {
background-color: #f00;
z-index: 1000;
position: absolute;
width: 150px;
}
</style>
</head>
<body>
<div>
<label>Input #1:</label> <input><br>
<ul><li>item<li>item<li>item<li>item</ul>
</div>
<div>
<label>Input #2:</label> <input>
</div>
</body>
</html>
See http://www.brenelz.com/blog/2009/02/03/squish-the-internet-explorer-z-index-bug/ for a similar example of this bug. The reason giving a parent element (envelope-1 in your example) a higher z-index works is because then all children of envelope-1 (including the menu) will overlap all siblings of envelope-1 (specifically, envelope-2).
Although z-index lets you explicitly define how things overlap, even without z-index the layering order is well defined. Finally, IE6 has an additional bug that causes selectboxes and iframes to float on top of everything else.
MySQL: Set user variable from result of query
Yes, but you need to move the variable assignment into the query:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
Test case:
CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
Result:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
Note that for SET
, either =
or :=
can be used as the assignment operator. However inside other statements, the assignment operator must be :=
and not =
because =
is treated as a comparison operator in non-SET statements.
UPDATE:
Further to comments below, you may also do the following:
SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group;
SELECT * FROM user WHERE `group` = @group;
Image scaling causes poor quality in firefox/internet explorer but not chrome
I've seen the same thing in firefox, css transform scaled transparent png's looking very rough.
I noticed that when they previously had a background color set the quality was much better, so I tried setting an RGBA background with as low an opacity value as possible.
background:rgba(255,255,255,0.001);
This worked for me, give it a try.
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 find Google's IP address?
Google maintains a server infrastructure that grows dynamically with the ever increasing internet demands. This link by google describes the method to remain up to date with their IP address ranges.
When you need the literal IP addresses for Google Apps mail servers, start by using one of the common DNS lookup commands (nslookup, dig, host) to retrieve the SPF records for the domain _spf.google.com, like so:
nslookup -q=TXT _spf.google.com 8.8.8.8
This returns a list of the domains included in Google's SPF record, such as:
_netblocks.google.com, _netblocks2.google.com, _netblocks3.google.com
Now look up the DNS records associated with those domains, one at a time, like so:
nslookup -q=TXT _netblocks.google.com 8.8.8.8
nslookup -q=TXT _netblocks2.google.com 8.8.8.8
nslookup -q=TXT _netblocks3.google.com 8.8.8.8
The results of these commands contain the current range of addresses.
get one item from an array of name,value JSON
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
_x000D_
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
How to declare a structure in a header that is to be used by multiple files in c?
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.
The extern
declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern
in a header file like:
extern struct a myAValue;
Then, in one source file, define the actual variable:
struct a myAValue;
If you forget to do this or accidentally define it in two source files, the linker will let you know about this.
'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel
I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).
/**
* Encode array from latin1 to utf8 recursively
* @param $dat
* @return array|string
*/
public static function convert_from_latin1_to_utf8_recursively($dat)
{
if (is_string($dat)) {
return utf8_encode($dat);
} elseif (is_array($dat)) {
$ret = [];
foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);
return $ret;
} elseif (is_object($dat)) {
foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);
return $dat;
} else {
return $dat;
}
}
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);
How to use Typescript with native ES6 Promises
A. If using "target": "es5"
and TypeScript version below 2.0:
typings install es6-promise --save --global --source dt
B. If using "target": "es5"
and TypeScript version 2.0 or higer:
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
C. If using "target": "es6"
, there's no need to do anything.
Calculate number of hours between 2 dates in PHP
To provide another method for DatePeriod
when using the UTC or GMT timezone.
$start = new \DateTime('2006-04-12T12:30:00');
$end = new \DateTime('2006-04-14T11:30:00');
//determine what interval should be used - can change to weeks, months, etc
$interval = new \DateInterval('PT1H');
//create periods every hour between the two dates
$periods = new \DatePeriod($start, $interval, $end);
//count the number of objects within the periods
$hours = iterator_count($periods);
echo $hours . ' hours';
//difference between Unix Epoch
$diff = $end->getTimestamp() - $start->getTimestamp();
$hours = $diff / ( 60 * 60 );
echo $hours . ' hours (60 * 60)';
//difference between days
$diff = $end->diff($start);
$hours = $diff->h + ($diff->days * 24);
echo $hours . ' hours (days * 24)';
Result
47 hours (iterator_count)
47 hours (60 * 60)
47 hours (days * 24)
Please be advised that DatePeriod
excludes an hour for DST but does not add another hour when DST ends. So its usage is subjective to your desired outcome and date range.
See the current bug report
//set timezone to UTC to disregard daylight savings
date_default_timezone_set('America/New_York');
$interval = new \DateInterval('PT1H');
//DST starts Apr. 2nd 02:00 and moves to 03:00
$start = new \DateTime('2006-04-01T12:00:00');
$end = new \DateTime('2006-04-02T12:00:00');
$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';
//DST ends Oct. 29th 02:00 and moves to 01:00
$start = new \DateTime('2006-10-28T12:00:00');
$end = new \DateTime('2006-10-29T12:00:00');
$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';
Result
#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT
23 hours (iterator_count)
//23 hours (60 * 60)
//24 hours (days * 24)
#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST
24 hours (iterator_count)
//25 hours (60 * 60)
//24 hours (days * 24)
#2006-01-01 12:00 EST to 2007-01-01 12:00 EST
8759 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)
//------
#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)
#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)
#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC
8760 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)
Where does Android emulator store SQLite database?
An update mentioned in the comments below:
You don't need to be on the DDMS perspective anymore, just open the File Explorer from Eclipse Window > Show View > Other... It seems the app doesn't need to be running even, I can browse around in different apps file contents. I'm
running ADB version 1.0.29
Or, you can try the old approach:
Open the DDMS perspective on your Eclipse IDE
(Window > Open Perspective > Other > DDMS)
and the most important:
YOUR APPLICATION MUST BE RUNNING SO YOU CAN SEE THE HIERARCHY OF FOLDERS AND FILES.
Then in the File Explorer Tab you will follow the path :
data > data > your-package-name > databases > your-database-file.
Then select the file, click on the disket icon in the right corner of the screen to download the .db file. If you want to upload a database file to the emulator you can click on the phone icon(beside disket icon) and choose the file to upload.
If you want to see the content of the .db file, I advise you to use SQLite Database Browser, which you can download here.
PS: If you want to see the database from a real device, you must root your phone.
How to use 'hover' in CSS
I was working on a nice defect last time and was wondering more about how to use properly hover property for A tag link and for IE browser.
A strange thing for me was that IE was not able to capture A tag link element based on a simple A selector.
So, I found out how to even force capturing A tag element and I spotted that we must use more specifc CSS selector. Here is an example below - It works perfect:
li a[href]:hover {...}
Find and replace strings in vim on multiple lines
The :&&
command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):
:6,10s/<search_string>/<replace_string>/g | 14,18&&
If you have many ranges though, I'd rather use a loop:
:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor
How to sort findAll Doctrine's method?
You need to use a criteria, for example:
<?php
namespace Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;
/**
* Thing controller
*/
class ThingController extends Controller
{
public function thingsAction(Request $request, $id)
{
$ids=explode(',',$id);
$criteria = new Criteria(null, <<DQL ordering expression>>, null, null );
$rep = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
$things = $rep->matching($criteria);
return $this->render('Bundle:Thing:things.html.twig', [
'entities' => $things,
]);
}
}
Use of ~ (tilde) in R programming Language
The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
How to implement OnFragmentInteractionListener
With me it worked delete this code:
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
Ending like this:
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
How do you determine the ideal buffer size when using FileInputStream?
In the ideal case we should have enough memory to read the file in one read operation.
That would be the best performer because we let the system manage File System , allocation units and HDD at will.
In practice you are fortunate to know the file sizes in advance, just use the average file size rounded up to 4K (default allocation unit on NTFS).
And best of all : create a benchmark to test multiple options.
Convert pyQt UI to python
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
Get table name by constraint name
SELECT owner, table_name
FROM dba_constraints
WHERE constraint_name = <<your constraint name>>
will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS
view, ALL_CONSTRAINTS
or USER_CONSTRAINTS
should work as well.
Deprecated meaning?
Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.
Yes, otherwise it wouldn't be called "deprecated"
Unless stated otherwise in docs, it should be the same as before
No, but if there were problems in v1 they aren't about to fix them
How to use multiprocessing pool.map with multiple arguments?
A better way is using decorator instead of writing wrapper function by hand. Especially when you have a lot of functions to map, decorator will save your time by avoiding writing wrapper for every function. Usually a decorated function is not picklable, however we may use functools
to get around it. More disscusions can be found here.
Here the example
def unpack_args(func):
from functools import wraps
@wraps(func)
def wrapper(args):
if isinstance(args, dict):
return func(**args)
else:
return func(*args)
return wrapper
@unpack_args
def func(x, y):
return x + y
Then you may map it with zipped arguments
np, xlist, ylist = 2, range(10), range(10)
pool = Pool(np)
res = pool.map(func, zip(xlist, ylist))
pool.close()
pool.join()
Of course, you may always use Pool.starmap
in Python 3 (>=3.3) as mentioned in other answers.
PHP error: Notice: Undefined index:
Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).
Wrap all the processing code in a conditional that checks if the form has even been sent.
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet! You can break out of php here and render your form
}
Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like
header('Location:http://www.yourdomainhere.com/formsuccess.php');
I would not get into the habit of supressing notices or errors.
Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.
Center image in div horizontally
text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :
div
{
position: relative;
}
div img
{
position: absolute;
top: 50%;
left: 50%;
margin-left: [-50% of your image's width];
margin-top: [-50% of your image's height];
}
R Error in x$ed : $ operator is invalid for atomic vectors
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
detach(package:neuralnet)
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
What is the difference between _tmain() and main() in C++?
the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.
cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;
angular-cli server - how to specify default port
Update for @angular/[email protected]: and over
In angular.json
you can specify a port per "project"
"projects": {
"my-cool-project": {
... rest of project config omitted
"architect": {
"serve": {
"options": {
"port": 1337
}
}
}
}
}
All options available:
https://angular.io/guide/workspace-config#project-tool-configuration-options
Alternatively, you may specify the port each time when running ng serve like this:
ng serve --port 1337
With this approach you may wish to put this into a script in your package.json to make it easier to run each time / share the config with others on your team:
"scripts": {
"start": "ng serve --port 1337"
}
Legacy:
Update for @angular/cli final:
Inside angular-cli.json
you can specify the port in the defaults:
"defaults": {
"serve": {
"port": 1337
}
}
Legacy-er:
Tested in [email protected]
The server in angular-cli
comes from the ember-cli
project.
To configure the server, create an .ember-cli
file in the project root. Add your JSON config in there:
{
"port": 1337
}
Restart the server and it will serve on that port.
There are more options specified here:
http://ember-cli.com/#runtime-configuration
{
"skipGit" : true,
"port" : 999,
"host" : "0.1.0.1",
"liveReload" : true,
"environment" : "mock-development",
"checkForUpdates" : false
}
#pragma mark in Swift?
Up to Xcode 5 the preprocessor directive #pragma mark
existed.
From Xcode 6 on, you have to use // MARK:
These preprocessor features allow to bring some structure to the function drop down box of the source code editor.
some examples :
// MARK:
-> will be preceded by a horizontal divider
// MARK: your text goes here
-> puts 'your text goes here' in bold in the drop down list
// MARK: - your text goes here
-> puts 'your text goes here' in bold in the drop down list, preceded by a horizontal divider
update : added screenshot 'cause some people still seem to have issues with this :
Activating Anaconda Environment in VsCode
I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e
conda create --name env_name python=3.6
so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:
Firstly, open the command palette using Ctrl + Shift + P
Secondly, Select Python: select Interpreter
Now, Select Enter interpreter path
We have to add the path where the env is, the default location will be
C:\Users\YourUserName\Anaconda3\envs\env_name
Finally, you have successfully activated your environment.
It might now be the best way but it worked for me. Let me know if there is any issue.
What is the difference between a database and a data warehouse?
Data Warehouse vs Database: A data warehouse is specially designed for data analytics, which involves reading large amounts of data to understand relationships and trends across the data. A database is used to capture and store data, such as recording details of a transaction.
Data Warehouse:
Suitable workloads - Analytics, reporting, big data.
Data source - Data collected and normalized from many sources.
Data capture - Bulk write operations typically on a predetermined batch schedule.
Data normalization - Denormalized schemas, such as the Star schema or Snowflake schema.
Data storage - Optimized for simplicity of access and high-speed query. performance using columnar storage.
Data access - Optimized to minimize I/O and maximize data throughput.
Transactional Database:
Suitable workloads - Transaction processing.
Data source - Data captured as-is from a single source, such as a transactional system.
Data capture - Optimized for continuous write operations as new data is available to maximize transaction throughput.
Data normalization - Highly normalized, static schemas.
Data storage - Optimized for high throughout write operations to a single row-oriented physical block.
Data access - High volumes of small read operations.
How do I find an element that contains specific text in Selenium WebDriver (Python)?
In the HTML which you have provided:
<div>My Button</div>
The text My Button
is the innerHTML
and have no whitespaces around it so you can easily use text()
as follows:
my_element = driver.find_element_by_xpath("//div[text()='My Button']")
Note: text()
selects all text node children of the context node
Text with leading/trailing spaces
In case the relevant text containing whitespaces either in the beginning:
<div> My Button</div>
or at the end:
<div>My Button </div>
or at both the ends:
<div> My Button </div>
In these cases you have two options:
You can use contains()
function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:
my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")
You can use normalize-space()
function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:
driver.find_element_by_xpath("//div[normalize-space()='My Button']]")
XPath expression for variable text
In case the text is a variable, you can use:
foo= "foo_bar"
my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")
Use cases for the 'setdefault' dict method
In addition to what have been suggested, setdefault
might be useful in situations where you don't want to modify a value that has been already set. For example, when you have duplicate numbers and you want to treat them as one group. In this case, if you encounter a repeated duplicate
key which has been already set, you won't update the value of that key. You will keep the first encountered value. As if you are iterating/updating the repeated keys once only.
Here's a code example of recording the index for the keys/elements of a sorted list:
nums = [2,2,2,2,2]
d = {}
for idx, num in enumerate(sorted(nums)):
# This will be updated with the value/index of the of the last repeated key
# d[num] = idx # Result (sorted_indices): [4, 4, 4, 4, 4]
# In the case of setdefault, all encountered repeated keys won't update the key.
# However, only the first encountered key's index will be set
d.setdefault(num,idx) # Result (sorted_indices): [0, 0, 0, 0, 0]
sorted_indices = [d[i] for i in nums]
Properties private set;
Perhaps, you can have them marked as internal, and in this case only classes in your DAL or BL (assuming they are separate dlls) would be able to set it.
You could also supply a constructor that takes the fields and then only exposes them as properties.
Get epoch for a specific date using Javascript
Date.parse()
method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
.
const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(unixTimeZero);
// expected output: 0
console.log(javaScriptRelease);
// expected output: 818035920000
Explore more at: Date.parse()
How to play only the audio of a Youtube video using HTML 5?
This may be an old post but people could still be searching for this so here you go:
<div style="position:relative;width:267px;height:25px;overflow:hidden;">
<div style="position:absolute;top:-276px;left:-5px">
<iframe width="300" height="300"
src="https://www.youtube.com/embed/youtubeID?rel=0">
</iframe>
</div>
</div>
Convert int to ASCII and back in Python
What about BASE58 encoding the URL? Like for example flickr does.
# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
url = ''
while node_id >= 58:
div, mod = divmod(node_id, 58)
url = BASE58[mod] + url
node_id = int(div)
return 'http://short.com/%s' % BASE58[node_id] + url
Turning that back into a number isn't a big deal either.
How to pass variable number of arguments to a PHP function
An old question, I know, however, none of the answers here really do a good job of simply answer the question.
I just played around with php and the solution looks like this:
function myFunction($requiredArgument, $optionalArgument = "default"){
echo $requiredArgument . $optionalArgument;
}
This function can do two things:
If its called with only the required parameter: myFunction("Hi")
It will print "Hi default"
But if it is called with the optional parameter: myFunction("Hi","me")
It will print "Hi me";
I hope this helps anyone who is looking for this down the road.
Reset par to the default values at startup
An alternative solution for preventing functions to change the user par
. You can set the default parameters early on the function, so that the graphical parameters and layout will not be changed during the function execution. See ?on.exit
for further details.
on.exit(layout(1))
opar<-par(no.readonly=TRUE)
on.exit(par(opar),add=TRUE,after=FALSE)
How to get the background color code of an element in hex?
Check example link below and click on the div to get the color value in hex.
_x000D_
_x000D_
var color = '';_x000D_
$('div').click(function() {_x000D_
var x = $(this).css('backgroundColor');_x000D_
hexc(x);_x000D_
console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
delete(parts[0]);_x000D_
for (var i = 1; i <= 3; ++i) {_x000D_
parts[i] = parseInt(parts[i]).toString(16);_x000D_
if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
}_x000D_
color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
_x000D_
_x000D_
Check working example at http://jsfiddle.net/DCaQb/
How create Date Object with values in java
tl;dr
LocalDate.of( 2014 , 2 , 11 )
If you insist on using the terrible old java.util.Date
class, convert from the modern java.time classes.
java.util.Date // Terrible old legacy class, avoid using. Represents a moment in UTC.
.from( // New conversion method added to old classes for converting between legacy classes and modern classes.
LocalDate // Represents a date-only value, without time-of-day and without time zone.
.of( 2014 , 2 , 11 ) // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
.atStartOfDay( // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" ) // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`.
) // Returns a `ZonedDateTime`.
.toInstant() // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
) // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.
Details
If you want "easy", you should be using the new java.time package in Java 8 rather than the notoriously troublesome java.util.Date & .Calendar classes bundled with Java.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes.
Date-only
A LocalDate
class is offered by java.time to represent a date-only value without any time-of-day or time zone. You do need a time zone to determine a date, as a new day dawns earlier in Paris than in Montréal for example. The ZoneId
class is for time zones.
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );
Dump to console:
System.out.println ( "today: " + today + " in zone: " + zoneId );
today: 2015-11-26 in zone: Asia/Singapore
Or use a factory method to specify the year, month, day.
LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );
localDate: 2014-02-11
Or pass a month number 1-12 rather than a DayOfWeek
enum object.
LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );
Time zone
A LocalDate
has no real meaning until you adjust it into a time zone. In java.time, we apply a time zone to generate a ZonedDateTime
object. That also means a time-of-day, but what time? Usually makes sense to go with first moment of the day. You might think that means the time 00:00:00.000
, but not always true because of Daylight Saving Time (DST) and perhaps other anomalies. Instead of assuming that time, we ask java.time to determine the first moment of the day by calling atStartOfDay
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
zdt: 2014-02-11T00:00+08:00[Asia/Singapore]
UTC
For back-end work (business logic, database, data storage & exchange) we usually use UTC time zone. In java.time, the Instant
class represents a moment on the timeline in UTC. An Instant object can be extracted from a ZonedDateTime by calling toInstant
.
Instant instant = zdt.toInstant();
instant: 2014-02-10T16:00:00Z
Convert
You should avoid using java.util.Date
class entirely. But if you must interoperate with old code not yet updated for java.time, you can convert back-and-forth. Look to new conversion methods added to the old classes.
java.util.Date d = java.util.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda-Time library is now in maintenance mode, and advises migration to the java.time classes. I am leaving this section in place for history.
Joda-Time
For one thing, Joda-Time uses sensible numbering so February is 2
not 1
. Another thing, a Joda-Time DateTime truly knows its assigned time zone unlike a java.util.Date which seems to have time zone but does not.
And don't forget the time zone. Otherwise you'll be getting the JVM’s default.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );
java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );
Dump to console…
System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
When run…
dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT
Conversion
If you need to convert to a java.util.Date for use with other classes…
java.util.Date date = dateTimeSingapore.toDate();
Compiling LaTex bib source
Just in case it helps someone, since these questions (and answers) helped me really much; I decided to create an alias that runs these 4 commands in a row:
Just add the following line to your ~/.bashrc
file (modify the main
keyword accordingly to the name of your .tex
and .bib
files)
alias texbib = 'pdflatex main.tex && bibtex main && pdflatex main.tex && pdflatex main.tex'
And now, by just executing the texbib
command (alias), all these commands will be executed sequentially.
Change keystore password from no password to a non blank password
this way worked better for me:
echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt
machine running:
[root@rhel80-68]# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.1 (Ootpa)
C++ IDE for Linux?
could you clarify a little bit more how it was for you, what you had to change. Maybe you could point me in the right direction by providing some links to the information you used.
My first source were actually the tools' man
pages. Just type
$ man toolname
on the command line ($
here is part of the prompt, not the input).
Depending on the platform, they're quite well-written and can also be found on the internet. In the case of make
, I actually read the complete documentation which took a few hours. Actually, I don't think this is necessary or helpful in most cases but I had a few special requirements in my first assignments under Linux that required a sophisticated makefile. After writing the makefile I gave it to an experienced colleague who did some minor tweaks and corrections. After that, I pretty much knew make
.
I used GVIM because I had some (but not much) prior experience there, I can't say anything at all about Emacs or alternatives. I find it really helps to read other peoples' .gvimrc
config file. Many people put it on the web. Here's mine.
Don't try to master all binutils at once, there are too many functions. But get a general overview so you'll know where to search when needing something in the future. You should, however, know all the important parameters for g++
and ld
(the GCC linker tool that's invoked automatically except when explicitly prevented).
Also I'm curious, do you have code completion and syntax highlighting when you code?
Syntax highlighting: yes, and a much better one than Visual Studio. Code completion: yes-ish. First, I have to admit that I didn't use C++ code completion even in Visual Studio because (compared to VB and C#) it wasn't good enough. I don't use it often now but nevertheless, GVIM has native code completion support for C++. Combined with the ctags library and a plug-in like taglist this is almost an IDE.
Actually, what got me started was an article by Armin Ronacher. Before reading the text, look at the screenshots at the end of it!
do you have to compile first before getting (syntax) errors?
Yes. But this is the same for Visual Studio, isn't it (I've never used Whole Tomato)? Of course, the syntax highlighting will show you non-matching brackets but that's about all.
and how do you debug (again think breakpoints etc)?
I use gdb
which is a command-line tool. There's also a graphical frontend called DDD
. gdb
is a modern debugging tool and can do everything you can do in an IDE. The only thing that really annoys me is reading a stack trace because lines aren't indented or formatted so it's really hard to scan the information when you're using a lot of templates (which I do). But those also clutter the stack trace in IDEs.
Like I said, I had the 'pleasure' to set my first steps in the Java programming language using windows notepad and the command line java compiler in high school, and it was, .. wel a nightmare! certainly when I could compare it with other programming courses I had back then where we had decent IDE's
You shouldn't even try to compare a modern, full-feature editor like Emacs or GVIM to Notepad. Notepad is an embellished TextBox
control, and this really makes all the difference. Additionally, working on the command line is a very different experience in Linux and Windows. The Windows cmd.exe
is severely crippled. PowerShell is much better.
/EDIT: I should mention explicitly that GVIM has tabbed editing (as in tabbed browsing, not tabs-vs-spaces)! It took me ages to find them although they're not hidden at all. Just type :tabe
instead of plain :e
when opening a file or creating a new one, and GVIM will create a new tab. Switching between tabs can be done using the cursor or several different shortcuts (depending on the platform). The key gt
(type g, then t in command mode) should work everywhere, and jumps to the next tab, or tab no. n if a number was given. Type :help gt
to get more help.
Pass path with spaces as parameter to bat file
Interesting one. I love collecting quotes about quotes handling in cmd/command.
Your particular scripts gets fixed by using %1 instead of "%1" !!!
By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.
Scatter plot and Color mapping in Python
To add to wflynny's answer above, you can find the available colormaps here
Example:
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)
or alternatively,
plt.scatter(x, y, c=t, cmap='jet')
How to convert string to Date in Angular2 \ Typescript?
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
How to log out user from web site using BASIC authentication?
Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.
What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.
They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.
In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.
The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.
Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.
Python send UDP packet
Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.
#!/usr/bin/python
import sys, socket
def main(args):
ip = args[1]
port = int(args[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
file = 'sample.csv'
fp = open(file, 'r')
for line in fp:
sock.sendto(line.encode('utf-8'), (ip, port))
fp.close()
main(sys.argv)
The program reads a file, sample.csv
from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp
then one could run it by doing something like:
$ python send-udp 192.168.1.2 30088
Is the order of elements in a JSON list preserved?
Practically speaking, if the keys were of type NaN, the browser will not change the order.
The following script will output "One", "Two", "Three":
var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Whereas the following script will output "Three", "One", "Two":
var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Configuring ObjectMapper in Spring
Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter
if you only intend to configure ObjectMapper
.
(configure MappingJacksonHttpMessageConverter
will cause you to lose other MessageConverter)
You just need to do:
public class MyObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 4219938065516862637L;
public MyObjectMapper() {
super();
enable(SerializationFeature.INDENT_OUTPUT);
}
}
And in your Spring configuration, create this bean:
@Bean
public MyObjectMapper myObjectMapper() {
return new MyObjectMapper();
}
Simple PHP calculator
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
How to force an entire layout View refresh?
Calling invalidate()
or postInvalidate()
on the root layout apparently does NOT guarantee that children views will be redrawn. In my specific case, my root layout was a TableLayout and had several children of class TableRow and TextView. Calling postInvalidate()
, or requestLayout()
or even forceLayout()
on the root TableLayout object did not cause any TextViews in the layout to be redrawn.
So, what I ended up doing was recursively parsing the layout looking for those TextViews and then calling postInvalidate()
on each of those TextView objects.
The code can be found on GitHub:
https://github.com/jkincali/Android-LinearLayout-Parser