Valid to use <a> (anchor tag) without href attribute?
Yes, it is valid to use the anchor tag without a href
attribute.
If the a
element has no href
attribute, then the element represents a
placeholder for where a link might otherwise have been placed, if it
had been relevant, consisting of just the element's contents.
Yes, you can use class
and other attributes, but you can not use target
, download
, rel
, hreflang
, and type
.
The target
, download
, rel
, hreflang
, and type
attributes must be
omitted if the href attribute is not present.
As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a>
without href
. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.
Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link
).
Source: W3C HTML5 Recommendation
How to convert InputStream to FileInputStream
You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.
How to disable XDebug
Two options:
1: Add following code in the initialization Script:
if (function_exists('xdebug_disable')) {
xdebug_disable();
}
2: Add following flag to php.ini
xdebug.remote_autostart=0
xdebug.remote_enable=0
1st option is recommended.
JQuery, Spring MVC @RequestBody and JSON - making it work together
In addition to the answers here...
if you are using jquery on the client side, this worked for me:
Java:
@RequestMapping(value = "/ajax/search/sync")
public String sync(@RequestBody Foo json) {
Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):
$.ajax({
type: "post",
url: "sync", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(jsonobject), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(){
alert('failure');
}
});
How to run Gulp tasks sequentially one after the other
I was having this exact same problem and the solution turned out to be pretty easy for me. Basically change your code to the following and it should work. NOTE: the return before gulp.src made all the difference for me.
gulp.task "coffee", ->
return gulp.src("src/server/**/*.coffee")
.pipe(coffee {bare: true}).on("error",gutil.log)
.pipe(gulp.dest "bin")
gulp.task "clean",->
return gulp.src("bin", {read:false})
.pipe clean
force:true
gulp.task 'develop',['clean','coffee'], ->
console.log "run something else"
How to submit an HTML form without redirection
Okay, I'm not going to tell you a magical way of doing it because there isn't.
If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction()
you do whatever you want, (with AJAX or not) and in the ending, you add return false;
to tell the browser not to submit the form...
How to get last month/year in java?
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar
to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
Give all permissions to a user on a PostgreSQL database
All commands must be executed while connected to the right database in the right database cluster. Make sure of it.
The user needs access to the database, obviously:
GRANT CONNECT ON DATABASE my_db TO my_user;
And (at least) the USAGE
privilege on the schema:
GRANT USAGE ON SCHEMA public TO my_user;
Or grant USAGE
on all custom schemas:
DO
$$
BEGIN
-- RAISE NOTICE '%', ( -- use instead of EXECUTE to see generated commands
EXECUTE (
SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
FROM pg_namespace
WHERE nspname <> 'information_schema' -- exclude information schema and ...
AND nspname NOT LIKE 'pg\_%' -- ... system schemas
);
END
$$;
Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;
For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).
There are some other objects, the manual for GRANT
has the complete list as of Postgres 12:
privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)
But the rest is rarely needed. More details:
Consider upgrading to a current version.
How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?
I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};
- Create a package for your spring tests,
("com.example.test")
.
- Create a marker interface in the package as a context qualifier.
- Provide the marker interface reference as a parameter to basePackageClasses.
Example
IsolatedTest.java
package com.example.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackageClasses = {TestDomain.class})
@SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
public class IsolatedTest {
String expected = "Read the documentation on @ComponentScan";
String actual = "Too lazy when I can just search on Stack Overflow.";
@Test
public void testSomething() throws Exception {
assertEquals(expected, actual);
}
@ComponentScan(basePackageClasses = {TestDomain.class})
public static class Config {
public static void main(String[] args) {
SpringApplication.run(Config.class, args);
}
}
}
...
TestDomain.java
package com.example.test;
public interface TestDomain {
//noop marker
}
Best Practices for mapping one object to another
I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:
Model model = Mapper.Map<Model>(dto);
Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.
How to display 3 buttons on the same line in css
This will serve the purpose. There is no need for any divs or paragraph. If you want the spaces between them to be specified, use margin-left or margin-right in the css classes.
<div style="width:500px;">
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
</div>
How should I declare default values for instance variables in Python?
Extending bp's answer, I wanted to show you what he meant by immutable types.
First, this is okay:
>>> class TestB():
... def __init__(self, attr=1):
... self.attr = attr
...
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1
However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:
>>> class Test():
... def __init__(self, attr=[]):
... self.attr = attr
...
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>>
Note that both a
and b
have a shared attribute. This is often unwanted.
This is the Pythonic way of defining default values for instance variables, when the type is mutable:
>>> class TestC():
... def __init__(self, attr=None):
... if attr is None:
... attr = []
... self.attr = attr
...
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]
The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.
ImportError: numpy.core.multiarray failed to import
I was getting the same error and the problem was solved by updating my numpy installation from 1.7.1 to 1.12.1
pip install -U numpy
The followings were my cmd sequence when the error was occurred,
slightly different from the above:
$ python
Python 2.7.12 |Anaconda 4.2.0 (x86_64)| (default, Jul 2 2016, 17:43:17)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import cv2
>>> import numpy as np
>>> from matplotlib import pyplot as plt
How to set image in imageview in android?
The images your put into res/drawable are handled by Android. There is no need for you to get the image the way you did.
in your case you could simply call iv.setImageRessource(R.drawable.apple)
to just get the image (and not adding it to the ImageView directly), you can call Context.getRessources().getDrawable(R.drawable.apple)
to get the image
Render HTML in React Native
<WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />
This worked for me :) I have html text aboutus file.
What is difference between Implicit wait and Explicit wait in Selenium WebDriver?
Differences:
1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load.
Now, you wouldn't want to write the same code again and again. Hence, implicit wait.
However, if you want to wait for only one element, use explicit.
2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.
A table name as a variable
You can't use a table name for a variable. You'd have to do this instead:
DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from yourtable'
EXEC (@sqlCommand)
Fade In Fade Out Android Animation in Java
Figured out my own problem. The solution ended up being based in interpolators.
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);
AnimationSet animation = new AnimationSet(false); //change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
If you are using Kotlin
val fadeIn = AlphaAnimation(0f, 1f)
fadeIn.interpolator = DecelerateInterpolator() //add this
fadeIn.duration = 1000
val fadeOut = AlphaAnimation(1f, 0f)
fadeOut.interpolator = AccelerateInterpolator() //and this
fadeOut.startOffset = 1000
fadeOut.duration = 1000
val animation = AnimationSet(false) //change to false
animation.addAnimation(fadeIn)
animation.addAnimation(fadeOut)
this.setAnimation(animation)
How to make the corners of a button round?
If you want change corner radius as well as want a ripple effect in button when pressed use this:-
- Put button_background.xml in drawable
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#F7941D">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="#F7941D" />
<corners android:radius="10dp" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="#FFFFFF" />
<corners android:radius="10dp" />
</shape>
</item>
</ripple>
- Apply this background to your button
<Button
android:background="@drawable/button_background"
android:id="@+id/myBtn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="My Button" />
How to use linux command line ftp with a @ sign in my username?
A more complete answer would be it is not possible with ftp(at least the ftp program installed on centos 6).
Since you wanted an un-attended process, "pts"'s answer will work fine.
Do the unattended upload with curl instead of ftp:
curl -u user:password -T file ftp://server/dir/file
%40 doesn't appear to work.
[~]# ftp domain.com
ftp: connect: Connection refused
ftp> quit
[~]# ftp some_user%[email protected]
ftp: some_user%[email protected]: Name or service not known
ftp> quit
All I've got is to open the ftp program and use the domain and enter the user when asked. Usually, a password is required anyway, so the interactive nature probably isn't problematic.
[~]# ftp domain.com
Connected to domain.com (173.254.13.235).
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 2 of 1000 allowed.
220-Local time is now 02:47. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
Name (domain.com:user): [email protected]
331 User [email protected] OK. Password required
Password:
230 OK. Current restricted directory is /
Remote system type is UNIX.
Using binary mode to transfer files.
Multiple radio button groups in one form
in input field make name same
like
<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >
Convert canvas to PDF
Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.
//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());
//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...
//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
var blob = ctx.stream.toBlob('application/pdf');
saveAs(blob, 'example.pdf', true);
});
ctx.end();
change values in array when doing foreach
Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]
_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);
console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);
console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_
How to display Woocommerce product price by ID number on a custom page?
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
perform an action on checkbox checked or unchecked event on html form
The problem is how you've attached the listener:
<input type="checkbox" ... onchange="doalert(this.id)">
Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).
Since the window object doesn't have a checked property, this.checked
always resolves to false.
If you want this within doalert to be the element, attach the listener using addEventListener:
window.onload = function() {
var input = document.querySelector('#g01-01');
if (input) {
input.addEventListener('change', doalert, false);
}
}
Or if you wish to use an inline listener:
<input type="checkbox" ... onchange="doalert.call(this, this.id)">
Check whether a string matches a regex in JS
Use regex.test()
if all you want is a boolean result:
_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
_x000D_
_x000D_
_x000D_
...and you could remove the ()
from your regexp since you've no need for a capture.
Git merge with force overwrite
You can try "ours" option in git merge,
git merge branch -X ours
This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict
with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
How to check whether a int is not null or empty?
An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.
Example:
int x;
// Some Code...
if (x <= 0 || x > 0){
// What you want the code to do if x has a value
} else {
// What you want the code to do if x has no value
}
Disclaimer:
I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.
unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9
In Linux adding these lines to my code helped me.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=chrome_options)
driver.get("www.counterviews.online")
Sending GET request with Authentication headers using restTemplate
You can use postForObject
with an HttpEntity
. It would look like this:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject(url, entity, String.class);
In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange
or execute
methods directly. The get shorthands don't support header modification.
The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.
What is a magic number, and why is it bad?
A magic number is a direct usage of a number in the code.
For example, if you have (in Java):
public class Foo {
public void setPassword(String password) {
// don't do this
if (password.length() > 7) {
throw new InvalidArgumentException("password");
}
}
}
This should be refactored to:
public class Foo {
public static final int MAX_PASSWORD_SIZE = 7;
public void setPassword(String password) {
if (password.length() > MAX_PASSWORD_SIZE) {
throw new InvalidArgumentException("password");
}
}
}
It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.
The JDK is full of examples like in Integer
, Character
and Math
classes.
PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.
Logging POST data from $request_body
FWIW, this config worked for me:
location = /logpush.html {
if ($request_method = POST) {
access_log /var/log/nginx/push.log push_requests;
proxy_pass $scheme://127.0.0.1/logsink;
break;
}
return 200 $scheme://$host/serviceup.html;
}
#
location /logsink {
return 200;
}
How to deploy correctly when using Composer's develop / production switch?
Actually, I would highly recommend AGAINST installing dependencies on the production server.
My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.
Why?
- on shared hosting, you might not be able to get to a command line
- even if you did, PHP might be restricted there in terms of commands, memory or network access
- repository CLI tools (Git, Svn) are likely to not be installed, which would fail if your lock file has recorded a dependency to checkout a certain commit instead of downloading that commit as ZIP (you used --prefer-source, or Composer had no other way to get that version)
- if your production machine is more like a small test server (think Amazon EC2 micro instance) there is probably not even enough memory installed to execute
composer install
- while composer tries to no break things, how do you feel about ending with a partially broken production website because some random dependency could not be loaded during Composers install phase
Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.
What's the correct way to deploy this without installing the -dev dependencies?
The command to use is
composer install --no-dev
This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.
The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.
If you don't mind deploying development software components on a production server, running composer install
would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.
An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code
It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null
.
Given your statement:
img1.ImageUrl = ConfigurationManager
.AppSettings
.Get("Url")
.Replace("###", randomString)
+ Server.UrlEncode(
((System.Web.UI.MobileControls.Form)Page
.FindControl("mobileForm"))
.Title);
I'm guessing either the call to AppSettings.Get("Url")
is returning null because the value isn't found or the call to Page.FindControl("mobileForm")
is returning null because the control isn't found.
You could easily break this out into multiple statements to solve the problem:
var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
as System.Web.UI.MobileControls.Form;
if(configUrl != null && mobileFormControl != null)
{
img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}
Viewing unpushed Git commits
There is tool named unpushed that scans all Git, Mercurial and Subversion repos in specified working directory and shows list of ucommited files and unpushed commits.
Installation is simple under Linux:
$ easy_install --user unpushed
or
$ sudo easy_install unpushed
to install system-wide.
Usage is simple too:
$ unpushed ~/workspace
* /home/nailgun/workspace/unpushed uncommitted (Git)
* /home/nailgun/workspace/unpushed:master unpushed (Git)
* /home/nailgun/workspace/python:new-syntax unpushed (Git)
See unpushed --help
or official description for more information. It also has a cronjob script unpushed-notify
for on-screen notification of uncommited and unpushed changes.
Order Bars in ggplot2 bar graph
In addition to forcats::fct_infreq, mentioned by
@HolgerBrandl, there is forcats::fct_rev, which reverses the factor order.
theTable <- data.frame(
Position=
c("Zoalkeeper", "Zoalkeeper", "Defense",
"Defense", "Defense", "Striker"),
Name=c("James", "Frank","Jean",
"Steve","John", "Tim"))
p1 <- ggplot(theTable, aes(x = Position)) + geom_bar()
p2 <- ggplot(theTable, aes(x = fct_infreq(Position))) + geom_bar()
p3 <- ggplot(theTable, aes(x = fct_rev(fct_infreq(Position)))) + geom_bar()
gridExtra::grid.arrange(p1, p2, p3, nrow=3)
Convert Mercurial project to Git
I had a similar task to do, but it contained some aspects that were not sufficiently covered by the other answers here:
- I wanted to convert all (in my case: two, or in general: more than one) branches of my repo.
- I had non-ASCII and (being a Windows user) non-UTF8-encoded characters (for the curious: German umlaute) in my commit messages and file names.
I did not try fast-export and hg-fast-export, since they require that you have Python and some Mercurial Python modules on your machine, which I didn't have.
I did try hg-init with TortoiseHG, and this answer gave me a good start. But it looked like it only converts the current branch, not all at once (*). So I read the hg-init docs and this blog post and added
[git]
branch_bookmark_suffix=_bookmark
to my mercurial.ini, and did
hg bookmarks -r default master
hg bookmarks -r my_branch my_branch_bookmark
hg gexport
(Repeat the 2nd line for every branch you want to convert, and repeat it again if you should happen to do another commit before executing the 3rd line). This creates a folder git
within .hg
, which turns out to be a bare Git repo with all the exported branches. I could clone this repo and had a working copy as desired.
Or almost...
Running
git status
on my working copy showed all files with non-ASCII characters in their names as untracked files. So I continued researching and followed this advice:
git rm -rf --cached \*
git add --all
git commit
And finally the repo was ready to be pushed up to Bitbucket :-)
I also tried the Github importer as mentioned in this answer. I used Bitbucket as the source system, and Github did quite a good job, i.e. it converted all branches automatically. However, it showed '?'-characters for all non-ASCII characters in my commit messages (Web-UI and locally) and filenames (Web-UI only), and while I could fix the filenames as described above, I had no idea what to do with the commit messages, and so I'd prefer the hg-init approach. Without the encoding issue the Github importer would have been a perfect and fast solution (as long as you have a paid Github account or can tolerate that your repo is public for as long as it takes to pull it from Github to your local machine).
(*) So it looked like before I discovered that I have to bookmark all the branches I want to export. If you do and push to a bare (!) repo, like the linked answer says, you get all the branches.
Set cellpadding and cellspacing in CSS?
Simply use CSS padding rules with table data:
td {
padding: 20px;
}
And for border spacing:
table {
border-spacing: 1px;
border-collapse: collapse;
}
However, it can create problems in older version of browsers like Internet Explorer because of the diff implementation of the box model.
How to use XMLReader in PHP?
For xml formatted with attributes...
data.xml:
<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>
php code:
$reader = new XMLReader();
if (!$reader->open("data.xml")) {
die("Failed to open 'data.xml'");
}
while($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
$address = $reader->getAttribute('address');
$latitude = $reader->getAttribute('lat');
$longitude = $reader->getAttribute('lng');
}
$reader->close();
scp with port number specified
One additional hint. Place the '-P' option after the scp command, no matter whether the machine you are ssh-ing into is the second one (aka destination). Example:
scp -P 2222 /absolute_path/source-folder/some-file [email protected]:/absolute_path/destination-folder
View/edit ID3 data for MP3 files
TagLib Sharp is pretty popular.
As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.
class MusicID3Tag
{
public byte[] TAGID = new byte[3]; // 3
public byte[] Title = new byte[30]; // 30
public byte[] Artist = new byte[30]; // 30
public byte[] Album = new byte[30]; // 30
public byte[] Year = new byte[4]; // 4
public byte[] Comment = new byte[30]; // 30
public byte[] Genre = new byte[1]; // 1
}
string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";
using (FileStream fs = File.OpenRead(filePath))
{
if (fs.Length >= 128)
{
MusicID3Tag tag = new MusicID3Tag();
fs.Seek(-128, SeekOrigin.End);
fs.Read(tag.TAGID, 0, tag.TAGID.Length);
fs.Read(tag.Title, 0, tag.Title.Length);
fs.Read(tag.Artist, 0, tag.Artist.Length);
fs.Read(tag.Album, 0, tag.Album.Length);
fs.Read(tag.Year, 0, tag.Year.Length);
fs.Read(tag.Comment, 0, tag.Comment.Length);
fs.Read(tag.Genre, 0, tag.Genre.Length);
string theTAGID = Encoding.Default.GetString(tag.TAGID);
if (theTAGID.Equals("TAG"))
{
string Title = Encoding.Default.GetString(tag.Title);
string Artist = Encoding.Default.GetString(tag.Artist);
string Album = Encoding.Default.GetString(tag.Album);
string Year = Encoding.Default.GetString(tag.Year);
string Comment = Encoding.Default.GetString(tag.Comment);
string Genre = Encoding.Default.GetString(tag.Genre);
Console.WriteLine(Title);
Console.WriteLine(Artist);
Console.WriteLine(Album);
Console.WriteLine(Year);
Console.WriteLine(Comment);
Console.WriteLine(Genre);
Console.WriteLine();
}
}
}
Escape single quote character for use in an SQLite query
In C# you can use the following to replace the single quote with a double quote:
string sample = "St. Mary's";
string escapedSample = sample.Replace("'", "''");
And the output will be:
"St. Mary''s"
And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:
private static string MySqlEscape(Object usString)
{
if (usString is DBNull)
{
return "";
}
string sample = Convert.ToString(usString);
return sample.Replace("'", "''");
}
BarCode Image Generator in Java
I use
barbeque
, it's great, and supports a very wide range of different barcode formats.
See if you like
its API
.
Sample API:
public static Barcode createCode128(java.lang.String data)
throws BarcodeException
Creates a Code 128 barcode that
dynamically switches between character
sets to give the smallest possible
encoding. This will encode all
numeric characters, upper and lower
case alpha characters and control
characters from the standard ASCII
character set. The size of the barcode
created will be the smallest possible
for the given data, and use of this
"optimal" encoding will generally
give smaller barcodes than any of the
other 3 "vanilla" encodings.
Aggregate a dataframe on a given column and display another column
A base R solution is to combine the output of aggregate()
with a merge()
step. I find the formula interface to aggregate()
a little more useful than the standard interface, partly because the names on the output are nicer, so I'll use that:
The aggregate()
step is
maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
and the merge()
step is simply
merge(maxs, dat)
This gives us the desired output:
R> maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
R> merge(maxs, dat)
Group Score Info
1 1 3 c
2 2 4 d
You could, of course, stick this into a one-liner (the intermediary step was more for exposition):
merge(aggregate(Score ~ Group, data = dat, FUN = max), dat)
The main reason I used the formula interface is that it returns a data frame with the correct names
for the merge step; these are the names of the columns from the original data set dat
. We need to have the output of aggregate()
have the correct names so that merge()
knows which columns in the original and aggregated data frames match.
The standard interface gives odd names, whichever way you call it:
R> aggregate(dat$Score, list(dat$Group), max)
Group.1 x
1 1 3
2 2 4
R> with(dat, aggregate(Score, list(Group), max))
Group.1 x
1 1 3
2 2 4
We can use merge()
on those outputs, but we need to do more work telling R which columns match up.
Declare a dictionary inside a static class
You can use the static/class constructor to initialize your dictionary:
public static class ErrorCode
{
public const IDictionary<string, string> ErrorCodeDic;
public static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
Remove 'standalone="yes"' from generated XML
I don't have a high enough "reputation" to have the "privilege" to comment. ;-)
@Debasis, note that the property you've specified:
"com.sun.xml.internal.bind.xmlHeaders"
should be:
"com.sun.xml.bind.xmlHeaders" (without the "internal", which are not meant to be used by the public)
If I use the "internal" property as you did, I get a javax.xml.bind.PropertyException
How to hide the keyboard when I press return key in a UITextField?
Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.
class TextFieldWithReturn: UITextField, UITextFieldDelegate
{
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
Then all you need to do in the storyboard is set the fields to use the class:
IIS7 Settings File Locations
Also check this answer from here: Cannot manually edit applicationhost.config
The answer is simple, if not that obvious: win2008 is 64bit, notepad++
is 32bit. When you navigate to Windows\System32\inetsrv\config using
explorer you are using a 64bit program to find the file. When you open
the file using using notepad++ you are trying to open it using a 32bit
program. The confusion occurs because, rather than telling you that
this is what you are doing, windows allows you to open the file but
when you save it the file's path is transparently mapped to
Windows\SysWOW64\inetsrv\Config.
So in practice what happens is you open applicationhost.config using
notepad++, make a change, save the file; but rather than overwriting
the original you are saving a 32bit copy of it in
Windows\SysWOW64\inetsrv\Config, therefore you are not making changes
to the version that is actually used by IIS. If you navigate to the
Windows\SysWOW64\inetsrv\Config you will find the file you just saved.
How to get around this? Simple - use a 64bit text editor, such as the
normal notepad that ships with windows.
Dart/Flutter : Converting timestamp
meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.
EDIT:
From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.
import 'package:timeago/timeago.dart' as timeago;
final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));
// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());
// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());
print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes
to convert epochMS to DateTime, just use...
final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);
error: the details of the application error from being viewed remotely
Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Relative answer:
Deploying website: 500 - Internal server error
By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.
What is the intended use-case for git stash?
Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.
The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:
# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something
# stash away the current mess I made
git stash save
# some changes in the working dir
# and now add them to the last commit:
git add -u
git commit --amend
# back to work!
git stash pop
Using margin / padding to space <span> from the rest of the <p>
Overall just add display:block; to your span. You can leave your html unchanged.
Demo
You can do it with the following css:
p {
font-size:24px;
font-weight: 300;
-webkit-font-smoothing: subpixel-antialiased;
margin-top:0px;
}
p span {
font-size:16px;
font-style: italic;
margin-top:20px;
padding-left:10px;
display:inline-block;
}
Difference between matches() and find() in Java Regex
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
Fatal error: Call to undefined function sqlsrv_connect()
This helped me get to my answer. There are two php.ini
files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin
folder. When connecting to SQL through sqlsrv_connect
function, we are referring to the php.ini
file in the apache
folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
Install apk without downloading
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
Is it a good practice to use try-except-else in Python?
Just because no-one else has posted this opinion, I would say
avoid else
clauses in try/excepts
because they're unfamiliar to most people
Unlike the keywords try
, except
, and finally
, the meaning of the else
clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.
(I'm writing this answer precisely because I found a try/except/else
in my codebase and it caused a wtf moment and forced me to do some googling).
So, wherever I see code like the OP example:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
else:
# do some more processing in non-exception case
return something
I would prefer to refactor to
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
return # <1>
# do some more processing in non-exception case <2>
return something
<1> explicit return, clearly shows that, in the exception case, we are finished working
<2> as a nice minor side-effect, the code that used to be in the else
block is dedented by one level.
Assign width to half available screen width declaratively
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textD_Author"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Author : "
android:textColor="#0404B4"
android:textSize="20sp" />
<TextView
android:id="@+id/textD_Tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Edition : "
android:textColor="#0404B4"
android:textSize="20sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="@+id/btbEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Edit" />
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Delete" />
</LinearLayout>
</LinearLayout>
Switching a DIV background image with jQuery
Old post, but this would allow you to use an image sprite and adjust the repeat as well as positioning by using the shorthand for the css property (background, repeat, left top).
$.each($('.smallPreview'), function(i){
var $this = $(this);
$this.mouseenter(function(){
$this.css('background', 'url(Assets/imgs/imgBckg-Small_Over.png) no-repeat 0 0');
});
$this.mouseleave(function(){
$this.css('background', 'url(Assets/imgs/imgBckg-Small.png) no-repeat 0 0');
});
});
Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>
In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.
<select defaultValue={'DEFAULT'} >
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
Here the user is forced to pick an option!
EDIT
If this is a controlled component
In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.
function TheSelectComponent(props){
let currentValue = props.curentValue || "DEFAULT";
return(
<select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
)
}
Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes
- How do I convert my results to only hours and minutes
- The accepted answer only returns
days + hours
. Minutes are not included.
- To provide a column that has hours and minutes, as
hh:mm
or x hours y minutes
, would require additional calculations and string formatting.
- This answer shows how to get either total hours or total minutes as a float, using
timedelta
math, and is faster than using .astype('timedelta64[h]')
- Pandas Time Deltas User Guide
- Pandas Time series / date functionality User Guide
- python
timedelta
objects: See supported operations.
- The following sample data is already a
datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.
import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
Other methods
- An item of note from the podcast in Other Resources,
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
- This is also why there aren't other
.total_xx
methods.
# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
Other Resources
%%timeit
test
import pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
in python how do I convert a single digit number into a double digits string?
Branching off of Mohommad's answer:
str_years = [x for x in range(24)]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
#Or, if you're starting with ints:
int_years = [int(x) for x in str_years]
#Formatted here
form_years = ["%02d" % x for x in int_years]
print(form_years)
#['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
How do I hide an element on a click event anywhere outside of the element?
$(document).on('click', function(e) { // Hides the div by clicking any where in the screen
if ( $(e.target).closest('#suggest_input').length ) {
$(".suggest_div").show();
}else if ( ! $(e.target).closest('.suggest_container').length ) {
$('.suggest_div').hide();
}
});
Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.
this code is for hiding the div elements by clicking any where in the screen.
Before doing every thing please understand the code and copy it...
How is a tag different from a branch in Git? Which should I use, here?
If you think of your repository as a book that chronicles progress on your project...
Branches
You can think of a branch as one of those sticky bookmarks:
A brand new repository has only one of those (called master
), which automatically moves to the latest page (think commit) you've written. However, you're free to create and use more bookmarks, in order to mark other points of interest in the book, so you can return to them quickly.
Also, you can always move a particular bookmark to some other page of the book (using git-reset
, for instance); points of interest typically vary over time.
Tags
You can think of tags as chapter headings.
It may contain a title (think annotated tags) or not. A tag is similar but different to a branch, in that it marks a point of historical interest in the book. To maintain its historical aspect, once you've shared a tag (i.e. pushed it to a shared remote), you're not supposed to move it to some other place in the book.
How to set up Automapper in ASP.NET Core
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register AutoMapper.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Start Registering and Initializing AutoMapper
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
// End Registering and Initializing AutoMapper
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
Improve INSERT-per-second performance of SQLite
Use ContentProvider for inserting the bulk data in db.
The below method used for inserting bulk data in to database. This should Improve INSERT-per-second performance of SQLite.
private SQLiteDatabase database;
database = dbHelper.getWritableDatabase();
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
database.beginTransaction();
for (ContentValues value : values)
db.insert("TABLE_NAME", null, value);
database.setTransactionSuccessful();
database.endTransaction();
}
Call bulkInsert method :
App.getAppContext().getContentResolver().bulkInsert(contentUriTable,
contentValuesArray);
Link: https://www.vogella.com/tutorials/AndroidSQLite/article.html
check Using ContentProvider Section for more details
MVC pattern on Android
According to the explanation that the Xamarin team explained (on the iOS MVC "I know it seems weird, but wait a second"):
- The model (data or application logic),
- The view (user interface), and
- The controller (code behind).
I can say this:
The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).
*This is just my opinion, not from any resource or a book.
What is the difference between XML and XSD?
Take an example
<root>
<parent>
<child_one>Y</child_one>
<child_two>12</child_two>
</parent>
</root>
and design an xsd for that:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="parent">
<xs:complexType>
<xs:sequence>
<xs:element name="child_one" type="xs:string" />
<xs:element name="child_two" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
What isn't possible with XSD: would like to write it first as the list is very small
1) You can't validate a node/attribute using the value of another node/attribute.
2) This is a restriction : An element defined in XSD file must be defined with only one datatype. [in the above example, for <child_two>
appearing in another <parent>
node, datatype cannot be defined other than int.
3) You can't ignore the validation of elements and attributes, ie, if an element/attribute appears in XML, it must be well-defined in the corresponding XSD. Though usage of <xsd:any>
allows it, but it has got its own rules. Abiding which leads to the validation error. I had tried for a similar approach, and certainly wasn't successful, here is the Q&A
what are possible with XSD:
1) You can test the proper hierarchy of the XML nodes. [xsd defines which child should come under which parent, etc, abiding which will be counted as error, in above example, child_two cannot be the immediate child of root, but it is the child of "parent" tag which is in-turn a child of "root" node, there is a hierarchy..]
2) You can define Data type of the values of the nodes. [in above example child_two cannot have any-other data than number]
3) You can also define custom data_types, [example, for node <month>
, the possible data can be one of the 12 months.. so you need to define all the 12 months in a new data type writing all the 12 month names as enumeration values .. validation shows error if the input XML contains any-other value than these 12 values .. ]
4) You can put the restriction on the occurrence of the elements, using minOccurs and maxOccurs, the default values are 1 and 1.
.. and many more ...
What does "atomic" mean in programming?
Here's an example, because an example is often clearer than a long explanation. Suppose foo
is a variable of type long
. The following operation is not an atomic operation:
foo = 65465498L;
Indeed, the variable is written using two separate operations: one that writes the first 32 bits, and a second one which writes the last 32 bits. That means that another thread might read the value of foo
, and see the intermediate state.
Making the operation atomic consists in using synchronization mechanisms in order to make sure that the operation is seen, from any other thread, as a single, atomic (i.e. not splittable in parts), operation. That means that any other thread, once the operation is made atomic, will either see the value of foo
before the assignment, or after the assignment. But never the intermediate value.
A simple way of doing this is to make the variable volatile:
private volatile long foo;
Or to synchronize every access to the variable:
public synchronized void setFoo(long value) {
this.foo = value;
}
public synchronized long getFoo() {
return this.foo;
}
// no other use of foo outside of these two methods, unless also synchronized
Or to replace it with an AtomicLong
:
private AtomicLong foo;
Google Chrome Printing Page Breaks
Actually one detail is missing from the answer that is selected as accepted (from Phil Ross)....
it DOES work in Chrome, and the solution is really silly!!
Both the parent and the element onto which you want to control page-breaking must be declared as:
position: relative
check out this fiddle:
http://jsfiddle.net/petersphilo/QCvA5/5/show/
This is true for:
page-break-before
page-break-after
page-break-inside
However, controlling page-break-inside in Safari does not work (in 5.1.7, at least)
i hope this helps!!!
PS: The question below brought up that fact that recent versions of Chrome no longer respect this, even with the position: relative; trick.
However, they do seem to respect:
-webkit-region-break-inside: avoid;
see this fiddle:
http://jsfiddle.net/petersphilo/QCvA5/23/show
so i guess we have to add that now...
Hope this helps!
Convert binary to ASCII and vice versa
This is a spruced up version of J.F. Sebastian's. Thanks for the snippets though J.F. Sebastian.
import binascii, sys
def goodbye():
sys.exit("\n"+"*"*43+"\n\nGood Bye! Come use again!\n\n"+"*"*43+"")
while __name__=='__main__':
print "[A]scii to Binary, [B]inary to Ascii, or [E]xit:"
var1=raw_input('>>> ')
if var1=='a':
string=raw_input('String to convert:\n>>> ')
convert=bin(int(binascii.hexlify(string), 16))
i=2
truebin=[]
while i!=len(convert):
truebin.append(convert[i])
i=i+1
convert=''.join(truebin)
print '\n'+'*'*84+'\n\n'+convert+'\n\n'+'*'*84+'\n'
if var1=='b':
binary=raw_input('Binary to convert:\n>>> ')
n = int(binary, 2)
done=binascii.unhexlify('%x' % n)
print '\n'+'*'*84+'\n\n'+done+'\n\n'+'*'*84+'\n'
if var1=='e':
aus=raw_input('Are you sure? (y/n)\n>>> ')
if aus=='y':
goodbye()
How to set JAVA_HOME in Linux for all users
This is a very simple script to solve the problem
export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`
And for testing:
echo $JAVA_HOME
Detect when browser receives file download
i use the following to download blobs and revoke the object-url after the download. it works in chrome and firefox!
function download(blob){
var url = URL.createObjectURL(blob);
console.log('create ' + url);
window.addEventListener('focus', window_focus, false);
function window_focus(){
window.removeEventListener('focus', window_focus, false);
URL.revokeObjectURL(url);
console.log('revoke ' + url);
}
location.href = url;
}
after the file download dialog is closed, the window gets her focus back so the focus event is triggered.
Can I delete data from the iOS DeviceSupport directory?
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
What's the "average" requests per second for a production web application?
You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.
Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.
There was an excellent video (I think it might have been on ted.com? I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.
No mapping found for HTTP request with URI Spring MVC
With the web.xml configured they way you have in the question, in particular:
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
ALL requests being made to your web app will be directed to the DispatcherServlet
. This includes requests like /tasklist/
, /tasklist/some-thing.html
, /tasklist/WEB-INF/views/index.jsp
.
Because of this, when your controller returns a view that points to a .jsp
, instead of allowing your server container to service the request, the DispatcherServlet
jumps in and starts looking for a controller that can service this request, it doesn't find any and hence the 404
.
The simplest way to solve is to have your servlet url mapping as follows:
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Notice the missing *
. This tells the container that any request that does not have a path info
in it (urls without a .xxx at the end), should be sent to the DispatcherServlet
. With this configuration, when a xxx.jsp
request is received, the DispatcherServlet
is not consulted, and your servlet container's default servlet will service the request and present the jsp as expected.
Hope this helps, I realize your earlier comments state that the problem has been resolved, but the solution CAN NOT be just adding method=RequestMethod.GET
to the RequestMethod
.
Why does JSON.parse fail with the empty string?
JSON.parse
expects valid notation inside a string, whether that be object {}
, array []
, string ""
or number types (int, float, doubles).
If there is potential for what is parsing to be an empty string then the developer should check for it.
If it was built into the function it would add extra cycles, since built in functions are expected to be extremely performant, it makes sense to not program them for the race case.
Android List View Drag and Drop sort
Am adding this answer for the purpose of those who google about this..
There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this
You can find it here also the sample code is available here.
What this code basically does is that it creates a dynamic listview
by the extension of listview
that supports cell dragging and swapping. So that you can use the DynamicListView
instead of your basic ListView
and that's it you have implemented a ListView with Drag and Drop.
How do you strip a character out of a column in SQL Server?
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
Using PropertyInfo to find out the property type
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
Where are static variables stored in C and C++?
In fact, a variable is tuple (storage, scope, type, address, value):
storage : where is it stored, for example data, stack, heap...
scope : who can see us, for example global, local...
type : what is our type, for example int, int*...
address : where are we located
value : what is our value
Local scope could mean local to either the translational unit (source file), the function or the block depending on where its defined. To make variable visible to more than one function, it definitely has to be in either DATA or the BSS area (depending on whether its initialized explicitly or not, respectively). Its then scoped accordingly to either all function(s) or function(s) within source file.
React - how to pass state to another component
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
Parse HTML table to Python list?
Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.
import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest
Only downside is that read_html()
doesn't preserve hyperlinks.
Check if a number has a decimal place/is a whole number
You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point.
If result is equal to zero then the number is a whole number.
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
Make a URL-encoded POST request using `http.NewRequest(...)`
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
Installing Python 3 on RHEL
Along with Python 2.7 and 3.3, Red Hat Software Collections now includes Python 3.4 - all work on both RHEL 6 and 7.
RHSCL 2.0 docs are at https://access.redhat.com/documentation/en-US/Red_Hat_Software_Collections/
Plus lot of articles at developerblog.redhat.com.
edit
Follow these instructions to install Python 3.4 on RHEL 6/7 or CentOS 6/7:
# 1. Install the Software Collections tools:
yum install scl-utils
# 2. Download a package with repository for your system.
# (See the Yum Repositories on external link. For RHEL/CentOS 6:)
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-6-x86_64/download/rhscl-rh-python34-epel-6-x86_64.noarch.rpm
# or for RHEL/CentOS 7
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-7-x86_64/download/rhscl-rh-python34-epel-7-x86_64.noarch.rpm
# 3. Install the repo package (on RHEL you will need to enable optional channel first):
yum install rhscl-rh-python34-*.noarch.rpm
# 4. Install the collection:
yum install rh-python34
# 5. Start using software collections:
scl enable rh-python34 bash
java.lang.UnsupportedClassVersionError: Bad version number in .class file?
Did you compile with Eclipse? It uses a different compiler (not javac). That should not result in this error (if everything is configured properly), but you can try to compile it with javac instead.
If that fixed the problem, try to see if Eclipse has some incorrect compiler settings. Specifically have it target Java 5.
How to get the date from jQuery UI datepicker
You can retrieve the date by using the getDate function:
$("#datepicker").datepicker( 'getDate' );
The value is returned as a JavaScript Date object.
If you want to use this value when the user selects a date, you can use the onSelect event:
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
}
});
The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.
See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.
How to install Intellij IDEA on Ubuntu?
try simple way to install intellij idea
Install IntelliJ on Ubuntu using Ubuntu Make
You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:
- sudo apt install ubuntu-make
Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:
- umake ide idea
To install the IntelliJ IDEA Ultimate edition, use the command below:
- umake ide idea-ultimate
To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:
- umake -r ide idea
- umake -r ide idea-ultimate
you may visit for more option.
https://itsfoss.com/install-intellij-ubuntu-linux/
load json into variable
<input class="pull-right" id="currSpecID" name="currSpecID" value="">
$.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$("#currSpecID").val(data);
});
Terminating a script in PowerShell
May be it is better to use "trap". A PowerShell trap specifies a codeblock to run when a terminating or error occurs. Type
Get-Help about_trap
to learn more about the trap statement.
Jersey stopped working with InjectionManagerFactory not found
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
Changing Underline color
In practice, it is possible, if you use span
element instead of font
:
<style>
u { color: black; }
.red { color: red }
</style>
<u><span class='red'><br>$username</span></u>
See jsfiddle. Appears to work on Chrome, Safari, Firefox, IE, Opera (tested on Win 7 with newest versions).
The code in the question should work, too, but it does not work for some reason on WebKit browsers (Chrome, Safari).
By the CSS spec: “The color(s) required for the text decoration must be derived from the 'color' property value of the element on which 'text-decoration' is set. The color of decorations must remain the same even if descendant elements have different 'color' values.”
What is a Python equivalent of PHP's var_dump()?
To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do
from pprint import pprint
pprint(globals())
pprint(locals())
If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.
How can I add comments in MySQL?
"A comment for a column can be specified with the COMMENT
option. The comment is displayed by the SHOW CREATE TABLE
and SHOW FULL COLUMNS
statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"
As an example
--
-- Table structure for table 'accesslog'
--
CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry',
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;
Convert Uri to String and String to Uri
This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?
String ordinal(int num)
{
String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int m = num % 100;
return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
}
Make a link in the Android browser start up my app?
You may want to consider a library to handle the deep link to your app:
https://github.com/airbnb/DeepLinkDispatch
You can add the intent filter on an annotated Activity like people suggested above. It will handle the routing and parsing of parameters for all of your deep links. For example, your MainActivity might have something like this:
@DeepLink("somePath/{useful_info_for_anton_app}")
public class MainActivity extends Activity {
...
}
It can also handle query parameters as well.
Resizing image in Java
If you have an java.awt.Image
, rezising it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Ovbiously, replace newWidth
and newHeight
with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
See the Javadoc for more info.
Why call super() in a constructor?
There is an implicit call to super()
with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super()
with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super()
with argument(s).
An example, where the explicit call to super()
gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
How can I declare optional function parameters in JavaScript?
Update
With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.
Old answer
Default parameters in JavaScript can be implemented in mainly two ways:
function myfunc(a, b)
{
// use this if you specifically want to know if b was passed
if (b === undefined) {
// b was not passed
}
// use this if you know that a truthy value comparison will be enough
if (b) {
// b was passed and has truthy value
} else {
// b was not passed or has falsy value
}
// use this to set b to a default value (using truthy comparison)
b = b || "default value";
}
The expression b || "default value"
evaluates the value AND existence of b
and returns the value of "default value"
if b
either doesn't exist or is falsy.
Alternative declaration:
function myfunc(a)
{
var b;
// use this to determine whether b was passed or not
if (arguments.length == 1) {
// b was not passed
} else {
b = arguments[1]; // take second argument
}
}
The special "array" arguments
is available inside the function; it contains all the arguments, starting from index 0
to N - 1
(where N
is the number of arguments passed).
This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!
Further considerations
Although undefined
is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:
b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
Getting rid of all the rounded corners in Twitter Bootstrap
code,
kbd,
pre,
.img-rounded,
.img-thumbnail,
.img-circle,
.form-control,
.btn,
.btn-link,
.dropdown-menu,
.list-group-item,
.input-group-addon,
.input-group-btn,
.nav-tabs a,
.nav-pills a,
.navbar,
.navbar-toggle,
.icon-bar,
.breadcrumb,
.pagination,
.pager *,
.label,
.badge,
.jumbotron,
.thumbnail,
.alert,
.progress,
.panel,
.well,
.modal-content,
.tooltip-inner,
.popover,
.popover-title,
.carousel-indicators li {
border-radius:0 !important;
}
Fastest way to tell if two files have the same contents in Unix/Linux?
Try also to use the cksum command:
chk1=`cksum <file1> | awk -F" " '{print $1}'`
chk2=`cksum <file2> | awk -F" " '{print $1}'`
if [ $chk1 -eq $chk2 ]
then
echo "File is identical"
else
echo "File is not identical"
fi
The cksum command will output the byte count of a file. See 'man cksum'.
How do I check if an integer is even or odd?
One more solution to the problem
(children are welcome to vote)
bool isEven(unsigned int x)
{
unsigned int half1 = 0, half2 = 0;
while (x)
{
if (x) { half1++; x--; }
if (x) { half2++; x--; }
}
return half1 == half2;
}
HTTP Request in Swift with POST method
@IBAction func btn_LogIn(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!)
request.HTTPMethod = "POST"
let postString = "email: [email protected] & password: testtest"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
guard error == nil && data != nil else{
print("error")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
Parse v. TryParse
For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.
if (!Int32.TryParse(txt,out tmpint)) {
tmpint = 0;
}
and:
try {
tmpint = Convert.ToInt32(txt);
} catch (Exception) {
tmpint = 0;
}
For c#, the best option is to use tryparse because try&Catch alternative thrown the exception
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.
Python 3 Float Decimal Points/Precision
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!
Is there a way to break a list into columns?
If you are looking for a solution that works in IE as well, you could float the list elements to the left. However, this will result in a list that snakes around, like this:
item 1 | item 2 | item 3
item 4 | item 5
Instead of neat columns, like:
item 1 | item 4
item 2 |
item 3 |
The code to do that would be:
ul li {
width:10em;
float:left;
}
You could add a border-bottom to the li
s to make the flow of the items from left to right more apparent.
How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?
Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.
I've added some CSS to the demo below to change the button's font color to red when its aria-expanded
is set to true
_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_
Are there such things as variables within an Excel formula?
Yes. But not directly.
Simpler way
- You could post Vlookup() in one cell and use its address in where required. - This is perhaps the only direct way of using variables in Excel.
OR
- You could define Vlookup(reference)-10 as a wrapper function from within VBE Macros. Press Alt+f12 and use that function
How to run a task when variable is undefined in ansible?
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
WinError 2 The system cannot find the file specified (Python)
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
plot is not defined
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
How to create a foreign key in phpmyadmin
The key must be indexed to apply foreign key constraint. To do that follow the steps.
- Open table structure. (2nd tab)
- See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
- Open relation view and add foreign key constraint.
You will be able to assign DOCTOR_ID as foreign now.
Sites not accepting wget user agent header
You need to set both the user-agent and the referer:
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip
How to create empty constructor for data class in Kotlin Android
Along with @miensol answer, let me add some details:
If you want a Java-visible empty constructor using data classes, you need to define it explicitely.
Using default values + constructor specifier is quite easy:
data class Activity(
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
) {
constructor() : this(title = "") // this constructor is an explicit
// "empty" constructor, as seen by Java.
}
This means that with this trick you can now serialize/deserialize this object with the standard Java serializers (Jackson, Gson etc).
Labels for radio buttons in rails form
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
How can I convert an Integer to localized month name in Java?
Try to use this a very simple way and call it like your own func
public static String convertnumtocharmonths(int m){
String charname=null;
if(m==1){
charname="Jan";
}
if(m==2){
charname="Fev";
}
if(m==3){
charname="Mar";
}
if(m==4){
charname="Avr";
}
if(m==5){
charname="Mai";
}
if(m==6){
charname="Jun";
}
if(m==7){
charname="Jul";
}
if(m==8){
charname="Aou";
}
if(m==9){
charname="Sep";
}
if(m==10){
charname="Oct";
}
if(m==11){
charname="Nov";
}
if(m==12){
charname="Dec";
}
return charname;
}
How to call a method after a delay in Android
Below one works when you get,
java.lang.RuntimeException: Can't create handler inside thread that
has not called Looper.prepare()
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
Programmatically check Play Store for app updates
You can get current Playstore Version using JSoup
with some modification like below:
@Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select(".hAyfc .htlgb")
.get(7)
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
Log.d("update", "playstore version " + onlineVersion);
}
answer of @Tarun is not working anymore.
How to set up subdomains on IIS 7
If your computer can't find the IP address associated with SUBDOMAIN1.example.COM
, it will not find the site.
You need to either change your hosts
file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).
Combine Date and Time columns using python pandas
First make sure to have the right data types:
df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_timedelta(df["Time"])
Then you easily combine them:
df["DateTime"] = df["Date"] + df["Time"]
Editing dictionary values in a foreach loop
You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:
Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...
int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();
foreach (string key in colStates.Keys)
{
double Percent = colStates[key] / colStates.Count;
if (Percent < 0.05)
{
OtherCount += colStates[key];
notRelevantKeys.Add(key);
}
}
foreach (string key in notRelevantKeys)
{
colStates[key] = 0;
}
colStates.Add("Other", OtherCount);
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to Pass Parameters to Activator.CreateInstance<T>()
Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.
There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.
Details about the issue on this article.
Graph is taken from the article and represents time taken in ms per 1000 calls.
How to change the new TabLayout indicator color and height
To change indicator color and height programmatically you can use reflection. for example for indicator color use code below:
try {
Field field = TabLayout.class.getDeclaredField("mTabStrip");
field.setAccessible(true);
Object ob = field.get(tabLayout);
Class<?> c = Class.forName("android.support.design.widget.TabLayout$SlidingTabStrip");
Method method = c.getDeclaredMethod("setSelectedIndicatorColor", int.class);
method.setAccessible(true);
method.invoke(ob, Color.RED);//now its ok
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
and to change indicator height use "setSelectedIndicatorHeight" instead of "setSelectedIndicatorColor" then invoke it by your desired height
How do I set cell value to Date and apply default Excel date format?
This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.
import org.apache.poi.xssf.usermodel.*; //import needed
XSSFWorkbook wb = new XSSFWorkbook (); // Create workbook
XSSFSheet sheet = wb.createSheet(); // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet
//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy"));
//2. Apply the Date cell style to a cell
//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
How to add hyperlink in JLabel?
You might try using a JEditorPane instead of a JLabel. This understands basic HTML and will send a HyperlinkEvent event to the HyperlinkListener you register with the JEditPane.
How do I make an image smaller with CSS?
Here's what I've done:
.resize {
width: 400px;
height: auto;
}
.resize {
width: 300px;
height: auto;
}
<img class="resize" src="example.jpg"/>
This will keep the image aspect ratio the same.
Specify sudo password for Ansible
My hack to automate this was to use an environment variable and access it via --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
.
Export an env var, but avoid bash/shell history (prepend with a space, or other methods). E.g.:
export ANSIBLE_BECOME_PASS='<your password>'
Lookup the env var while passing the extra ansible_become_pass
variable into the ansible-playbook
, E.g.:
ansible-playbook playbook.yml -i inventories/dev/hosts.yml -u user --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
Good alternate answers:
yii2 redirect in controller action does not work?
Redirects the browser to the specified URL.
This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:
return Yii::$app->getResponse()->redirect($url);
In other places, if you want to send out the "Location" header immediately, you should use the following code:
Yii::$app->getResponse()->redirect($url)->send();
return;
How to implement HorizontalScrollView like Gallery?
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
:last-child not working as expected?
I encounter similar situation. I would like to have background of the last .item
to be yellow in the elements that look like...
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
...
<div class="item">item x</div>
<div class="other">I'm here for some reasons</div>
</div>
I use nth-last-child(2)
to achieve it.
.item:nth-last-child(2) {
background-color: yellow;
}
It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect.
I found this helpful trick from CSS Trick
How to preventDefault on anchor tags?
So reading through these answers, @Chris still has the most "correct" answer, I suppose, but it has one problem, it doesn't show the "pointer"....
So here are two ways to solve this problem without needing to add a cursor:pointer style:
Use javascript:void(0)
instead of #
:
<a href="javascript:void(0)" ng-click="doSomething()">Do Something</a>
Use $event.preventDefault()
in the ng-click
directive (so you don't junk up your controller with DOM-related references):
<a href="#dontGoHere" ng-click="doSomething(); $event.preventDefault()">Do Something</a>
Personally I prefer the former over the latter. javascript:void(0)
has other benefits that are discussed here. There is also discussion of "unobtrusive JavaScript" in that link which is frighteningly recent, and doesn't necessarily directly apply to an angular application.
Compiling and Running Java Code in Sublime Text 2
compile and running as per documentation of sublime text 2 nd 3
step- 1:
set environment variables for java as u know already or refer somewhere
strp-2:
open new document and copy paste code below
{
"cmd": ["javac", "$file_name", "&&", "java", "$file_base_name"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.java",
"shell":true }
step-3:
save the document as userjavaC.sublime-build in directory C:\Users\myLapi\AppData\Roaming\Sublime Text 3\Packages\User
step-4:
after done select as tools->build systems->userjavaC
to both compile and run press ctrl+b
iOS 7 status bar overlapping UI
In MainViewController.m inside: - (void)viewWillAppear:(BOOL)animated
add this:
//Lower screen 20px on ios 7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect viewBounds = [self.webView bounds];
viewBounds.origin.y = 18;
viewBounds.size.height = viewBounds.size.height - 18;
self.webView.frame = viewBounds;
}
so the end function will look like this:
- (void)viewWillAppear:(BOOL)animated
{
// View defaults to full size. If you want to customize the view's size, or its subviews (e.g. webView),
// you can do so here.
//Lower screen 20px on ios 7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect viewBounds = [self.webView bounds];
viewBounds.origin.y = 18;
viewBounds.size.height = viewBounds.size.height - 18;
self.webView.frame = viewBounds;
}
[super viewWillAppear:animated];
}
How to declare an ArrayList with values?
In Java 9+ you can do:
var x = List.of("xyz", "abc");
// 'var' works only for local variables
Java 8 using Stream
:
Stream.of("xyz", "abc").collect(Collectors.toList());
And of course, you can create a new object using the constructor that accepts a Collection
:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList
class:
Why does my sorting loop seem to append an element where it shouldn't?
Starting from Java 8, you can also use parallelSort
which is useful if you have arrays containing a lot of elements.
Example:
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "b", "y" };
Arrays.parallelSort(strings);
System.out.println(Arrays.toString(strings)); // [a, b, c, x, y]
}
If you want to ignore the case, you can use:
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "B", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(Arrays.toString(strings)); // [a, B, c, x, y]
}
otherwise B
will be before a
.
If you want to ignore the trailing spaces during the comparison, you can use trim()
:
public static void main(String[] args) {
String[] strings = { "x", " a", "c ", " b", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.trim().compareTo(o2.trim());
}
});
System.out.println(Arrays.toString(strings)); // [ a, b, c , x, y]
}
See:
Unix - copy contents of one directory to another
Quite simple, with a *
wildcard.
cp -r Folder1/* Folder2/
But according to your example recursion is not needed so the following will suffice:
cp Folder1/* Folder2/
EDIT:
Or skip the mkdir Folder2
part and just run:
cp -r Folder1 Folder2
How can I de-install a Perl module installed via `cpan`?
Update 2013: This code is obsolescent. Upvote bsb's late-coming answer instead.
I don't need to uninstall modules often, but the .packlist
file based approach has never failed me so far.
use 5.010;
use ExtUtils::Installed qw();
use ExtUtils::Packlist qw();
die "Usage: $0 Module::Name Module::Name\n" unless @ARGV;
for my $mod (@ARGV) {
my $inst = ExtUtils::Installed->new;
foreach my $item (sort($inst->files($mod))) {
say "removing $item";
unlink $item or warn "could not remove $item: $!\n";
}
my $packfile = $inst->packlist($mod)->packlist_file;
print "removing $packfile\n";
unlink $packfile or warn "could not remove $packfile: $!\n";
}
Get user profile picture by Id
You can use AngularJs for this, Its two -way data binding feature will get solution with minimum effort and less code.
<div>
<input type="text" name="" ng-model="fbid"><br/>
<img src="https://graph.facebook.com/{{fbid}}/picture?type=normal">
</div>
I hope this answers your query.Note: You can use other library as well.