Import Excel to Datagridview
Since you have not replied to my comment above, I am posting a solution for both.
You are missing '
in Extended Properties
For Excel 2003 try this (TRIED AND TESTED)
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
BTW, I stopped working with Jet longtime ago. I use ACE now.
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
For Excel 2007+
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
Specified cast is not valid?
htmlStr
is string then You need to Date
and Time
variables to string
while (reader.Read())
{
DateTime Date = reader.GetDateTime(0);
DateTime Time = reader.GetDateTime(1);
htmlStr += "<tr><td>" + Date.ToString() + "</td><td>" +
Time.ToString() + "</td></tr>";
}
Need to install urllib2 for Python 3.5.1
Acording to the docs:
Note The urllib2 module has been split across several modules in Python 3 named urllib.request
and urllib.error
. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request
.
Getting the parameters of a running JVM
If you are interested in getting the JVM parameters of a running java process, then just do kill -3 java-pid. You will get a core dump file in which you can find the jvm parameters used while launching the java application.
MYSQL import data from csv using LOAD DATA INFILE
You can use LOAD DATA INFILE command to import csv file into table.
Check this link MySQL - LOAD DATA INFILE.
LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);
For MySQL 8.0 users:
Using the LOCAL
keyword hold security risks and as of MySQL 8.0 the LOCAL
capability is set to False
by default. You might see the error:
ERROR 1148: The used command is not allowed with this MySQL version
You can overwrite it by following the instructions in the docs.
Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.
Force LF eol in git repo and working copy
Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)
Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....
However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.
As you're partially working on Linux and Windows, make sure core.eol
is set to native
and core.autocrlf
is set to true
.
Then, replace the content of your .gitattributes
file with the following
* text=auto
This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.
However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.
Provided you work on a C based image processing project, replace the content of your .gitattributes
file with the following
* text=auto
*.txt text
*.c text
*.h text
*.jpg binary
This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.
In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.
As a real world example, you can also peek at this commit where those changes to a .gitattributes
file are demonstrated.
UPDATE to the answer considering the following comment
I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory
Makes sense. Thanks for the clarification. In this specific context, the .gitattributes
file by itself won't be enough.
Run the following commands against your repository
$ git config core.eol lf
$ git config core.autocrlf input
As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol
will make sure text files bear LF line endings on checkouts. core.autocrlf
will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.
Optionally, you can help Git distinguish what is a text file by creating a .gitattributes
file containing something similar to the following:
# Autodetect text files
* text=auto
# ...Unless the name matches the following
# overriding patterns
# Definitively text files
*.txt text
*.c text
*.h text
# Ensure those won't be messed up with
*.jpg binary
*.data binary
If you decided to create a .gitattributes
file, commit it.
Lastly, ensure git status
mentions "nothing to commit (working directory clean)", then perform the following operation
$ git checkout-index --force --all
This will recreate your files in your working directory, taking into account your config changes and the .gitattributes
file and replacing any potential overlooked CRLF in your text files.
Once this is done, every text file in your working directory WILL bear LF line endings and git status
should still consider the workdir as clean.
Bootstrap Carousel image doesn't align properly
In Bootstrap 4, you can add mx-auto
class to your img
tag.
For instance, if your image has a width of 75%, it should look like this:
<img class="d-block w-75 mx-auto" src="image.jpg" alt="First slide">
Bootstrap will automatically translate mx-auto
to:
ml-auto, .mx-auto {
margin-left: auto !important;
}
.mr-auto, .mx-auto {
margin-right: auto !important;
}
How do I check form validity with angularjs?
When you put <form>
tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form
that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form>
will satisfy:
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
So to check form validity, you can check value of $scope.yourformname.$valid
property of scope.
More information you can get at Developer's Guide section about forms.
The simplest way to resize an UIImage?
I've also seen this done as well (which I use on UIButtons
for Normal and Selected state since buttons don't resize
to fit). Credit goes to whoever the original author was.
First make an empty .h and .m file called UIImageResizing.h
and UIImageResizing.m
// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end
// Put this in UIImageResizing.m
@implementation UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
Include that .h file in whatever .m file you're going to use the function in and then call it like this:
UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];
Adding a tooltip to an input box
It seems to be a bug, it work for all input type that aren't textbox (checkboxes, radio,...)
There is a quick workaround that will work.
<div data-tip="This is the text of the tooltip2">
<input type="text" name="test" value="44"/>
</div>
JsFiddle
How to make Twitter bootstrap modal full screen
The following class will make a full-screen modal in Bootstrap:
.full-screen {
width: 100%;
height: 100%;
margin: 0;
top: 0;
left: 0;
}
I'm not sure how the inner content of your modal is structured, this may have an effect on the overall height depending on the CSS that is associated with it.
UIDevice uniqueIdentifier deprecated - What to do now?
Apple has hidden the UDID from all public APIs, starting with iOS 7. Any UDID that begins with FFFF is a fake ID. The "Send UDID" apps that previously worked can no longer be used to gather UDID for test devices. (sigh!)
The UDID is shown when a device is connected to XCode (in the organizer), and when the device is connected to iTunes (although you have to click on 'Serial Number' to get the Identifier to display.
If you need to get the UDID for a device to add to a provisioning profile, and can't do it yourself in XCode, you will have to walk them through the steps to copy/paste it from iTunes.
Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?
Append an array to another array in JavaScript
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_
How to build & install GLFW 3 and use it in a Linux project
Step 1: Installing GLFW 3 on your system with CMAKE
For this install, I was using KUbuntu 13.04, 64bit.
The first step is to download the latest version (assuming versions in the future work in a similar way) from www.glfw.org, probably using this link.
The next step is to extract the archive, and open a terminal. cd
into the glfw-3.X.X directory and run cmake -G "Unix Makefiles"
you may need elevated privileges, and you may also need to install build dependencies first. To do this, try sudo apt-get build-dep glfw
or sudo apt-get build-dep glfw3
or do it manually, as I did using sudo apt-get install cmake xorg-dev libglu1-mesa-dev
... There may be other libs you require such as the pthread libraries... Apparently I had them already. (See the -l options given to the g++ linker stage, below.)
Now you can type make
and then make install
, which will probably require you to sudo
first.
Okay, you should get some verbose output on the last three CMake stages, telling you what has been built or where it has been placed. (In /usr/include
, for example.)
Step 2: Create a test program and compile
The next step is to fire up vim ("what?! vim?!" you say) or your preferred IDE / text editor... I didn't use vim, I used Kate, because I am on KUbuntu 13.04... Anyway, download or copy the test program from here (at the bottom of the page) and save, exit.
Now compile using g++ -std=c++11 -c main.cpp
- not sure if c++11 is required but I used nullptr
so, I needed it... You may need to upgrade your gcc to version 4.7, or the upcoming version 4.8... Info on that here.
Then fix your errors if you typed the program by hand or tried to be "too clever" and something didn't work... Then link it using this monster! g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi
So you see, in the "install build dependencies" part, you may also want to check you have the GL, GLU, X11 Xxf86vm (whatever that is) Xrandr posix-thread and Xi (whatever that is) development libraries installed also. Maybe update your graphics drivers too, I think GLFW 3 may require OpenGL version 3 or higher? Perhaps someone can confirm that? You may also need to add the linker options -ldl -lXinerama -lXcursor
to get it to work correctly if you are getting undefined references to dlclose
(credit to @user2255242).
And, yes, I really did need that many -l
s!
Step 3: You are finished, have a nice day!
Hopefully this information was correct and everything worked for you, and you enjoyed writing the GLFW test program. Also hopefully this guide has helped, or will help, a few people in the future who were struggling as I was today yesterday!
By the way, all the tags are the things I searched for on stackoverflow looking for an answer that didn't exist. (Until now.) Hopefully they are what you searched for if you were in a similar position to myself.
Author Note:
This might not be a good idea. This method (using sudo make install) might be harzardous to your system. (See Don't Break Debian)
Ideally I, or someone else, should propose a solution which does not just install lib files etc into the system default directories as these should be managed by package managers such as apt
, and doing so may cause a conflict and break your package management system.
See the new "2020 answer" for an alternative solution.
Purpose of ESI & EDI registers?
There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are
REP STOSB
REP MOVSB
REP SCASB
Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.
Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )
That's most of what those regs are for.
Pagination response payload from a RESTful API
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
- Without the total count, how can the client know that it has not yet received everything there is and should continue paging through the result set? In a UI that didn't perform look ahead to the next page, in the worst case this might be represented as a Next/More link that didn't actually fetch any more data.
- Including metadata in the response allows the client to track less state. Now I don't have to match up my REST request with the response, as the response contains the metadata necessary to reconstruct the request state (in this case the cursor into the dataset).
- If the state is part of the response, I can perform multiple requests into the same dataset simultaneously, and I can handle the requests in any order they happen to arrive in which is not necessarily the order I made the requests in.
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
How do I set the value property in AngularJS' ng-options?
ngOptions directive:
$scope.items = [{name: 'a', age: 20},{ name: 'b', age: 30},{ name: 'c', age: 40}];
Case-1) label for value in array:
<div>
<p>selected item is : {{selectedItem}}</p>
<p> age of selected item is : {{selectedItem.age}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
Output Explanation (Assume 1st item selected):
selectedItem = {name: 'a', age: 20} // [by default, selected item is equal to the value item]
selectedItem.age = 20
Output Explanation (Assume 1st item selected):
selectedItem = 20 // [select part is item.age]
remove item from stored array in angular 2
//declaration
list: Array<any> = new Array<any>();
//remove item from an array
removeitem()
{
const index = this.list.findIndex(user => user._id === 2);
this.list.splice(index, 1);
}
Can't find AVD or SDK manager in Eclipse
I would suggest you to install the ADT plugin compatable with your Android SDK tools and try to install all the required plugins compatable with your Android SDK
LIKE
Android SDK tools Rev 20.0.3
Android SDK tools Rev 20.0.3
Android SDK Platform-tools Rev 14
Android 2.3.3(API 10) sdk platform rev 2
samples for sdk api 10 rev 1
ADT Plugin 20.0.3
How to display text in pygame?
You can create a surface with text on it. For this take a look at this short example:
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)
This creates a new object on which you can call the render
method.
textsurface = myfont.render('Some Text', False, (0, 0, 0))
This creates a new surface with text already drawn onto it.
At the end you can just blit the text surface onto your main screen.
screen.blit(textsurface,(0,0))
Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.
Best way to parse RSS/Atom feeds with PHP
I would like introduce simple script to parse RSS:
$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser
// RSS items loop
print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src
foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}
$i++;
}
How to use KeyListener
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
@Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.
Including non-Python files with setup.py
None of the answers worked for me because my files were at the top level, outside the package. I used a custom build command instead.
import os
import setuptools
from setuptools.command.build_py import build_py
from shutil import copyfile
HERE = os.path.abspath(os.path.dirname(__file__))
NAME = "thepackage"
class BuildCommand(build_py):
def run(self):
build_py.run(self)
if not self.dry_run:
target_dir = os.path.join(self.build_lib, NAME)
for fn in ["VERSION", "LICENSE.txt"]:
copyfile(os.path.join(HERE, fn), os.path.join(target_dir,fn))
setuptools.setup(
name=NAME,
cmdclass={"build_py": BuildCommand},
description=DESCRIPTION,
...
)
Getting return value from stored procedure in C#
You say your SQL compiles fine, but I get: Must declare the scalar variable "@Password".
Also you are trying to return a varchar (@b) from your stored procedure, but SQL Server stored procedures can only return integers.
When you run the procedure you are going to get the error:
'Conversion failed when converting the varchar value 'x' to data type int.'
Font is not available to the JVM with Jasper Reports
JasperReports raises a JRFontNotFoundException in the case where the font used inside a report template is not available to the JVM as either as a system font or a font coming from a JR font extension. This ensure that all problems caused by font metrics mismatches are avoided and we have an early warning about the inconsistency.
Jasper reports is trying to help you in your report development, stating that it can not export your report correctly since it can not find the font defined in TextField
or StaticText
<font fontName="Arial"/>
Yes you can disable this by setting net.sf.jasperreports.awt.ignore.missing.font to true but you will have export inconsistencies.
Yes you can install the font as JVM system font (but you need to do it on every PC used that may generate report and you can still have encoding problems).
The correct way!
Use Font Extensions!, if you like to create your own (see link below), jasper reports also distributes a default font-extension jar (jasperreports-fonts-x.x.x.jar
), that supports fontName DejaVu Sans
, DejaVu Serif
and DejaVu Sans Mono
<font fontName="DejaVu Sans"/>
From the JasperReport Ultimate Guide:
We strongly encourage people to use only fonts derived from font
extensions, because this is the only way to make sure that the fonts
will be available to the application when the reports are executed at
runtime. Using system fonts always brings the risk for the reports not
to work properly when deployed on a new machine that might not have
those fonts installed
Links on StackOverflow on how to render fonts correctly in pdf
Checklist on how to render font correctly in pdf
Generate font-extensions with JasperSoft Studio
Generate font-extensions with iReport
How do I make an HTTP request in Swift?
var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"
NSLog("PostData: %@",post);
var url1:NSURL = NSURL(string: url)!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
let success:NSInteger = jsonData.valueForKey("error") as NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 0)
{
NSLog("Login SUCCESS");
self.dataArr = jsonData.valueForKey("data") as NSMutableArray
self.table.reloadData()
} else {
NSLog("Login failed1");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
} else {
NSLog("Login failed2");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
} else {
NSLog("Login failed3");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
it will help you surely
Query Mongodb on month, day, year... of a datetime
You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.
As an example if you want all the orders which are created in April 2016 you can use below query.
db.getCollection('orders').aggregate(
[
{
$project:
{
doc: "$$ROOT",
year: { $year: "$created" },
month: { $month: "$created" },
day: { $dayOfMonth: "$created" }
}
},
{ $match : { "month" : 4, "year": 2016 } }
]
)
Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.
You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.
How to make jQuery UI nav menu horizontal?
I just been for 3 days looking for a jquery UI and CSS solution, I merge some code I saw, fix a little, and finally (along the other codes) I could make it work!
http://jsfiddle.net/Moatilliatta/97m6ty1a/
<ul id="nav" class="testnav">
<li><a class="clk" href="#">Item 1</a></li>
<li><a class="clk" href="#">Item 2</a></li>
<li><a class="clk" href="#">Item 3</a>
<ul class="sub-menu">
<li><a href="#">Item 3-1</a>
<ul class="sub-menu">
<li><a href="#">Item 3-11</a></li>
<li><a href="#">Item 3-12</a>
<ul>
<li><a href="#">Item 3-111</a></li>
<li><a href="#">Item 3-112</a>
<ul>
<li><a href="#">Item 3-1111</a></li>
<li><a href="#">Item 3-1112</a></li>
<li><a href="#">Item 3-1113</a>
<ul>
<li><a href="#">Item 3-11131</a></li>
<li><a href="#">Item 3-11132</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Item 3-113</a></li>
</ul>
</li>
<li><a href="#">Item 3-13</a></li>
</ul>
</li>
<li><a href="#">Item 3-2</a>
<ul>
<li><a href="#."> Item 3-21 </a></li>
<li><a href="#."> Item 3-22 </a></li>
<li><a href="#."> Item 3-23 </a></li>
</ul>
</li>
<li><a href="#">Item 3-3</a></li>
<li><a href="#">Item 3-4</a></li>
<li><a href="#">Item 3-5</a></li>
</ul>
</li>
<li><a class="clk" href="#">Item 4</a>
<ul class="sub-menu">
<li><a href="#">Item 4-1</a>
<ul class="sub-menu">
<li><a href="#."> Item 4-11 </a></li>
<li><a href="#."> Item 4-12 </a></li>
<li><a href="#."> Item 4-13 </a>
<ul>
<li><a href="#."> Item 4-131 </a></li>
<li><a href="#."> Item 4-132 </a></li>
<li><a href="#."> Item 4-133 </a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Item 4-2</a></li>
<li><a href="#">Item 4-3</a></li>
</ul>
</li>
<li><a class="clk" href="#">Item 5</a></li>
</ul>
javascript
$(document).ready(function(){
var menu = "#nav";
var position = {my: "left top", at: "left bottom"};
$(menu).menu({
position: position,
blur: function() {
$(this).menu("option", "position", position);
},
focus: function(e, ui) {
if ($(menu).get(0) !== $(ui).get(0).item.parent().get(0)) {
$(this).menu("option", "position", {my: "left top", at: "right top"});
}
}
}); });
CSS
.ui-menu {width: auto;}.ui-menu:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}.ui-menu .ui-menu-item {display: inline-block;margin: 0;padding: 0;width: auto;}#nav{text-align: center;font-size: 12px;}#nav li {display: inline-block;}#nav li a span.ui-icon-carat-1-e {float:right;position:static;margin-top:2px;width:16px;height:16px;background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -64px -16px;}#nav li ul li {width: 120px;border-bottom: 1px solid #ccc;}#nav li ul {width: 120px; }.ui-menu .ui-menu-item li a span.ui-icon-carat-1-e {background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -32px -16px !important;
Is it possible to make abstract classes in Python?
This one will be working in python 3
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
Abstract()
>>> TypeError: Can not instantiate abstract class Abstract with abstract methods foo
How to align input forms in HTML
<form>
<div>
<label for='username'>UserName</label>
<input type='text' name='username' id='username' value=''>
</div>
</form>
In the CSS you have to declare both label and input as display: inline-block and give width according to your requirements. Hope this will help you. :)
Jquery UI Datepicker not displaying
In case you are having this issue when working with WordPress control panel and using a ThemeRoller generated theme - be sure that you are using 1.7.3 Version of theme, 1.8.13 will not work. (If you look closely, the element is being rendered, but .ui-helper-hidden-accessible is causing it to not be displayed.
Current WP Version: 3.1.3
onclick="javascript:history.go(-1)" not working in Chrome
Why not get rid of the inline javascript and do something like this instead?
Inline javascript is considered bad practice as it is outdated.
Notes
Why use addEventListener?
addEventListener is the way to register an event listener as specified
in W3C DOM. Its benefits are as follows:
It allows adding more than a single handler for an event. This is
particularly useful for DHTML libraries or Mozilla extensions that
need to work well even if other libraries/extensions are used. It
gives you finer-grained control of the phase when the listener gets
activated (capturing vs. bubbling) It works on any DOM element, not
just HTML elements.
<a id="back" href="www.mypage.com"> Link </a>
document.getElementById("back").addEventListener("click", window.history.back, false);
On jsfiddle
Convert java.util.Date to String
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
How to import image (.svg, .png ) in a React Component
You can also try:
...
var imageName = require('relative_path_of_image_from_component_file');
...
...
class XYZ extends Component {
render(){
return(
...
<img src={imageName.default} alt="something"/>
...
)
}
}
...
Note: Make sure Image is not outside the project root folder.
FragmentActivity to Fragment
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
How to set button click effect in Android?
If you're using xml background instead of IMG, just remove this :
<item>
<bitmap android:src="@drawable/YOURIMAGE"/>
</item>
from the 1st answer that @Ljdawson gave us.
Set HTTP header for one request
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
PHP compare time
Simple way to compare time is :
$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
// your code
}
How do I get the picture size with PIL?
This is a complete example loading image from URL, creating with PIL, printing the size and resizing...
import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)
from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))
width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)
Matching an optional substring in a regex
You can do this:
([0-9]+) (\([^)]+\))? Z
This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Ignore mapping one property with Automapper
When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list
Mapper.CreateMap<OrderModel, Orders>(MemberList.Source);
Now my mapping validation doesn't fail, requiring another Ignore()
, every time I add a property to my domain class.
user authentication libraries for node.js?
A word of caution regarding handrolled approaches:
I'm disappointed to see that some of the suggested code examples in this post do not protect against such fundamental authentication vulnerabilities such as session fixation or timing attacks.
Contrary to several suggestions here, authentication is not simple and handrolling a solution is not always trivial. I would recommend passportjs and bcrypt.
If you do decide to handroll a solution however, have a look at the express js provided example for inspiration.
Good luck.
Find all files with a filename beginning with a specified string?
ls | grep "^abc"
will give you all files beginning (which is what the OP specifically required) with the substringabc
.
It operates only on the current directory whereas find
operates recursively into sub folders.
To use find
for only files starting with your string try
find . -name 'abc'*
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
Requires PHP5.3:
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
This will output all days in the defined period between $start
and $end
. If you want to include the 10th, set $end
to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.
How to display a gif fullscreen for a webpage background?
You can set up a background with your GIF file and set the body this way:
body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}
Change background image URL with your GIF. With background-position: center
you can put the image to the center and with background-size: cover
you set the picture to fit all the screen. You can also set background-size: contain
if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.
Here's more info about the property:
http://www.w3schools.com/cssref/css3_pr_background-size.asp
Hope it helps :)
How can I measure the similarity between two images?
How to measure similarity between two images entirely depends on what you would like to measure, for example: contrast, brightness, modality, noise... and then choose the best suitable similarity measure there is for you. You can choose from MAD (mean absolute difference), MSD (mean squared difference) which are good for measuring brightness...there is also available CR (correlation coefficient) which is good in representing correlation between two images. You could also choose from histogram based similarity measures like SDH (standard deviation of difference image histogram) or multimodality similarity measures like MI (mutual information) or NMI (normalized mutual information).
Because this similarity measures cost much in time, it is advised to scale images down before applying these measures on them.
Generate a range of dates using SQL
Ahahaha, here's a funny way I just came up with to do this:
select SYSDATE - ROWNUM
from shipment_weights sw
where ROWNUM < 365;
where shipment_weights is any large table;
getaddrinfo: nodename nor servname provided, or not known
I ran into a similar situation today - deploying an app to a mac os x server, and receiving the 'getaddrinfo' message when I tried to access an external api. It turns out that the error occurs when the ssh session that originally launched the app is no longer active. That's why everything works perfectly if you ssh into your server and run commands manually (or launch the server manually) - as long as you keep your ssh session alive, this error won't occur.
Whether this is a bug or a quirk in OS X, I'm not sure. Here's the page that led me to the solution - http://lists.apple.com/archives/unix-porting/2010/Jul/msg00001.html
All I had to do was update my capistrano task to launch the app using 'nohup'. So changing
run "cd #{current_path} && RAILS_ENV=production unicorn_rails -c config/unicorn.rb -D"
to
run "cd #{current_path} && RAILS_ENV=production nohup unicorn_rails -c config/unicorn.rb -D"
did the trick for me.
Hope this helps somebody - it was quite a pain to figure out!
How can I check file size in Python?
You need the st_size
property of the object returned by os.stat
. You can get it by either using pathlib
(Python 3.4+):
>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564
or using os.stat
:
>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564
Output is in bytes.
Declaring and initializing arrays in C
Why can't you initialize when you declare?
Which C compiler are you using? Does it support C99?
If it does support C99, you can declare the variable where you need it and initialize it when you declare it.
The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.
MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query
Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
AS new
ON DUPLICATE KEY UPDATE
age = new.age
...
For earlier versions use the keyword VALUES
(see reference, deprecated with MySQL 8.0.20).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
ON DUPLICATE KEY UPDATE
age = VALUES(age),
...
Creating a range of dates in Python
From the title of this question I was expecting to find something like range()
, that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.
So with the risk of being slightly off-topic, this one-liner does the job:
import datetime
start_date = datetime.date(2011, 01, 01)
end_date = datetime.date(2014, 01, 01)
dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
All credits to this answer!
Regular expressions inside SQL Server
stored value in DB is: 5XXXXXX [where x can be any digit]
You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.
Use:
WHERE CHARINDEX(column, '5') = 1
AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
AND ISNUMERIC(column) = 1
References:
i have also different cases like XXXX7XX for example, so it has to be generic.
Use:
WHERE PATINDEX('%7%', column) = 5
AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
AND ISNUMERIC(column) = 1
References:
Regex Support
SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:
5\d{6}
for your first example
\d{4}7\d{2}
for your second example
For more info on regular expressions, I highly recommend this website.
Start service in Android
I like to make it more dynamic
Class<?> serviceMonitor = MyService.class;
private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService() { context.stopService(new Intent(context, serviceMonitor)); }
do not forget the Manifest
<service android:enabled="true" android:name=".MyService.class" />
How to print current date on python3?
I use this which is standard for every time
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Getting Integer value from a String using javascript/jquery
just do this , you need to remove char other than "numeric" and "." form your string will do work for you
yourString = yourString.replace ( /[^\d.]/g, '' );
your final code will be
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
Demo
How to save data file into .RData?
There are three ways to save objects from your R session:
Saving all objects in your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
Saving some objects in your R session:
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
Saving a single object
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
JavaScript: filter() for Objects
First of all, it's considered bad practice to extend Object.prototype
. Instead, provide your feature as utility function on Object
, just like there already are Object.keys
, Object.assign
, Object.is
, ...etc.
I provide here several solutions:
- Using
reduce
and Object.keys
- As (1), in combination with
Object.assign
- Using
map
and spread syntax instead of reduce
- Using
Object.entries
and Object.fromEntries
1. Using reduce
and Object.keys
With reduce
and Object.keys
to implement the desired filter (using ES6 arrow syntax):
_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
Object.keys(obj)_x000D_
.filter( key => predicate(obj[key]) )_x000D_
.reduce( (res, key) => (res[key] = obj[key], res), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
Note that in the above code predicate
must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter
works.
2. As (1), in combination with Object.assign
In the above solution the comma operator is used in the reduce
part to return the mutated res
object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign
instead, which does return the mutated object:
_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
Object.keys(obj)_x000D_
.filter( key => predicate(obj[key]) )_x000D_
.reduce( (res, key) => Object.assign(res, { [key]: obj[key] }), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
3. Using map
and spread syntax instead of reduce
Here we move the Object.assign
call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):
_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
Object.assign(...Object.keys(obj)_x000D_
.filter( key => predicate(obj[key]) )_x000D_
.map( key => ({ [key]: obj[key] }) ) );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
4. Using Object.entries
and Object.fromEntries
As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries
(ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries
(ES2019).
It leads to this "one-liner" method on Object
:
_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
Object.fromEntries(Object.entries(obj).filter(predicate));_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
_x000D_
var filtered = Object.filter(scores, ([name, score]) => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.
form_for with nested resources
You don't need to do special things in the form. You just build the comment correctly in the show action:
class ArticlesController < ActionController::Base
....
def show
@article = Article.find(params[:id])
@new_comment = @article.comments.build
end
....
end
and then make a form for it in the article view:
<% form_for @new_comment do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post Comment" %>
<% end %>
by default, this comment will go to the create
action of CommentsController
, which you will then probably want to put redirect :back
into so you're routed back to the Article
page.
Automatically size JPanel inside JFrame
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
How to send a Post body in the HttpClient request in Windows Phone 8?
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
How to use querySelectorAll only for elements that have a specific attribute set?
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
Is there a destructor for Java?
There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors:
@Cleanup
ResourceClass resource = new ResourceClass();
When processing it (at compilation time), Lombok inserts appropriate try-finally
block so that resource.close()
is invoked, when execution leaves the scope of the variable. You can also specify explicitly another method for releasing the resource, e.g. resource.dispose()
:
@Cleanup("dispose")
ResourceClass resource = new ResourceClass();
How to check if an app is installed from a web-page on an iPhone?
I need to do something like this I ended up going with the following solution.
I have a specific website URL that will open a page with two buttons
1) Button One go to website
2) Button Two go to application (iphone / android phone / tablet) you can fall back to a default location from here if the app is not installed (like another url or an app store)
3) cookie to remember users choice
<head>
<title>Mobile Router Example </title>
<script type="text/javascript">
function set_cookie(name,value)
{
// js code to write cookie
}
function read_cookie(name) {
// jsCode to read cookie
}
function goToApp(appLocation) {
setTimeout(function() {
window.location = appLocation;
//this is a fallback if the app is not installed. Could direct to an app store or a website telling user how to get app
}, 25);
window.location = "custom-uri://AppShouldListenForThis";
}
function goToWeb(webLocation) {
window.location = webLocation;
}
if (readCookie('appLinkIgnoreWeb') == 'true' ) {
goToWeb('http://somewebsite');
}
else if (readCookie('appLinkIgnoreApp') == 'true') {
goToApp('http://fallbackLocation');
}
</script>
</head>
<body>
<div class="iphone_table_padding">
<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<!-- INTRO -->
<span class="iphone_copy_intro">Check out our new app or go to website</span>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_btn_padding">
<!-- GET IPHONE APP BTN -->
<table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreApp',document.getElementById('chkDontShow').checked);goToApp('http://getappfallback')">
<tr>
<td class="iphone_btn_on_left"> </td>
<td class="iphone_btn_on_mid">
<span class="iphone_copy_btn">
Get The Mobile Applications
</span>
</td>
<td class="iphone_btn_on_right"> </td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_btn_padding">
<table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreWeb',document.getElementById('chkDontShow').checked);goToWeb('http://www.website.com')">
<tr>
<td class="iphone_btn_left"> </td>
<td class="iphone_btn_mid">
<span class="iphone_copy_btn">
Visit Website.com
</span>
</td>
<td class="iphone_btn_right"> </td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_chk_padding">
<!-- CHECK BOX -->
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="checkbox" id="chkDontShow" /></td>
<td>
<span class="iphone_copy_chk">
<label for="chkDontShow"> Don’t show this screen again.</label>
</span>
</td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
</table>
</div>
</body>
</html>
Rotate a div using javascript
I recently had to build something similar. You can check it out in the snippet below.
The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin
Basically, my code looks like this...
Run Code Snippet
_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
runner = setInterval(function(){_x000D_
degrees++;_x000D_
rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
},50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
if (!rotate){_x000D_
rotate = true;_x000D_
start();_x000D_
} else {_x000D_
rotate = false;_x000D_
stop();_x000D_
}_x000D_
})
_x000D_
body {_x000D_
background: #1e1e1e;_x000D_
} _x000D_
_x000D_
.rocket {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
margin: 1em;_x000D_
border: 3px dashed teal;_x000D_
border-radius: 50%;_x000D_
background-color: rgba(128,128,128,0.5);_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.rocket h1 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-size: .8em;_x000D_
color: skyblue;_x000D_
letter-spacing: 1em;_x000D_
text-shadow: 0 0 10px black;_x000D_
}_x000D_
_x000D_
.toggle {_x000D_
margin: 10px;_x000D_
background: #000;_x000D_
color: white;_x000D_
font-size: 1em;_x000D_
padding: .3em;_x000D_
border: 2px solid red;_x000D_
outline: none;_x000D_
letter-spacing: 3px;_x000D_
}
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_
Is there a way to 'uniq' by column?
sort -u -t, -k1,1 file
-u
for unique
-t,
so comma is the delimiter
-k1,1
for the key field 1
Test result:
[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
Download file from web in Python 3
Yes, definietly requests is great package to use in something related to HTTP requests. but we need to be careful with the encoding type of the incoming data as well below is an example which explains the difference
from requests import get
# case when the response is byte array
url = 'some_image_url'
response = get(url)
with open('output', 'wb') as file:
file.write(response.content)
# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'
response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding
with open('output', 'w', encoding='utf-8') as file:
file.write(response.content)
Generate fixed length Strings filled with whitespaces
This simple function works for me:
public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}
Invocation:
String s = leftPad(myString, 10, "0");
Notice: Undefined offset: 0 in
If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then
It looks like we're using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.
Can you try changing line 800 to:
$r_rows = $this->_frames[$g_key]["rows"];
($g_key instead of $r_key)
https://github.com/dompdf/dompdf/issues/1295
replace anchor text with jquery
$('#link1').text("Replacement text");
The .text()
method drops the text you pass it into the element content. Unlike using .html()
, .text()
implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>
, <i>
, or whatever other similar elements, use .html()
instead.
SQL Row_Number() function in Where Clause
To get around this issue, wrap your select statement in a CTE, and then you can query against the CTE and use the windowed function's results in the where clause.
WITH MyCte AS
(
select employee_id,
RowNum = row_number() OVER ( order by employee_id )
from V_EMPLOYEE
ORDER BY Employee_ID
)
SELECT employee_id
FROM MyCte
WHERE RowNum > 0
How can I make my flexbox layout take 100% vertical space?
Let me show you another way that works 100%. I will also add some padding for the example.
<div class = "container">
<div class = "flex-pad-x">
<div class = "flex-pad-y">
<div class = "flex-pad-y">
<div class = "flex-grow-y">
Content Centered
</div>
</div>
</div>
</div>
</div>
.container {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
}
.flex-pad-x {
padding: 0px 20px;
height: 100%;
display: flex;
}
.flex-pad-y {
padding: 20px 0px;
width: 100%;
display: flex;
flex-direction: column;
}
.flex-grow-y {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.
1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally.
2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.
Hope this helps
Daniel
Disable-web-security in Chrome 48+
Update 2020-04-30
As of Chrome 81, it is mandatory to pass both --disable-site-isolation-trials
and a non-empty profile path via --user-data-dir
in order for --disable-web-security
to take effect:
# MacOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
(Speculation) It is likely that Chrome requires a non-empty profile path to mitigate the high security risk of launching the browser with web security disabled on the default profile. See --user-data-dir=
vs --user-data-dir=/some/path
for more details below.
Thanks to @Snæbjørn for the Chrome 81 tip in the comments.
Update 2020-03-06
As of Chrome 80 (possibly even earlier), the combination of flags --user-data-dir=/tmp/some-path --disable-web-security --disable-site-isolation-trials
no longer disables web security.
It is unclear when the Chromium codebase regressed, but downloading an older build of Chromium (following "Not-so-easy steps" on the Chromium download page) is the only workaround I found. I ended up using Version 77.0.3865.0, which properly disables web security with these flags.
Original Post 2019-11-01
In Chrome 67+, it is necessary to pass the --disable-site-isolation-trials
flag alongside arguments --user-data-dir=
and --disable-web-security
to truly disable web security.
On MacOS, the full command becomes:
open -na Google\ Chrome --args --user-data-dir= --disable-web-security --disable-site-isolation-trials
Regarding --user-data-dir
Per David Amey's answer, it is still necessary to specify --user-data-dir=
for Chrome to respect the --disable-web-security
option.
--user-data-dir=
vs --user-data-dir=/some/path
Though passing in an empty path via --user-data-dir=
works with --disable-web-security
, it is not recommended for security purposes as it uses your default Chrome profile, which has active login sessions to email, etc. With Chrome security disabled, your active sessions are thus vulnerable to additional in-browser exploits.
Thus, it is recommended to use an alternative directory for your Chrome profile with --user-data-dir=/tmp/chrome-sesh
or equivalent. Credit to @James B for pointing this out in the comments.
Source
This fix was discoreved within the browser testing framework Cypress: https://github.com/cypress-io/cypress/issues/1951
S3 Static Website Hosting Route All Paths to Index.html
I ran into the same problem today but the solution of @Mark-Nutter was incomplete to remove the hashbang from my angularjs application.
In fact you have to go to Edit Permissions, click on Add more permissions and then add the right List on your bucket to everyone. With this configuration, AWS S3 will now, be able to return 404 error and then the redirection rule will properly catch the case.
Just like this :
And then you can go to Edit Redirection Rules and add this rule :
<RoutingRules>
<RoutingRule>
<Condition>
<HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
</Condition>
<Redirect>
<HostName>subdomain.domain.fr</HostName>
<ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
</Redirect>
</RoutingRule>
</RoutingRules>
Here you can replace the HostName subdomain.domain.fr with your domain and the KeyPrefix #!/ if you don't use the hashbang method for SEO purpose.
Of course, all of this will only work if you have already have setup html5mode in your angular application.
$locationProvider.html5Mode(true).hashPrefix('!');
Best way to convert text files between character sets?
Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.
How can I get the session object if I have the entity-manager?
'entityManager.unwrap(Session.class)' is used to get session from EntityManager.
@Repository
@Transactional
public class EmployeeRepository {
@PersistenceContext
private EntityManager entityManager;
public Session getSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
......
......
}
Demo Application link.
css padding is not working in outlook
I changed to following and it worked for me
<tr>
<td bgcolor="#7d9aaa" style="color: #fff; font-size:15px; font-family:Arial, Helvetica, sans-serif; padding: 12px 2px 12px 0px; ">
<table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0">
<td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>
<td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>
</table>
</td>
</tr>
Update based on Bsalex request what has actually changed.
I replaced span tag
<span style="font-weight: bold;padding-right:150px;padding-left: 35px;">Order Confirmation </span>
<span style="font-weight: bold;width:400px;"> Your Confirmation number is {{var order.increment_id}} </span>
with table and td tags as following
<table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0">
<td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>
<td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>
</table>
How to scroll to bottom in react?
Full version (Typescript):
_x000D_
_x000D_
import * as React from 'react'_x000D_
_x000D_
export class DivWithScrollHere extends React.Component<any, any> {_x000D_
_x000D_
loading:any = React.createRef();_x000D_
_x000D_
componentDidMount() {_x000D_
this.loading.scrollIntoView(false);_x000D_
}_x000D_
_x000D_
render() {_x000D_
_x000D_
return (_x000D_
<div ref={e => { this.loading = e; }}> <LoadingTile /> </div>_x000D_
)_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_
How can I serve static html from spring boot?
I am using :: Spring Boot :: (v2.0.4.
RELEASE
) with Spring Framework 5
Spring Boot 2.0 requires Java 8 as a minimum version. Many existing APIs have been updated to take advantage of Java 8 features such as: default methods on interfaces, functional callbacks, and new APIs such as javax.time.
Static Content
By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer
and overriding the addResourceHandlers
method.
By default, resources are mapped on /**
and located on /static
directory.
But you can customize the static loactions programmatically inside our web context configuration class.
@Configuration @EnableWebMvc
public class Static_ResourceHandler implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// When overriding default behavior, you need to add default(/) as well as added static paths(/webapp).
// src/main/resources/static/...
registry
//.addResourceHandler("/**") // « /css/myStatic.css
.addResourceHandler("/static/**") // « /static/css/myStatic.css
.addResourceLocations("classpath:/static/") // Default Static Loaction
.setCachePeriod( 3600 )
.resourceChain(true) // 4.1
.addResolver(new GzipResourceResolver()) // 4.1
.addResolver(new PathResourceResolver()); //4.1
// src/main/resources/templates/static/...
registry
.addResourceHandler("/templates/**") // « /templates/style.css
.addResourceLocations("classpath:/templates/static/");
// Do not use the src/main/webapp/... directory if your application is packaged as a jar.
registry
.addResourceHandler("/webapp/**") // « /webapp/css/style.css
.addResourceLocations("/");
// File located on disk
registry
.addResourceHandler("/system/files/**")
.addResourceLocations("file:///D:/");
}
}
http://localhost:8080/handlerPath/resource-path+name
/static /css/myStatic.css
/webapp /css/style.css
/templates /style.css
In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.
As @STEEL
said static resources should not go through Controller. Thymleaf
is a ViewResolver which takes the view name form controller and adds prefix
and suffix
to View Layer.
How many characters can you store with 1 byte?
The syntax of TINYINT
data type is TINYINT(M)
,
where M
indicates the maximum display width (used only if your MySQL client supports it).
The (m) indicates the column width in SELECT statements; however, it
doesn't control the accepted range of numbers for that field.
A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.
TINYINT()
Java - Including variables within strings?
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
You should not use <Link> outside a <Router>
I was getting this error because I was importing a reusable component from an npm library and the versions of react-router-dom
did not match.
So make sure you use the same version in both places!
Python: How would you save a simple settings/config file?
Configuration files in python
There are several ways to do this depending on the file format required.
ConfigParser [.ini format]
I would use the standard configparser approach unless there were compelling reasons to use a different format.
Write a file like so:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')
with open('config.ini', 'w') as f:
config.write(f)
The file format is very simple with sections marked out in square brackets:
[main]
key1 = value1
key2 = value2
key3 = value3
Values can be extracted from the file like so:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"
# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')
# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')
JSON [.json format]
JSON data can be very complex and has the advantage of being highly portable.
Write data to a file:
import json
config = {"key1": "value1", "key2": "value2"}
with open('config1.json', 'w') as f:
json.dump(config, f)
Read data from a file:
import json
with open('config.json', 'r') as f:
config = json.load(f)
#edit the data
config['key3'] = 'value3'
#write it back to the file
with open('config.json', 'w') as f:
json.dump(config, f)
YAML
A basic YAML example is provided in this answer. More details can be found on the pyYAML website.
JAVA_HOME directory in Linux
Did you set your JAVA_HOME
- Korn and bash shells:export JAVA_HOME=jdk-install-dir
- Bourne shell:JAVA_HOME=jdk-install-dir;export JAVA_HOME
- C shell:setenv JAVA_HOME jdk-install-dir
Chaining Observables in RxJS
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
DLL load failed error when importing cv2
The issue is due to the missing python3.dll
file in Anaconda3.
To fix the issue, you should simply copy the python3.dll
to C:\Program Files\Anaconda3
(or wherever your Anaconda3 is installed).
You can get the python3.dll
by downloading the binaries provided at the bottom of the Python's Release page and extracting the python3.dll
from the ZIP file.
How to use global variables in React Native?
You can consider leveraging React's Context feature.
class NavigationContainer extends React.Component {
constructor(props) {
super(props);
this.goTo = this.goTo.bind(this);
}
goTo(location) {
...
}
getChildContext() {
// returns the context to pass to children
return {
goTo: this.goTo
}
}
...
}
// defines the context available to children
NavigationContainer.childContextTypes = {
goTo: PropTypes.func
}
class SomeViewContainer extends React.Component {
render() {
// grab the context provided by ancestors
const {goTo} = this.context;
return <button onClick={evt => goTo('somewhere')}>
Hello
</button>
}
}
// Define the context we want from ancestors
SomeViewContainer.contextTypes = {
goTo: PropTypes.func
}
With context
, you can pass data through the component tree without having to pass the props down manually at every level. There is a big warning on this being an experimental feature and may break in the future, but I would imagine this feature to be around given the majority of the popular frameworks like Redux use context
extensively.
The main advantage of using context
v.s. a global variable is context
is "scoped" to a subtree (this means you can define different scopes for different subtrees).
Do note that you should not pass your model data via context
, as changes in context
will not trigger React's component render cycle. However, I do find it useful in some use case, especially when implementing your own custom framework or workflow.
When to use <span> instead <p>?
A practical explanation: By default, <p> </p>
will add line breaks before and after the enclosed text (so it creates a paragraph). <span>
does not do this, that is why it is called inline.
What is the best way to measure execution time of a function?
Use a Profiler
Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.
The advantages they have is:
- You can even get a statement level
breakup
- No changes required in your codebase
- Instrumentions generally have very less overhead, hence very accurate results can be obtained.
There are many available open-source as well.
Solving a "communications link failure" with JDBC and MySQL
I faced this problem also.
As Soheil suggested,
I went to php.ini file at the path C:\windows\php.ini , then I revised port number in this file.
it is on the line mysqli.default_port =..........
So I changed it in my java app as it's in the php.ini file,now it works fine with me.
No newline at end of file
The core problem is what you define line and whether end-on-line
character sequence is part of the line or not. UNIX-based editors
(such as VIM) or tools (such as Git) use EOL character sequence as
line terminator, therefore it's a part of the line. It's similar to
use of semicolon (;) in C and Pascal. In C semicolon terminates
statements, in Pascal it separates them.
In AngularJS, what's the difference between ng-pristine and ng-dirty?
pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>_x000D_
<form ng-app="" name="myForm">_x000D_
<input name="email" ng-model="data.email">_x000D_
<div class="info" ng-show="myForm.email.$pristine">_x000D_
Email is virgine._x000D_
</div>_x000D_
<div class="error" ng-show="myForm.email.$dirty">_x000D_
E-mail is dirty_x000D_
</div>_x000D_
</form>
_x000D_
_x000D_
_x000D_
A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.
How to make circular background using css?
It can be done using the border-radius
property. basically, you need to set the border-radius to exactly half of the height and width to get a circle.
JSFiddle
HTML
<div id="container">
<div id="inner">
</div>
</div>
CSS
#container
{
height:400px;
width:400px;
border:1px black solid;
}
#inner
{
height:200px;
width:200px;
background:black;
-moz-border-radius: 100px;
-webkit-border-radius: 100px;
border-radius: 100px;
margin-left:25%;
margin-top:25%;
}
What is the difference between state and props in React?
State resides within a component where as props are passed from parent to child.
Props are generally immutable.
class Parent extends React.Component {
constructor() {
super();
this.state = {
name : "John",
}
}
render() {
return (
<Child name={this.state.name}>
)
}
}
class Child extends React.Component {
constructor() {
super();
}
render() {
return(
{this.props.name}
)
}
}
In the above code, we have a parent class(Parent) which has name as its state which is passed to the child component(Child class) as a prop and the child component renders it using {this.props.name}
How to change the default GCC compiler in Ubuntu?
Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root
:
apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5
Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:
update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin
(Note the use of cpp-bin
instead of just cpp
. Ubuntu already has a cpp
alternative with a master link of /lib/cpp
. Renaming that link would remove the /lib/cpp
link, which could break scripts.)
Efficient way to add spaces between characters in a string
The most efficient way is to take input make the logic and run
so the code is like this to make your own space maker
need = input("Write a string:- ")
result = ''
for character in need:
result = result + character + ' '
print(result) # to rid of space after O
but if you want to use what python give then use this code
need2 = input("Write a string:- ")
print(" ".join(need2))
How to destroy Fragment?
If you don't remove manually these fragments, they are still attached to the activity. Your activity is not destroyed so these fragments are too.
To remove (so destroy) these fragments, you can call:
fragmentTransaction.remove(yourfragment).commit()
Hope it helps to you
Converting JSON to XML in Java
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
Jquery/Ajax call with timer
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Modulo operator in Python
When you have the expression:
a % b = c
It really means there exists an integer n
that makes c
as small as possible, but non-negative.
a - n*b = c
By hand, you can just subtract 2
(or add 2
if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
Also, 3.14 % 2 * pi
is interpreted as (3.14 % 2) * pi
. I'm not sure if you meant to write 3.14 % (2 * pi)
(in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
Clear terminal in Python
You can use call()
function to execute terminal's commands :
from subprocess import call
call("clear")
How do I pre-populate a jQuery Datepicker textbox with today's date?
Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:
$( "#datepicker" ).datepicker();
<?php if (!empty($oneEVENT['start_ts'])): ?>
$( "#datepicker" ).datepicker( "setDate", "<?php echo $startDATE; ?>" );
<? else: ?>
$("#datepicker").datepicker('setDate', new Date());
<?php endif; ?>
});
'Java' is not recognized as an internal or external command
Assume, Java/JDK is installed to the folder: C:\Program Files\Java:
Follow the steps:
- Goto Control Panel ? System ? Advanced system settings ? Advanced ? Environment variables (Win+Pause/Break for System in Control Panel)
- In the System variables section click on New…
- In Variable name write:
JAVA_HOME
- In Variable value write:
C:\Program Files\Java\bin
, press OK:
- In the System variables section double click on
Path
- Press New and write
C:\Program Files\Java\bin
, press OK:
- In Environment variables window press OK
- Restart/Run
cmd.exe
and write: java --version
:
Removing special characters VBA Excel
Here is how removed special characters.
I simply applied regex
Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters
' Configure the regex object
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)
Remove Elements from a HashSet while Iterating
The reason you get a ConcurrentModificationException
is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.
The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.
If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.
for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
Integer element = it.next();
if (element % 2 == 0) {
it.remove();
}
}
How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long
value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
Postgres: How to do Composite keys?
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
How to describe "object" arguments in jsdoc?
There's a new @config
tag for these cases. They link to the preceding @param
.
/** My function does X and Y.
@params {object} parameters An object containing the parameters
@config {integer} setting1 A required setting.
@config {string} [setting2] An optional setting.
@params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
// ...
};
/**
* This callback is displayed as part of the MyClass class.
* @callback MyClass~FuncCallback
* @param {number} responseCode
* @param {string} responseMessage
*/
Launching a website via windows commandline
Ok, The Windows 10 BatchFile is done works just like I had hoped. First press the windows key and R. Type mmc and Enter. In File Add SnapIn>Got to a specific Website and add it to the list. Press OK in the tab, and on the left side console root menu double click your site. Once it opens Add it to favourites. That should place it in C:\Users\user\AppData\Roaming\Microsoft\StartMenu\Programs\Windows Administrative Tools. I made a shortcut of this to a folder on the desktop. Right click the Shortcut and view the properties. In the Shortcut tab of the Properties click advanced and check the Run as Administrator. The Start in Location is also on the Shortcuts Tab you can add that to your batch file if you need. The Batch I made is as follows
@echo off
title Manage SiteEnviro
color 0a
:Clock
cls
echo Date:%date% Time:%time%
pause
cls
c:\WINDOWS\System32\netstat
c:\WINDOWS\System32\netstat -an
goto Greeting
:Greeting
cls
echo Open ShellSite
pause
cls
goto Manage SiteEnviro
:Manage SiteEnviro
"C:\Users\user\AppData\Roaming\Microsoft\Start Menu\Programs\Administrative Tools\YourCustomSavedMMC.msc"
You need to make a shortcut when you save this as a bat file and in the properties>shortcuts>advanced enable administrator access, can also set a keybind there and change the icon if you like. I probably did not need :Clock. The netstat commands can change to setting a hosted network or anything you want including nothing. Can Canscade websites in 1 mmc console and have more than 1 favourite added into the batch file.
Stop absolutely positioned div from overlapping text
_x000D_
_x000D_
<div style="position: relative; width:600px;">_x000D_
<p>Content of unknown length</p>_x000D_
<div>Content of unknown height</div>_x000D_
<div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:
inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'
So I did it like this
.spacer {
float: left;
height: 20px;
width: 200px;
}
And it works just as well.
How do I get extra data from intent on Android?
Getting Different Types of Extra from Intent
To access data from Intent you should know two things.
- KEY
- DataType of your data.
There are different methods in Intent class to extract different kind of data types.
It looks like this
getIntent().XXXX(KEY) or intent.XXX(KEY);
So if you know the datatype of your varibale which you set in otherActivity you can use the respective method.
Example to retrieve String in your Activity from Intent
String profileName = getIntent().getStringExtra("SomeKey");
List of different variants of methods for different dataType
You can see the list of available methods in Official Documentation of Intent.
Convert a 1D array to a 2D array in numpy
You can useflatten()
from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
How can I put CSS and HTML code in the same file?
Is this what you're looking for? You place you CSS between style
tags in the HTML document header. I'm guessing for iPhone it's webkit so it should work.
<html>
<head>
<style type="text/css">
.title { color: blue; text-decoration: bold; text-size: 1em; }
.author { color: gray; }
</style>
</head>
<body>
<p>
<span class="title">La super bonne</span>
<span class="author">proposée par Jérém</span>
</p>
</body>
</html>
MySQL Sum() multiple columns
//Mysql sum of multiple rows
Hi Here is the simple way to do sum of columns
SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'
How do I add multiple conditions to "ng-disabled"?
There is maybe a bit of a gotcha in the phrasing of the original question:
I need to check that two conditions are both true before enabling a button
The first thing to remember that the ng-disabled directive is evaluating a condition under which the button should be, well, disabled, but the original question is referring to the conditions under which it should en enabled. It will be enabled under any circumstances where the ng-disabled expression is not "truthy".
So, the first consideration is how to rephrase the logic of the question to be closer to the logical requirements of ng-disabled. The logical inverse of checking that two conditions are true in order to enable a button is that if either condition is false then the button should be disabled.
Thus, in the case of the original question, the pseudo-expression for ng-disabled is "disable the button if condition1 is false or condition2 is false". Translating into the Javascript-like code snippet required by Angular (https://docs.angularjs.org/guide/expression), we get:
!condition1 || !condition2
Zoomlar has it right!
Tools for making latex tables in R
Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.
The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs
I would also add the apsrtable
package to the mix as it produces nice looking regression tables.
Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?
How do you upload a file to a document library in sharepoint?
string filePath = @"C:\styles\MyStyles.css";
string siteURL = "http://example.org/";
string libraryName = "Style Library";
using (SPSite oSite = new SPSite(siteURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(filePath))
throw new FileNotFoundException("File not found.", filePath);
SPFolder libFolder = oWeb.Folders[libraryName];
// Prepare to upload
string fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);
//Check the existing File out if the Library Requires CheckOut
if (libFolder.RequiresCheckout)
{
try {
SPFile fileOld = libFolder.Files[fileName];
fileOld.CheckOut();
} catch {}
}
// Upload document
SPFile spfile = libFolder.Files.Add(fileName, fileStream, true);
// Commit
myLibrary.Update();
//Check the File in and Publish a Major Version
if (libFolder.RequiresCheckout)
{
spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
spFile.Publish("Publish Comment");
}
}
}
HTTP POST with Json on Body - Flutter/Dart
OK, finally we have an answer...
You are correctly specifying headers: {"Content-Type": "application/json"},
to set your content type. Under the hood either the package http
or the lower level dart:io HttpClient
is changing this to application/json; charset=utf-8
. However, your server web application obviously isn't expecting the suffix.
To prove this I tried it in Java, with the two versions
conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works
Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.
EDIT
Later investigation shows that it's the http
package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http
and use the dart:io HttpClient
directly. You end up with a bit of boilerplate which is normally handled for you by http
.
Working example below:
import 'dart:convert';
import 'dart:io';
import 'dart:async';
main() async {
String url =
'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map map = {
'data': {'apikey': '12345678901234567890'},
};
print(await apiRequest(url, map));
}
Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}
Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)
How to hide navigation bar permanently in android activity?
It's my solution:
First, define boolean that indicate if navigation bar is visible or not.
boolean navigationBarVisibility = true //because it's visible when activity is created
Second create method that hide navigation bar.
private void setNavigationBarVisibility(boolean visibility){
if(visibility){
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
navigationBarVisibility = false;
}
else
navigationBarVisibility = true;
}
By default, if you click to activity after hide navigation bar, navigation bar will be visible. So we got it's state if it visible we will hide it.
Now set OnClickListener to your view. I use a surfaceview so for me:
playerSurface.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setNavigationBarVisibility(navigationBarVisibility);
}
});
Also, we must call this method when activity is launched. Because we want hide it at the beginning.
setNavigationBarVisibility(navigationBarVisibility);
JQuery Validate input file type
So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.
So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.
Converting Secret Key into a String and Vice Versa
try this, it's work without Base64 ( that is included only in JDK 1.8 ), this code run also in the previous java version :)
private static String SK = "Secret Key in HEX";
// To Encrupt
public static String encrypt( String Message ) throws Exception{
byte[] KeyByte = hexStringToByteArray( SK);
SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");
Cipher c = Cipher.getInstance("DES","SunJCE");
c.init(1, k);
byte mes_encrypted[] = cipher.doFinal(Message.getBytes());
String MessageEncrypted = byteArrayToHexString(mes_encrypted);
return MessageEncrypted;
}
// To Decrypt
public static String decrypt( String MessageEncrypted )throws Exception{
byte[] KeyByte = hexStringToByteArray( SK );
SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");
Cipher dcr = Cipher.getInstance("DES","SunJCE");
dc.init(Cipher.DECRYPT_MODE, k);
byte[] MesByte = hexStringToByteArray( MessageEncrypted );
byte mes_decrypted[] = dcipher.doFinal( MesByte );
String MessageDecrypeted = new String(mes_decrypted);
return MessageDecrypeted;
}
public static String byteArrayToHexString(byte bytes[]){
StringBuffer hexDump = new StringBuffer();
for(int i = 0; i < bytes.length; i++){
if(bytes[i] < 0)
{
hexDump.append(getDoubleHexValue(Integer.toHexString(256 - Math.abs(bytes[i]))).toUpperCase());
}else
{
hexDump.append(getDoubleHexValue(Integer.toHexString(bytes[i])).toUpperCase());
}
return hexDump.toString();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
How to declare a variable in a PostgreSQL query
Using a Temp Table outside of pl/PgSQL
Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.
begin;
select 5::int as var into temp table myvar;
select *
from somewhere s, myvar v
where s.something = v.var;
commit;
Git diff says subproject is dirty
I ended up removing the submodule directory and initializing it once again
cd my-submodule
git push
cd ../
rm -rf my-submodule
git submodule init
git submodule update
How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2
I also struggled finding articles on how to just generate the token part. I never found one and wrote my own. So if it helps:
The things to do are:
- Create a new web application
- Install the following NuGet packages:
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.Identity.Owin
- Add a OWIN
startup
class
Then create a HTML and a JavaScript (index.js
) file with these contents:
var loginData = 'grant_type=password&[email protected]&password=test123';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
The OWIN startup
class should have this content:
using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace OAuth20
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/token"),
Provider = new OAuthAuthorizationServerProvider()
{
OnValidateClientAuthentication = async (context) =>
{
context.Validated();
},
OnGrantResourceOwnerCredentials = async (context) =>
{
if (context.UserName == "[email protected]" && context.Password == "test123")
{
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
context.Validated(oAuthIdentity);
}
}
},
AllowInsecureHttp = true,
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
};
app.UseOAuthBearerTokens(OAuthOptions);
}
}
}
Run your project. The token should be displayed in the pop-up.
How do I implement charts in Bootstrap?
Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.
I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.
What JSON library to use in Scala?
I use uPickle which has the big advantage that it will handle nested case classes automatically:
object SerializingApp extends App {
case class Person(name: String, address: Address)
case class Address(street: String, town: String, zipCode: String)
import upickle.default._
val john = Person("John Doe", Address("Elm Street 1", "Springfield", "ABC123"))
val johnAsJson = write(john)
// Prints {"name":"John Doe","address":{"street":"Elm Street 1","town":"Springfield","zipCode":"ABC123"}}
Console.println(johnAsJson)
// Parse the JSON back into a Scala object
Console.println(read[Person](johnAsJson))
}
Add this to your build.sbt
to use uPickle:
libraryDependencies += "com.lihaoyi" %% "upickle" % "0.4.3"
How to pass in password to pg_dump?
the easiest way in my opinion, this:
you edit you main postgres config file: pg_hba.conf
there you have to add the following line:
host <you_db_name> <you_db_owner> 127.0.0.1/32 trust
and after this you need start you cron thus:
pg_dump -h 127.0.0.1 -U <you_db_user> <you_db_name> | gzip > /backup/db/$(date +%Y-%m-%d).psql.gz
and it worked without password
Why can't I define a static method in a Java interface?
To solve this :
error: missing method body, or declare abstract
static void main(String[] args);
interface I
{
int x=20;
void getValue();
static void main(String[] args){};//Put curly braces
}
class InterDemo implements I
{
public void getValue()
{
System.out.println(x);
}
public static void main(String[] args)
{
InterDemo i=new InterDemo();
i.getValue();
}
}
output :
20
Now we can use static method in interface
Best way to add Gradle support to IntelliJ Project
In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.
No need to delete any files or add the idea plugin to build.gradle.
Javascript form validation with password confirming
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
Why does foo = filter(...) return a <filter object>, not a list?
filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:
In [47]: def greetings(x):
....: return x == "hello"
....:
In [48]: filter(greetings, ["hello", "goodbye"])
Out[48]: ['hello']
Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"]))
to get this same result.
Can I set an unlimited length for maxJsonLength in web.config?
It appears that there is no "unlimited" value. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
As as already been observed, 17,000 records are hard to use well in the browser. If you are presenting an aggregate view it may be much more efficient to do the aggregation on the server and transfer only a summary in the browser. For example, consider a file system brower, we only see the top of the tree, then emit further requestes as we drill down. The number of records returned in each request is comparatively small. A tree view presentation can work well for large result sets.
How can I print out just the index of a pandas dataframe?
You can access the index attribute of a df using df.index[i]
>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
a b
0 0 1.088998
1 1 -1.381735
2 2 0.035058
3 3 -2.273023
4 4 1.345342
>> df.index[1] ## Second index
>> df.index[-1] ## Last index
>> for i in xrange(len(df)):print df.index[i] ## Using loop
...
0
1
2
3
4
How to select clear table contents without destroying the table?
There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.
The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents
attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.
I did some digging and found this advice from Mathieu Guindon:
Range SpecialCells ClearContents clears whole sheet
Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.
Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
' Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
' Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead
On Error Resume Next
With lst
'.Range.Worksheet.Activate ' Enable this if you are debugging
If .ShowAutoFilter Then .AutoFilter.ShowAllData
If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
.DataBodyRange.Offset(1).Rows.Clear
If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ElseIf Not .Range.HasFormula Then
' Only one cell in range and it does not contain a formula.
.DataBodyRange.Rows(1).ClearContents
End If
.Resize .Range.Rows("1:2")
.HeaderRowRange.Offset(1).Select
' Reset used range on the sheet
Dim X
X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73
End With
End Sub
A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73
Automatically Resetting The Last Cell
Form submit with AJAX passing form data to PHP without page refresh
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?
I recently ran into this problem again. It's been a while since I last worked with submodules and having learned more about git I realized that simply checking out the branch you want to commit on is sufficient. Git will keep the working tree even if you don't stash it.
git checkout existing_branch_name
If you want to work on a new branch this should work for you:
git checkout -b new_branch_name
The checkout will fail if you have conflicts in the working tree, but that should be quite unusual and if it happens you can just stash it, pop it and resolve the conflict.
Compared to the accepted answer, this answer will save you the execution of two commands, that don't really take that long to execute anyway. Therefore I will not accept this answer, unless it miraculously gets more upvotes (or at least close) than the currently accepted answer.
Can you target <br /> with css?
For the benefit of any future visitors who may have missed my comments:
br {
border-bottom:1px dashed black;
}
does not work.
It has been tested in IE 6, 7 & 8, Firefox 2, 3 & 3.5B4, Safari 3 & 4 for Windows, Opera 9.6 & 10 (alpha) and Google Chrome (version 2) and it didn't work in any of them. If at some point in the future someone finds a browser that does support a border on a <br>
element, please feel free to update this list.
Also note that I tried a number of other things:
br {
border-bottom:1px dashed black;
display:block;
}
br:before { /* and :after */
border-bottom:1px dashed black;
/* content and display added as per porneL's comment */
content: "";
display: block;
}
br { /* and :before and :after */
content: url(a_dashed_line_image);
}
Of those, the following does works in Opera 9.6 and 10 (alpha) (thanks porneL!):
br:after {
border-bottom:1px dashed black;
content: "";
display: block;
}
Not very useful when it is only supported in one browser, but I always find it interesting to see how different browsers implement the specification.
iPhone X / 8 / 8 Plus CSS media queries
Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
/* iphone 3 */
@media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
/* iphone 4 */
@media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 5 */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 6, 6s, 7, 8 */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 6+, 6s+, 7+, 8+ */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone X , XS, 11 Pro, 12 Mini */
@media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone 12, 12 Pro */
@media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone XR, 11 */
@media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
/* iphone XS Max, 11 Pro Max */
@media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }
/* iphone 12 Pro Max */
@media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }
How do I use TensorFlow GPU?
Follow this tutorial Tensorflow GPU I did it and it works perfect.
Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu
Steps:
- Uninstall your old tensorflow
- Install tensorflow-gpu
pip install tensorflow-gpu
- Install Nvidia Graphics Card & Drivers (you probably already have)
- Download & Install CUDA
- Download & Install cuDNN
- Verify by simple program
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Drop shadow for PNG image in CSS
This won't be possible with css - an image is a square, and so the shadow would be the shadow of a square. The easiest way would be to use photoshop/gimp or any other image editor to apply the shadow like core draw.
Abstraction VS Information Hiding VS Encapsulation
Abstraction
is hiding the implementation details by providing a layer over the basic functionality.
Information Hiding
is hiding the data which is being affected by that implementation. Use of private
and public
comes under this. For example, hiding the variables of the classes.
Encapsulation
is just putting all similar data and functions into a group e.g Class
in programming; Packet
in networking.
Through the use of Classes, we implement all three concepts - Abstraction
, Information Hiding
and Encapsulation
jQuery click function doesn't work after ajax call?
When you use $('.deletelanguage').click()
to register an event handler it adds the handler to only those elements which exists in the dom when the code was executed
you need to use delegation based event handlers here
$(document).on('click', '.deletelanguage', function(){
alert("success");
});
What is the .idea folder?
When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea
folder.
Project settings are stored with each specific project as a set of xml
files under the .idea folder. If you specify the default project
settings, these settings will be automatically used for each newly
created project.
Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.
Note: If you are using git or some version control system, you might want to set this folder "ignore".
Example - for git, add this directory to .gitignore
. This way, the application is not IDE-specific.
Default argument values in JavaScript functions
In javascript you can call a function (even if it has parameters) without parameters.
So you can add default values like this:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
//your code
}
and then you can call it like func();
to use default parameters.
Here's a test:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);
.gitignore and "The following untracked working tree files would be overwritten by checkout"
In my case, I was seeing this error because I am using a popular open source CMS and the directory which was causing issues was the uploads directory which the CMS writes to.
So what it was saying is that there are files which you don't have, but which you can't get from versioning.
I'm grabbing all the files from the live site to my local, then I'll check this into the repo in the hope that this fixes the issue.
Objects inside objects in javascript
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_
How to create a generic array in Java?
If you really want to wrap a generic array of fixed size you will have a method to add data to that array, hence you can initialize properly the array there doing something like this:
import java.lang.reflect.Array;
class Stack<T> {
private T[] array = null;
private final int capacity = 10; // fixed or pass it in the constructor
private int pos = 0;
public void push(T value) {
if (value == null)
throw new IllegalArgumentException("Stack does not accept nulls");
if (array == null)
array = (T[]) Array.newInstance(value.getClass(), capacity);
// put logic: e.g.
if(pos == capacity)
throw new IllegalStateException("push on full stack");
array[pos++] = value;
}
public T pop() throws IllegalStateException {
if (pos == 0)
throw new IllegalStateException("pop on empty stack");
return array[--pos];
}
}
in this case you use a java.lang.reflect.Array.newInstance to create the array, and it will not be an Object[], but a real T[].
You should not worry of it not being final, since it is managed inside your class.
Note that you need a non null object on the push() to be able to get the type to use, so I added a check on the data you push and throw an exception there.
Still this is somewhat pointless: you store data via push and it is the signature of the method that guarantees only T elements will enter. So it is more or less irrelevant that the array is Object[] or T[].
Alternative Windows shells, besides CMD.EXE?
At the moment there are three realy powerfull cmd.exe alternatives:
cmder is an enhancement off ConEmu and Clink
All have features like Copy & Paste, Window Resize per Mouse, Splitscreen, Tabs and a lot of other usefull features.
Check If only numeric values were entered in input. (jQuery)
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput
event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}