How to store(bitmap image) and retrieve image from sqlite database in android?
If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.
on button click write this
Intent in = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
in.putExtra("crop", "true");
in.putExtra("outputX", 100);
in.putExtra("outputY", 100);
in.putExtra("scale", true);
in.putExtra("return-data", true);
startActivityForResult(in, 1);
then do this in your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bmp);
btnadd.requestFocus();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
}
}
Non-alphanumeric list order from os.listdir()
I found "sort" does not always do what I expected. eg, I have a directory as below, and the "sort" give me a very strange result:
>>> os.listdir(pathon)
['2', '3', '4', '5', '403', '404', '407', '408', '410', '411', '412', '413', '414', '415', '416', '472']
>>> sorted([ f for f in os.listdir(pathon)])
['2', '3', '4', '403', '404', '407', '408', '410', '411', '412', '413', '414', '415', '416', '472', '5']
It seems it compares the first character first, if that is the biggest, it would be the last one.
Get WooCommerce product categories from WordPress
Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
with:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}
or if you also wish a counter for each subcategory, replace with this:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
Mockito - difference between doReturn() and when()
Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...
PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
So it will return false when the method is called in same test case and then it will return false again and lastly true.
Disabling browser caching for all browsers from ASP.NET
This is what we use in ASP.NET:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
It stops caching in Firefox and IE, but we haven't tried other browsers. The following response headers are added by these statements:
Cache-Control: no-cache, no-store
Pragma: no-cache
How do I check if string contains substring?
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf()
returns -1
if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
how to cancel/abort ajax request in axios
Axios does not support canceling requests at the moment. Please see this issue for details.
UPDATE: Cancellation support was added in axios v0.15.
EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.
Example:
const cancelTokenSource = axios.CancelToken.source();
axios.get('/user/12345', {
cancelToken: cancelTokenSource.token
});
// Cancel request
cancelTokenSource.cancel();
Detect if a NumPy array contains at least one non-numeric value?
If infinity is a possible value, I would use numpy.isfinite
numpy.isfinite(myarray).all()
If the above evaluates to True
, then myarray
contains no, numpy.nan
, numpy.inf
or -numpy.inf
values.
numpy.nan
will be OK with numpy.inf
values, for example:
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
Random alpha-numeric string in JavaScript?
Nice and simple, and not limited to a certain number of characters:
let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
Custom method names in ASP.NET Web API
I am days into the MVC4 world.
For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:
http://localhost:9000/api/SitesAPI/Disposition/0
With different values for the last parameter to get record with different dispositions.
What Finally worked for me was:
The method in the SitesAPIController:
// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
Site site = db.Sites.Where(s => s.Disposition == disposition).First();
return site;
}
And this in the WebApiConfig.cs
// this was already there
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this i added
config.Routes.MapHttpRoute(
name: "Action",
routeTemplate: "api/{controller}/{action}/{disposition}"
);
For as long as I was naming the {disposition} as {id} i was encountering:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}
When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.
Feel free to edit this answer to make it more accurate/explanatory.
How to completely remove node.js from Windows
I came here because the Remove button was not available from Add/Remove programs. It was saying "Node.js cannot be removed".
This worked:
- Got the .msi of my installed Node version. Ran it to repair the installation just in case.
- Opened the Administrator command prompt and ran
msiexec /uninstall <node.msi>
.
Getting file names without extensions
Below is my code to get a picture to load into a PictureBox and Display a Picture name in to a TextBox without Extension.
private void browse_btn_Click(object sender, EventArgs e)
{
OpenFileDialog Open = new OpenFileDialog();
Open.Filter = "image files|*.jpg;*.png;*.gif;*.icon;.*;";
if (Open.ShowDialog() == DialogResult.OK)
{
imageLocation = Open.FileName.ToString();
string picTureName = null;
picTureName = Path.ChangeExtension(Path.GetFileName(imageLocation), null);
pictureBox_Gift.ImageLocation = imageLocation;
GiftName_txt.Text = picTureName.ToString();
Savebtn.Enabled = true;
}
}
Adding headers to requests module
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
How to determine the content size of a UIWebView?
If your HTML contains heavy HTML-contents like iframe's (i.e. facebook-, twitter, instagram-embeds) the real solution is much more difficult, first wrap your HTML:
[htmlContent appendFormat:@"<html>", [[LocalizationStore instance] currentTextDir], [[LocalizationStore instance] currentLang]];
[htmlContent appendFormat:@"<head>"];
[htmlContent appendString:@"<script type=\"text/javascript\">"];
[htmlContent appendFormat:@" var lastHeight = 0;"];
[htmlContent appendFormat:@" function updateHeight() { var h = document.getElementById('content').offsetHeight; if (lastHeight != h) { lastHeight = h; window.location.href = \"x-update-webview-height://\" + h } }"];
[htmlContent appendFormat:@" window.onload = function() {"];
[htmlContent appendFormat:@" setTimeout(updateHeight, 1000);"];
[htmlContent appendFormat:@" setTimeout(updateHeight, 3000);"];
[htmlContent appendFormat:@" if (window.intervalId) { clearInterval(window.intervalId); }"];
[htmlContent appendFormat:@" window.intervalId = setInterval(updateHeight, 5000);"];
[htmlContent appendFormat:@" setTimeout(function(){ clearInterval(window.intervalId); window.intervalId = null; }, 30000);"];
[htmlContent appendFormat:@" };"];
[htmlContent appendFormat:@"</script>"];
[htmlContent appendFormat:@"..."]; // Rest of your HTML <head>-section
[htmlContent appendFormat:@"</head>"];
[htmlContent appendFormat:@"<body>"];
[htmlContent appendFormat:@"<div id=\"content\">"]; // !important https://stackoverflow.com/a/8031442/1046909
[htmlContent appendFormat:@"..."]; // Your HTML-content
[htmlContent appendFormat:@"</div>"]; // </div id="content">
[htmlContent appendFormat:@"</body>"];
[htmlContent appendFormat:@"</html>"];
Then add handling x-update-webview-height-scheme into your shouldStartLoadWithRequest:
if (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeOther) {
// Handling Custom URL Scheme
if([[[request URL] scheme] isEqualToString:@"x-update-webview-height"]) {
NSInteger currentWebViewHeight = [[[request URL] host] intValue];
if (_lastWebViewHeight != currentWebViewHeight) {
_lastWebViewHeight = currentWebViewHeight; // class property
_realWebViewHeight = currentWebViewHeight; // class property
[self layoutSubviews];
}
return NO;
}
...
And finally add the following code inside your layoutSubviews:
...
NSInteger webViewHeight = 0;
if (_realWebViewHeight > 0) {
webViewHeight = _realWebViewHeight;
_realWebViewHeight = 0;
} else {
webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] integerValue];
}
upateWebViewHeightTheWayYorLike(webViewHeight);// Now your have real WebViewHeight so you can update your webview height you like.
...
P.S. You can implement time delaying (SetTimeout and setInterval) inside your ObjectiveC/Swift-code - it's up to you.
P.S.S. Important info about UIWebView and Facebook Embeds: Embedded Facebook post does not shows properly in UIWebView
Use "ENTER" key on softkeyboard instead of clicking button
To avoid the focus advancing to the next editable field (if you have one) you might want to ignore the key-down events, but handle key-up events. I also prefer to filter first on the keyCode, assuming that it would be marginally more efficient. By the way, remember that returning true means that you have handled the event, so no other listener will. Anyway, here is my version.
ETFind.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
|| keyCode == KeyEvent.KEYCODE_ENTER) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
// do nothing yet
} else if (event.getAction() == KeyEvent.ACTION_UP) {
findForward();
} // is there any other option here?...
// Regardless of what we did above,
// we do not want to propagate the Enter key up
// since it was our task to handle it.
return true;
} else {
// it is not an Enter key - let others handle the event
return false;
}
}
});
LPCSTR, LPCTSTR and LPTSTR
To answer the second part of your question, you need to do things like
LV_DISPINFO dispinfo;
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);
because MS's LVITEM
struct has an LPTSTR
, i.e. a mutable T-string pointer, not an LPCTSTR
. What you are doing is
1) convert string
(a CString
at a guess) into an LPCTSTR
(which in practise means getting the address of its character buffer as a read-only pointer)
2) convert that read-only pointer into a writeable pointer by casting away its const
-ness.
It depends what dispinfo
is used for whether or not there is a chance that your ListView
call will end up trying to write through that pszText
. If it does, this is a potentially very bad thing: after all you were given a read-only pointer and then decided to treat it as writeable: maybe there is a reason it was read-only!
If it is a CString
you are working with you have the option to use string.GetBuffer()
-- that deliberately gives you a writeable LPTSTR
. You then have to remember to call ReleaseBuffer()
if the string does get changed. Or you can allocate a local temporary buffer and copy the string into there.
99% of the time this will be unnecessary and treating the LPCTSTR
as an LPTSTR
will work... but one day, when you least expect it...
How to create an 2D ArrayList in java?
I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList
.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList
Rounding a number to the nearest 5 or 10 or X
For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)
Multiples of 5 or x can be done simply by dividing before and multiplying after the round.
If you want to round and keep decimal places, Math.round(n, d) would work.
Python __call__ special method practical example
Yes, when you know you're dealing with objects, it's perfectly possible (and in many cases advisable) to use an explicit method call. However, sometimes you deal with code that expects callable objects - typically functions, but thanks to __call__
you can build more complex objects, with instance data and more methods to delegate repetitive tasks, etc. that are still callable.
Also, sometimes you're using both objects for complex tasks (where it makes sense to write a dedicated class) and objects for simple tasks (that already exist in functions, or are more easily written as functions). To have a common interface, you either have to write tiny classes wrapping those functions with the expected interface, or you keep the functions functions and make the more complex objects callable. Let's take threads as example. The Thread
objects from the standard libary module threading
want a callable as target
argument (i.e. as action to be done in the new thread). With a callable object, you are not restricted to functions, you can pass other objects as well, such as a relatively complex worker that gets tasks to do from other threads and executes them sequentially:
class Worker(object):
def __init__(self, *args, **kwargs):
self.queue = queue.Queue()
self.args = args
self.kwargs = kwargs
def add_task(self, task):
self.queue.put(task)
def __call__(self):
while True:
next_action = self.queue.get()
success = next_action(*self.args, **self.kwargs)
if not success:
self.add_task(next_action)
This is just an example off the top of my head, but I think it is already complex enough to warrant the class. Doing this only with functions is hard, at least it requires returning two functions and that's slowly getting complex. One could rename __call__
to something else and pass a bound method, but that makes the code creating the thread slightly less obvious, and doesn't add any value.
Git push rejected "non-fast-forward"
It looks, that someone pushed new commits between your last git fetch
and git push
. In this case you need to repeat your steps and rebase my_feature_branch
one more time.
git fetch
git rebase feature/my_feature_branch
git push origin feature/my_feature_branch
After the git fetch
I recommend to examine situation with gitk --all
.
jQuery disable a link
html link example:
<!-- boostrap button + fontawesome icon -->
<a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
<i class="icon-file-text icon-large"></i>
Download Document
</a>
use this in jQuery
$('#BT_Download').attr('disabled',true);
add this to css :
a[disabled="disabled"] {
pointer-events: none;
}
How to embed new Youtube's live video permanent URL?
The issue is two-fold:
- WordPress reformats the YouTube link
- You need a custom embed link to support a live stream embed
As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.
You will need to use the following URL format for the embed:
<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>
The &autoplay=1
is not necessary, but I like to include it. Change CHANNEL
to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:
<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>
Let me know if that worked for you!
How to pass multiple parameters in a querystring
Query_string
(Following is the text of the linked section of the Wikipedia entry.)
Structure
A typical URL containing a query string is as follows:
http://server/path/program?query_string
When a server receives a request for such a page, it runs a program (if configured to do so), passing the query_string unchanged to the program. The question mark is used as a separator and is not part of the query string.
A link in a web page may have a URL that contains a query string, however, HTML defines three ways a web browser can generate the query string:
- a web form via the ... element
- a server-side image map via the ?ismap? attribute on the element with a construction
- an indexed search via the now deprecated element
Web forms
The main use of query strings is to contain the content of an HTML form, also known as web form. In particular, when a form containing the fields field1, field2, field3 is submitted, the content of the fields is encoded as a query string as follows:
field1=value1&field2=value2&field3=value3...
- The query string is composed of a series of field-value pairs.
- Within each pair, the field name and value are separated by an equals sign. The equals sign may be omitted if the value is an empty string.
- The series of pairs is separated by the ampersand, '&' (or semicolon, ';' for URLs embedded in HTML and not generated by a ...; see below).
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field:
field1=value1&field1=value2&field1=value3...
For each field of the form, the query string contains a pair field=value. Web forms may include fields that are not visible to the user; these fields are included in the query string when the form is submitted
This convention is a W3C recommendation. W3C recommends that all web servers support semicolon separators in addition to ampersand separators[6] to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands.
Technically, the form content is only encoded as a query string when the form submission method is GET. The same encoding is used by default when the submission method is POST, but the result is not sent as a query string, that is, is not added to the action URL of the form. Rather, the string is sent as the body of the HTTP request.
Forking vs. Branching in GitHub
You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.
Forking is nothing more than a clone on the GitHub server side:
- without the possibility to directly push back
- with fork queue feature added to manage the merge request
You keep a fork in sync with the original project by:
- adding the original project as a remote
- fetching regularly from that original project
- rebase your current development on top of the branch of interest you got updated from that fetch.
The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.
The goal is really to allow collaboration even though direct participation is not always possible.
The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.
The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream
(rebase your work on top of new commits from upstream), and then git push --force origin
, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.
See also:
How to auto adjust the <div> height according to content in it?
I have made some reach to do auto adjust of height for my project and I think I found a solution
[CSS]
overflow: auto;
overflow-x: hidden;
overflow-y: hidden;
This can be attached to prime div
(e.g. warpper, but not to body
or html
cause the page will not scroll down) in your css file and inherited by other child classes and write into them overflow: inherit;
attribute.
Notice: Odd thing is that my netbeans 7.2.1 IDE highlight overflow: inherit;
as Unexpected value token inherit
but all modern browser read this attribute fine.
This solution work very well into
- firefox 18+
- chorme 24+
- ie 9+
- opera 12+
I do not test it on previous versions of those browsers. If someone will check it, it will be nice.
How to provide user name and password when connecting to a network share
OK... I can resond..
Disclaimer: I just had an 18+ hour day (again).. I'm old and forgetfull.. I can't spell.. I have a short attention span so I better respond fast.. :-)
Question:
Is it possible to change the thread principal to an user with no account on the local machine?
Answer:
Yes, you can change a thread principal even if the credentials you are using are not defined locally or are outside the "forest".
I just ran into this problem when trying to connect to an SQL server with NTLM authentication from a service. This call uses the credentials associated with the process meaning that you need either a local account or a domain account to authenticate before you can impersonate. Blah, blah...
But...
Calling LogonUser(..) with the attribute of ????_NEW_CREDENTIALS will return a security token without trying to authenticate the credentials. Kewl.. Don't have to define the account within the "forest". Once you have the token you might have to call DuplicateToken() with the option to enable impersonation resulting in a new token. Now call SetThreadToken( NULL, token ); (It might be &token?).. A call to ImpersonateLoggedonUser( token ); might be required, but I don't think so. Look it up..
Do what you need to do..
Call RevertToSelf() if you called ImpersonateLoggedonUser() then SetThreadToken( NULL, NULL ); (I think... look it up), and then CloseHandle() on the created handles..
No promises but this worked for me... This is off the top of my head (like my hair) and I can't spell!!!
jQuery validation plugin: accept only alphabetical characters?
Just a small addition to Nick's answer (which works great !) :
If you want to allow spaces in between letters, for example ,
you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:
jQuery.validator.addMethod("lettersonly", function(value, element)
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Why are static variables considered evil?
Static variables are not good nor evil. They represent attributes that describe the whole class and not a particular instance. If you need to have a counter for all the instances of a certain class, a static variable would be the right place to hold the value.
Problems appear when you try to use static variables for holding instance related values.
How to pass all arguments passed to my bash script to a function of mine?
abc "$@" is generally the correct answer.
But I was trying to pass a parameter through to an su command, and no amount of quoting could stop the error su: unrecognized option '--myoption'
. What actually worked for me was passing all the arguments as a single string :
abc "$*"
My exact case (I'm sure someone else needs this) was in my .bashrc
# run all aws commands as Jenkins user
aws ()
{
sudo su jenkins -c "aws $*"
}
When to use <span> instead <p>?
You should keep in mind, that HTML is intended to DESCRIBE the content it contains.
So, if you wish to convey a paragraph, then do so.
Your comparison isn't exactly right, though. The more direct comparison would be
When to use a <div>
instead of a <p>
?
as both are block level elements.
A <span>
is inline, much like an anchor (<a>
), <strong>
, emphasis (<em>
), etc., so bear in mind that by it's default nature in both html and in natural writing, that a paragraph will cause a break before and after itself, like a <div>
.
Sometimes, when styling things — inline things — a <span>
is great to give you something to "hook" the css to, but it is otherwise an empty tag devoid of semantic or stylistic meaning.
How to check which locks are held on a table
You can find current locks on your table by following query.
USE yourdatabase;
GO
SELECT * FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID()
AND resource_associated_entity_id = OBJECT_ID(N'dbo.yourtablename');
See sys.dm_tran_locks
If multiple instances of the same request_owner_type exist, the request_owner_id column is used to distinguish each instance. For distributed transactions, the request_owner_type and the request_owner_guid columns will show the different entity information.
For example, Session S1 owns a shared lock on Table1; and transaction T1, which is running under session S1, also owns a shared lock on Table1. In this case, the resource_description column that is returned by sys.dm_tran_locks will show two instances of the same resource. The request_owner_type column will show one instance as a session and the other as a transaction. Also, the resource_owner_id column will have different values.
How can I get client information such as OS and browser
Here's my code that works, as of today, with some of the latest browsers.
Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.
String userAgent = "Unknown";
String osType = "Unknown";
String osVersion = "Unknown";
String browserType = "Unknown";
String browserVersion = "Unknown";
String deviceType = "Unknown";
try {
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
//userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
boolean exceptionTest = false;
if(exceptionTest) throw new Exception("EXCEPTION TEST");
if (userAgent.indexOf("Windows NT") >= 0) {
osType = "Windows";
osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));
} else if (userAgent.indexOf("Mac OS") >= 0) {
osType = "Mac";
osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));
if(userAgent.indexOf("iPhone") >= 0) {
deviceType = "iPhone";
} else if(userAgent.indexOf("iPad") >= 0) {
deviceType = "iPad";
}
} else if (userAgent.indexOf("X11") >= 0) {
osType = "Unix";
osVersion = "Unknown";
} else if (userAgent.indexOf("android") >= 0) {
osType = "Android";
osVersion = "Unknown";
}
logger.trace("end of os section");
if (userAgent.contains("Edge/")) {
browserType = "Edge";
browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];
} else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
browserType = "Safari";
browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];
} else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
browserType = "Opera";
browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];
} else if (userAgent.contains("Chrome/")) {
browserType = "Chrome";
browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
browserVersion = browserVersion.split(" ")[0];
} else if (userAgent.contains("Firefox/")) {
browserType = "Firefox";
browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
}
logger.trace("end of browser section");
} catch (Exception ex) {
logger.error("ERROR: " +ex);
}
logger.debug(
"\n userAgent: " + userAgent
+ "\n osType: " + osType
+ "\n osVersion: " + osVersion
+ "\n browserType: " + browserType
+ "\n browserVersion: " + browserVersion
+ "\n deviceType: " + deviceType
);
Logger Output:
userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
osType: Windows
osVersion: 10.0
browserType: Opera
browserVersion: 60.0.3255.165
deviceType: Unknown
nodejs - How to read and output jpg image?
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
Difference between parameter and argument
Argument is often used in the sense of actual argument vs. formal parameter.
The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.
That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.
So here, x
and y
would be formal parameters:
int foo(int x, int y) {
...
}
Whereas here, in the function call, 5 and z
are the actual arguments:
foo(5, z);
checking if a number is divisible by 6 PHP
if ($number % 6 != 0) {
$number += 6 - ($number % 6);
}
The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.
If decreasing is acceptable then this is even faster:
$number -= $number % 6;
Node.js Write a line into a .txt file
Step 1
If you have a small file
Read all the file data in to memory
Step 2
Convert file data string into Array
Step 3
Search the array to find a location where you want to insert the text
Step 4
Once you have the location insert your text
yourArray.splice(index,0,"new added test");
Step 5
convert your array to string
yourArray.join("");
Step 6
write your file like so
fs.createWriteStream(yourArray);
This is not advised if your file is too big
Converting milliseconds to a date (jQuery/JavaScript)
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Reverse a string in Java
package ThingsInArray;
public class MagicWithSelectionSort {
public static void main(String[] arg) {
isSort("uhsnamiH");
}
private static void isSort(String name) {
String revName="";
for (int i = name.toCharArray().length-1; i >0 ; i--) {
revName=revName+name.charAt(i);
}
System.out.println(revName);
}
}
display Java.util.Date in a specific format
You need to go through SimpleDateFormat.format
in order to format the date as a string.
Here's an example that goes from String
-> Date
-> String
.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
How to get the timezone offset in GMT(Like GMT+7:00) from android device?
This code return me GMT offset.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: +0530
If we use SimpleDateFormat below
DateFormat date = new SimpleDateFormat("z",Locale.getDefault());
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: GMT+05:30
How can I simulate mobile devices and debug in Firefox Browser?
Most web applications detects mobile devices based on the HTTP Headers.
If your web site also uses HTTP Headers to identify mobile device, you can do the following:
- Add Modify Headers plug in to your Firefox browser (
https://addons.mozilla.org/en-US/firefox/addon/modify-headers/
)
- Using plugin modify headers:
- select Headers tab-> select Action 'ADD'
- to simulate e.g. iPhone add a header with name
User-Agent
and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
- click 'Add' button
- After that you should be able to see mobile
version of you web application in Firefox and use Firebug plugin.
Hope it helps!
Set focus on TextBox in WPF from view model
You could use the ViewCommand design pattern. It describes a method for the MVVM design pattern to control a View from a ViewModel with commands.
I've implemented it based on King A.Majid's suggestion to use the MVVM Light Messenger class. The ViewCommandManager class handles invoking commands in connected views. It's basically the other direction of regular Commands, for these cases when a ViewModel needs to do some action in its View. It uses reflection like data-bound commands and WeakReferences to avoid memory leaks.
http://dev.unclassified.de/source/viewcommand (also published on CodeProject)
Android scale animation on view
Here is a code snip to do exactly that.
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
v.startAnimation(anim);
}
The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...)
.
The other 4 args are for the Y-scaling we do care about.
startScale, endScale
- In your case, you'd use 0f, 0.6f
.
Animation.RELATIVE_TO_SELF, 1f
- This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f
because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f
.
Finally, and equally important, is the call to anim.setFillAfter(true)
. If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.
So in your case, you can do something like this:
View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);
Regular expression replace in C#
You can do it this with two replace's
//let stw be "John Smith $100,000.00 M"
sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"
sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"
sw.WriteLine(sb_trim);
What to do with "Unexpected indent" in python?
This error can also occur when pasting something into the Python interpreter (terminal/console).
Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like
def my_function():
x = 3
y = 7
the interpreter will interpret the empty line before y = 7
as the end of the expression, i.e. that you're done defining your function, and the next line - y = 7
will have incorrect indentation because it is a new expression.
Executing Javascript code "on the spot" in Chrome?
Have you tried something like this? Put it in the head for it to work properly.
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(){
//using DOMContentLoaded is good as it relies on the DOM being ready for
//manipulation, rather than the windows being fully loaded. Just like
//how jQuery's $(document).ready() does it.
//loop through your inputs and set their values here
}, false);
</script>
Find Item in ObservableCollection without using a loop
Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance.
You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.
How to set HTTP headers (for cache-control)?
OWASP recommends the following,
Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.
<IfModule mod_headers.c>
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</IfModule>
Jquery how to find an Object by attribute in an Array
No need for jQuery.
JavaScript arrays have a find method, so you can achieve that in one line:
array.find((o) => { return o[propertyName] === propertyValue }
Example
const purposeObjects = [
{purpose: "daily"},
{purpose: "weekly"},
{purpose: "monthly"}
];
purposeObjects.find((o) => { return o["purpose"] === "weekly" }
// output -> {purpose: "weekly"}
If you need IE compatibility, import this polyfill in your code.
How to load local html file into UIWebView
UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
//[self.view addSubview:web];
NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
[web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];
Calling a function of a module by using its name (a string)
As this question How to dynamically call methods within a class using method-name assignment to a variable [duplicate] marked as a duplicate as this one, I am posting a related answer here:
The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func = getattr(MyClass, 'function{}'.format(self.i))
func(self, 12) # This one will work
# self.func(12) # But this does NOT work.
def function1(self, p1):
print('function1: {}'.format(p1))
# do other stuff
def function2(self, p1):
print('function2: {}'.format(p1))
# do other stuff
if __name__ == "__main__":
class1 = MyClass(1)
class1.get()
class2 = MyClass(2)
class2.get()
Output (Python 3.7.x)
function1: 12
function2: 12
Error loading the SDK when Eclipse starts
Apart from Android Wear image, the same error is also displayed for Android TV as well, so if you do not have Android Wear image installed but have Android TV image installed, please uninstall that and then try.
JavaScript: Difference between .forEach() and .map()
Difference between forEach() & map()
forEach() just loop through the elements. It's throws away return values and always returns undefined.The result of this method does not give us an output .
map() loop through the elements allocates memory and stores return values by iterating main array
Example:
var numbers = [2,3,5,7];
var forEachNum = numbers.forEach(function(number){
return number
})
console.log(forEachNum)
//output undefined
var mapNum = numbers.map(function(number){
return number
})
console.log(mapNum)
//output [2,3,5,7]
map() is faster than forEach()
What does "Git push non-fast-forward updates were rejected" mean?
It means that there have been other commits pushed to the remote repository that differ from your commits. You can usually solve this with a
git pull
before you push
Ultimately, "fast-forward" means that the commits can be applied directly on top of the working tree without requiring a merge.
JS file gets a net::ERR_ABORTED 404 (Not Found)
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Resize on div element
You can change your text or Content or Attribute depend on Screen size:
HTML:
<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>
Javascript:
<script>
const changeText = document.querySelector('.change');
function resize() {
if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
changeText.textContent="FAQ";
} else {
changeText.textContent="Frequently Asked Questions (FAQ)";
}
}
window.onresize = resize;
</script>
How to validate Google reCAPTCHA v3 on server side?
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
$username = $_POST['username'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if($response->success){
echo "Verification is correct. Your name is $username";
} else {
echo "Verification failed";
}
} ?>
<html>
<meta>
<title>Google ReCaptcha</title>
</meta>
<body>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Write your name"/>
<div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
<input type="submit" name="submit" value="send"/>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
Array Length in Java
Java arrays are actually fixed in size, and the other answers explain how .length isn't really doing what you'd expect. I'd just like to add that given your question what you might want to be using is an ArrayList, that is an array that can grow and shrink:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Here the .size() method will show you the number of elements in your list, and you can grow this as you add things.
How to measure elapsed time
There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime()
and TimeUnit.NANOSECONDS
as the time unit. Why should I do this? Well, it is because System.nanoTime()
method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
For the same reason, it is recommended to avoid the use of the System.currentTimeMillis()
method for measuring elapsed time. This method returns the wall-clock
time, which may change based on many factors. This will be negative for your measurements.
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
So here you have one solution based on the System.nanoTime()
method, another one using Guava, and the final one Apache Commons Lang
public class TimeBenchUtil
{
public static void main(String[] args) throws InterruptedException
{
stopWatch();
stopWatchGuava();
stopWatchApacheCommons();
}
public static void stopWatch() throws InterruptedException
{
long endTime, timeElapsed, startTime = System.nanoTime();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
endTime = System.nanoTime();
// get difference of two nanoTime values
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchGuava() throws InterruptedException
{
// Creates and starts a new stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // optional
// get elapsed time, expressed in milliseconds
long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchApacheCommons() throws InterruptedException
{
StopWatch stopwatch = new StopWatch();
stopwatch.start();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // Optional
long timeElapsed = stopwatch.getNanoTime();
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
}
Java URLConnection Timeout
You can set timeouts for all connections made from the jvm by changing the following System-properties:
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
Every connection will time out after 10 seconds.
Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.
Use component from another module
The main rule here is that:
The selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.
So, try to export it:
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
exports: [TaskCardComponent] <== this line
})
export class TaskModule{}
What should I export?
Export declarable classes that components in other modules should be
able to reference in their templates. These are your public classes.
If you don't export a class, it stays private, visible only to other
component declared in this module.
The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state(as Ward Bell said in https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2)
Angular creates transitive module for each of @NgModule
s.
This module collects directives that either imported from another module(if transitive module of imported module has exported directives) or declared in current module.
When angular compiles template that belongs to module X
it is used those directives that had been collected in X.transitiveModule.directives.
compiledTemplate = new CompiledTemplate(
false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251
This way according to the picture above
YComponent
can't use ZComponent
in its template because directives
array of Transitive module Y
doesn't contain ZComponent
because YModule
has not imported ZModule
whose transitive module contains ZComponent
in exportedDirectives
array.
Within XComponent
template we can use ZComponent
because Transitive module X
has directives array that contains ZComponent
because
XModule
imports module (YModule
) that exports module (ZModule
) that exports directive ZComponent
Within AppComponent
template we can't use XComponent
because AppModule
imports XModule
but XModule
doesn't exports XComponent
.
See also
How to read a .xlsx file using the pandas Library in iPython?
DataFrame's read_excel
method is like read_csv
method:
dfs = pd.read_excel(xlsx_file, sheetname="sheet1")
Help on function read_excel in module pandas.io.excel:
read_excel(io, sheetname=0, header=0, skiprows=None, skip_footer=0, index_col=None, names=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, convert_float=True, has_index_names=None, converters=None, true_values=None, false_values=None, engine=None, squeeze=False, **kwds)
Read an Excel table into a pandas DataFrame
Parameters
----------
io : string, path object (pathlib.Path or py._path.local.LocalPath),
file-like object, pandas ExcelFile, or xlrd workbook.
The string could be a URL. Valid URL schemes include http, ftp, s3,
and file. For file URLs, a host is expected. For instance, a local
file could be file://localhost/path/to/workbook.xlsx
sheetname : string, int, mixed list of strings/ints, or None, default 0
Strings are used for sheet names, Integers are used in zero-indexed
sheet positions.
Lists of strings/integers are used to request multiple sheets.
Specify None to get all sheets.
str|int -> DataFrame is returned.
list|None -> Dict of DataFrames is returned, with keys representing
sheets.
Available Cases
* Defaults to 0 -> 1st sheet as a DataFrame
* 1 -> 2nd sheet as a DataFrame
* "Sheet1" -> 1st sheet as a DataFrame
* [0,1,"Sheet5"] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames
* None -> All sheets as a dictionary of DataFrames
header : int, list of ints, default 0
Row (0-indexed) to use for the column labels of the parsed
DataFrame. If a list of integers is passed those row positions will
be combined into a ``MultiIndex``
skiprows : list-like
Rows to skip at the beginning (0-indexed)
skip_footer : int, default 0
Rows at the end to skip (0-indexed)
index_col : int, list of ints, default None
Column (0-indexed) to use as the row labels of the DataFrame.
Pass None if there is no such column. If a list is passed,
those columns will be combined into a ``MultiIndex``
names : array-like, default None
List of column names to use. If file contains no header row,
then you should explicitly pass header=None
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
either be integers or column labels, values are functions that take one
input argument, the Excel cell content, and return the transformed
content.
true_values : list, default None
Values to consider as True
.. versionadded:: 0.19.0
false_values : list, default None
Values to consider as False
.. versionadded:: 0.19.0
parse_cols : int or list, default None
* If None then parse all columns,
* If int then indicates last column to be parsed
* If list of ints then indicates list of column numbers to be parsed
* If string then indicates comma separated list of column names and
column ranges (e.g. "A:E" or "A,C,E:F")
squeeze : boolean, default False
If the parsed data only contains one column then return a Series
na_values : scalar, str, list-like, or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific
per-column NA values. By default the following values are interpreted
as NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
'1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'nan'.
thousands : str, default None
Thousands separator for parsing string columns to numeric. Note that
this parameter is only necessary for columns stored as TEXT in Excel,
any numeric columns will automatically be parsed, regardless of display
format.
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to.
verbose : boolean, default False
Indicate number of NA values placed in non-numeric columns
engine: string, default None
If io is not a buffer or path, this must be set to identify io.
Acceptable values are None or xlrd
convert_float : boolean, default True
convert integral floats to int (i.e., 1.0 --> 1). If False, all numeric
data will be read in as floats: Excel stores all numbers as floats
internally
has_index_names : boolean, default None
DEPRECATED: for version 0.17+ index names will be automatically
inferred based on index_col. To read Excel output from 0.16.2 and
prior that had saved index names, use True.
Returns
-------
parsed : DataFrame or Dict of DataFrames
DataFrame from the passed in Excel file. See notes in sheetname
argument for more information on when a Dict of Dataframes is returned.
Adding a UISegmentedControl to UITableView
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
Detect click event inside iframe
The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler
// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onClick.add(function(ed, e) {
console.debug('Iframe clicked:' + e.target);
});
}
});
File upload along with other object in Jersey restful web service
When I tried @PaulSamsotha's solution with Jersey client 2.21.1, there was 400 error. It worked when I added following in my client code:
MediaType contentType = MediaType.MULTIPART_FORM_DATA_TYPE;
contentType = Boundary.addBoundary(contentType);
Response response = t.request()
.post(Entity.entity(multipartEntity, contentType));
instead of hardcoded MediaType.MULTIPART_FORM_DATA
in POST request call.
The reason this is needed is because when you use a different Connector (like Apache) for the Jersey Client, it is unable to alter outbound headers, which is required to add a boundary to the Content-Type. This limitation is explained in the Jersey Client docs. So if you want to use a different Connector, then you need to manually create the boundary.
Laravel 5.5 ajax call 419 (unknown status)
Even though you have a csrf_token
, if you are authenticate your controller actions using Laravel Policies
you can have 419 response as well. In that case you should add necessary policy functions in your Policy
class.
phpMyAdmin on MySQL 8.0
I solved this issue by doing following:
Enter to system preferences -> mysql
Select "Initialize database" and enter a new root password selecting "Use Legacy Password Encryption".
Login into phpmyadmin with the new password.
How to do a Postgresql subquery in select clause with join in from clause like SQL Server?
Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different
Table structure
CREATE TABLE ITEMS (
N INTEGER NOT NULL,
S TEXT NOT NULL
);
INSERT INTO ITEMS
SELECT
(random()*1000000)::integer AS n,
md5(random()::text) AS s
FROM
generate_series(1,1000000);
CREATE INDEX N_INDEX ON ITEMS(N);
Performing JOIN
with GROUP BY
in subquery without LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN (
SELECT
COUNT(1), n
FROM ITEMS
GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);
The results
Merge Join (cost=0.87..637500.40 rows=23 width=37)
Merge Cond: (i.n = items.n)
-> Index Scan using n_index on items i (cost=0.43..101.28 rows=23 width=37)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..626631.11 rows=861418 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..593016.93 rows=10000000 width=4)
Using LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN LATERAL (
SELECT
COUNT(1), n
FROM ITEMS
WHERE N = I.N
GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);
Results
Nested Loop (cost=9.49..1319.97 rows=276 width=37)
-> Bitmap Heap Scan on items i (cost=9.06..100.20 rows=23 width=37)
Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
-> Bitmap Index Scan on n_index (cost=0.00..9.05 rows=23 width=0)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..52.79 rows=12 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..52.64 rows=12 width=4)
Index Cond: (n = i.n)
My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)
Difference between BYTE and CHAR in column datatypes
I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.
Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).
How do I POST XML data with curl
It is simpler to use a file (req.xml
in my case) with content you want to send -- like this:
curl -H "Content-Type: text/xml" -d @req.xml -X POST http://localhost/asdf
You should consider using type 'application/xml', too (differences explained here)
Alternatively, without needing making curl actually read the file, you can use cat
to spit the file into the stdout and make curl
to read from stdout like this:
cat req.xml | curl -H "Content-Type: text/xml" -d @- -X POST http://localhost/asdf
Both examples should produce identical service output.
Match two strings in one line with grep
Place the strings you want to grep for into a file
echo who > find.txt
echo Roger >> find.txt
echo [44][0-9]{9,} >> find.txt
Then search using -f
grep -f find.txt BIG_FILE_TO_SEARCH.txt
SQL Call Stored Procedure for each Row without using a cursor
If you can turn the stored procedure into a function that returns a table, then you can use cross-apply.
For example, say you have a table of customers, and you want to compute the sum of their orders, you would create a function that took a CustomerID and returned the sum.
And you could do this:
SELECT CustomerID, CustomerSum.Total
FROM Customers
CROSS APPLY ufn_ComputeCustomerTotal(Customers.CustomerID) AS CustomerSum
Where the function would look like:
CREATE FUNCTION ComputeCustomerTotal
(
@CustomerID INT
)
RETURNS TABLE
AS
RETURN
(
SELECT SUM(CustomerOrder.Amount) AS Total FROM CustomerOrder WHERE CustomerID = @CustomerID
)
Obviously, the example above could be done without a user defined function in a single query.
The drawback is that functions are very limited - many of the features of a stored procedure are not available in a user-defined function, and converting a stored procedure to a function does not always work.
How do I compute the intersection point of two lines?
Here is a solution using the Shapely library. Shapely is often used for GIS work, but is built to be useful for computational geometry. I changed your inputs from lists to tuples.
Problem
# Given these endpoints
#line 1
A = (X, Y)
B = (X, Y)
#line 2
C = (X, Y)
D = (X, Y)
# Compute this:
point_of_intersection = (X, Y)
Solution
import shapely
from shapely.geometry import LineString, Point
line1 = LineString([A, B])
line2 = LineString([C, D])
int_pt = line1.intersection(line2)
point_of_intersection = int_pt.x, int_pt.y
print(point_of_intersection)
Scraping data from website using vba
This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.
Sub ExtractLastValue()
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600
objIE.Visible = True
objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")
Do
DoEvents
Loop Until objIE.readystate = 4
MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText
End Sub
And if you are new to web scraping please read this blog post.
Web Scraping - Basics
And also there are various techniques to extract data from web pages. This article explain few of them with examples.
Web Scraping - Collecting Data From a Webpage
makefile:4: *** missing separator. Stop
If you are editing your Makefile in eclipse:
Windows-> Preferences->General->Editor->Text Editors->Show Whitespace Characters -> Apply
Or use the shortcut shown below.
Tab will be represented by gray ">>" and Space will be represented by gray "." as in figure below.
How to run html file using node js
Just install http-server globally
npm install -g http-server
where ever you need to run a html file run the command http-server
For ex: your html file is in /home/project/index.html
you can do /home/project/$ http-server
That will give you a link to accessyour webpages:
http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.0.106:8080
Alternative to iFrames with HTML5
I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.
Changes to the parent site are picked up every 5 minutes.
var iframeReplacement = require('node-iframe-replacement');
// add iframe replacement to express as middleware (adds res.merge method)
app.use(iframeReplacement);
// create a regular express route
app.get('/', function(req, res){
// respond to this request with our fake-news content embedded within the BBC News home page
res.merge('fake-news', {
// external url to fetch
sourceUrl: 'http://www.bbc.co.uk/news',
// css selector to inject our content into
sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
// pass a function here to intercept the source html prior to merging
transform: null
});
});
The source contains a working example of injecting content into the BBC News home page.
Extract text from a string
Just to add a non-regex solution:
'(' + $myString.Split('()')[1] + ')'
This splits the string at the parentheses and takes the string from the array with the program name in it.
If you don't need the parentheses, just use:
$myString.Split('()')[1]
java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
- Your server is running a lower Java version then the one used to compile your Servlet and vice versa
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 :
If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
Get full query string in C# ASP.NET
Just use Request.QueryString.ToString()
to get full query string, like this:
string URL = "http://www.example.com/rendernews.php?"+Request.Querystring.ToString();
Can an Android Toast be longer than Toast.LENGTH_LONG?
LONG_DELAY toast display for 3.5 sec and SHORT_DELAY toast display for 2 sec.
Toast internally use INotificationManager and calls it's enqueueToast method every time a Toast.show() is called.
Call the show() with SHORT_DELAY twice will enqueue same toast again. it will display for 4 sec ( 2 sec + 2 sec).
similarly, call the show() with LONG_DELAY twice will enqueue same toast again. it will display for 7 sec ( 3.5 sec + 3.5 sec)
List of all users that can connect via SSH
Any user whose login shell setting in /etc/passwd
is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells
is probably as good as you can get.
Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false
as their shell -- this will just log them out immediately.
To the power of in C?
You need pow();
function from math.h
header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y
.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h
to avoid warning ("incompatible implicit declaration of built in function 'pow'
").
Link math library by using -lm
while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
How do I remove a library from the arduino environment?
For others who are looking to remove a built-in library, the route is to get into PackageContents -> Java -> libraries.
BUT : IT MAKES NO SENSE TO ELIMINATE LIBRARIES inside the app, they don't take space, don't have any influence on performance, and if you don't know what you are doing, you can harm the program.
I did it because Arduino told me about libraries to update, showing then a board I don't have, and when saying ok it wanted to install a lot of new dependencies - I just felt forced to something I don't want, so I deinstalled that board.
XPath test if node value is number
The shortest possible way to test if the value contained in a variable $v
can be used as a number is:
number($v) = number($v)
You only need to substitute the $v
above with the expression whose value you want to test.
Explanation:
number($v) = number($v)
is obviously true, if $v
is a number, or a string that represents a number.
It is true also for a boolean value, because a number(true())
is 1 and number(false)
is 0.
Whenever $v
cannot be used as a number, then number($v)
is NaN
and NaN is not equal to any other value, even to itself.
Thus, the above expression is true only for $v
whose value can be used as a number, and false otherwise.
ASP.net Repeater get current index, pointer, or counter
To display the item number on the repeater you can use the Container.ItemIndex
property.
<asp:repeater id="rptRepeater" runat="server">
<itemtemplate>
Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
</itemtemplate>
<separatortemplate>
<br />
</separatortemplate>
</asp:repeater>
How to assert greater than using JUnit Assert?
As I recognize, at the moment, in JUnit, the syntax is like this:
AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");
Means that, the condition is in front of the message.
Remove stubborn underline from link
You missed text-decoration:none
for the anchor tag. So code should be following.
_x000D_
_x000D_
.boxhead a {_x000D_
text-decoration: none;_x000D_
}
_x000D_
<div class="boxhead">_x000D_
<h2>_x000D_
<span class="thisPage">Current Page</span>_x000D_
<a href="myLink"><span class="otherPage">Different Page</span></a>_x000D_
</h2>_x000D_
</div>
_x000D_
_x000D_
_x000D_
More standard properties for text-decoration
Linker error: "linker input file unused because linking not done", undefined reference to a function in that file
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
How to find if directory exists in Python
We can check with 2 built in functions
os.path.isdir("directory")
It will give boolean true the specified directory is available.
os.path.exists("directoryorfile")
It will give boolead true if specified directory or file is available.
To check whether the path is directory;
os.path.isdir("directorypath")
will give boolean true if the path is directory
React Native Change Default iOS Simulator Device
As answered by Ian L, I also use NPM to manage my scripts.
Example:
_x000D_
_x000D_
{_x000D_
"scripts": {_x000D_
"ios": "react-native run-ios --simulator=\"iPad Air 2\"",_x000D_
"devices": "xcrun simctl list devices"_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_
This way, I can quickly get what I need:
- List all devices:
npm run devices
- Run the default simulator:
npm run ios
Reading serial data in realtime in Python
You need to set the timeout to "None" when you open the serial port:
ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False)
This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end:
line = ser.readline()
Once you have the data, it will return ASAP.
Disable asp.net button after click to prevent double clicking
If anyone cares I found this post initially, but I use ASP.NET's build in Validation on the page. The solutions work, but disable the button even if its been validated. You can use this following code in order to make it so it only disables the button if it passes page validation.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" OnClientClick=" if ( Page_ClientValidate() ) { this.value='Submitting..'; this.disabled=true; }" UseSubmitBehavior="false" />
Difference between .on('click') vs .click()
I think, the difference is in usage patterns.
I would prefer .on
over .click
because the former can use less memory and work for dynamically added elements.
Consider the following html:
<html>
<button id="add">Add new</button>
<div id="container">
<button class="alert">alert!</button>
</div>
</html>
where we add new buttons via
$("button#add").click(function() {
var html = "<button class='alert'>Alert!</button>";
$("button.alert:last").parent().append(html);
});
and want "Alert!" to show an alert. We can use either "click" or "on" for that.
When we use click
$("button.alert").click(function() {
alert(1);
});
with the above, a separate handler gets created for every single element that matches the selector. That means
- many matching elements would create many identical handlers and thus increase memory footprint
- dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.
When we use .on
$("div#container").on('click', 'button.alert', function() {
alert(1);
});
with the above, a single handler for all elements that match your selector, including the ones created dynamically.
...another reason to use .on
As Adrien commented below, another reason to use .on
is namespaced events.
If you add a handler with .on("click", handler)
you normally remove it with .off("click", handler)
which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:
$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });
with unbinding via
$("#element").off("click.someNamespace");
Easiest way to make lua script wait/pause/sleep/block for a few seconds?
It's also easy to use Alien as a libc/msvcrt wrapper:
> luarocks install alien
Then from lua:
require 'alien'
if alien.platform == "windows" then
-- untested!!
libc = alien.load("msvcrt.dll")
else
libc = alien.default
end
usleep = libc.usleep
usleep:types('int', 'uint')
function sleep(ms)
while ms > 1000 do
usleep(1000)
ms = ms - 1000
end
usleep(1000 * ms)
end
print('hello')
sleep(500) -- sleep 500 ms
print('world')
Caveat lector: I haven't tried this on MSWindows; I don't even know if msvcrt has a usleep()
Resolve Javascript Promise outside function scope
I've put together a gist that does that job: https://gist.github.com/thiagoh/c24310b562d50a14f3e7602a82b4ef13
here's how you should use it:
import ExternalizedPromiseCreator from '../externalized-promise';
describe('ExternalizedPromise', () => {
let fn: jest.Mock;
let deferredFn: jest.Mock;
let neverCalledFn: jest.Mock;
beforeEach(() => {
fn = jest.fn();
deferredFn = jest.fn();
neverCalledFn = jest.fn();
});
it('resolve should resolve the promise', done => {
const externalizedPromise = ExternalizedPromiseCreator.create(() => fn());
externalizedPromise
.promise
.then(() => deferredFn())
.catch(() => neverCalledFn())
.then(() => {
expect(deferredFn).toHaveBeenCalled();
expect(neverCalledFn).not.toHaveBeenCalled();
done();
});
expect(fn).toHaveBeenCalled();
expect(neverCalledFn).not.toHaveBeenCalled();
expect(deferredFn).not.toHaveBeenCalled();
externalizedPromise.resolve();
});
...
});
How to adjust text font size to fit textview
I've written a class that extends TextView and does this. It just uses measureText as you suggest. Basically it has a maximum text size and minimum text size (which can be changed) and it just runs through the sizes between them in decrements of 1 until it finds the biggest one that will fit. Not particularly elegant, but I don't know of any other way.
Here is the code:
import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialise();
}
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialise();
}
private void initialise() {
testPaint = new Paint();
testPaint.set(this.getPaint());
//max size defaults to the intially specified text size unless it is too small
maxTextSize = this.getTextSize();
if (maxTextSize < 11) {
maxTextSize = 20;
}
minTextSize = 10;
}
/* Re size the font so the specified text fits in the text box
* assuming the text box is the specified width.
*/
private void refitText(String text, int textWidth) {
if (textWidth > 0) {
int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
float trySize = maxTextSize;
testPaint.setTextSize(trySize);
while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) {
trySize -= 1;
if (trySize <= minTextSize) {
trySize = minTextSize;
break;
}
testPaint.setTextSize(trySize);
}
this.setTextSize(trySize);
}
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}
//Getters and Setters
public float getMinTextSize() {
return minTextSize;
}
public void setMinTextSize(int minTextSize) {
this.minTextSize = minTextSize;
}
public float getMaxTextSize() {
return maxTextSize;
}
public void setMaxTextSize(int minTextSize) {
this.maxTextSize = minTextSize;
}
//Attributes
private Paint testPaint;
private float minTextSize;
private float maxTextSize;
}
Match linebreaks - \n or \r\n?
In Python:
# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M)
or more rigorous:
# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()
Adding Python Path on Windows 7
I just installed Python 3.3 on Windows 7 using the option "add python to PATH".
In PATH variable, the installer automatically added a final backslash: C:\Python33\
and so it did not work on command prompt (i tried closing/opening the prompt several times)
I removed the final backslash and then it worked: C:\Python33
Thanks Ram Narasimhan for your tip #4 !
How to check if a variable is set in Bash?
If you wish to test that a variable is bound or unbound, this works well, even after you've turned on the nounset option:
set -o noun set
if printenv variableName >/dev/null; then
# variable is bound to a value
else
# variable is unbound
fi
How to use a global array in C#?
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Show animated GIF
//Class Name
public class ClassName {
//Make it runnable
public static void main(String args[]) throws MalformedURLException{
//Get the URL
URL img = this.getClass().getResource("src/Name.gif");
//Make it to a Icon
Icon icon = new ImageIcon(img);
//Make a new JLabel that shows "icon"
JLabel Gif = new JLabel(icon);
//Make a new Window
JFrame main = new JFrame("gif");
//adds the JLabel to the Window
main.getContentPane().add(Gif);
//Shows where and how big the Window is
main.setBounds(x, y, H, W);
//set the Default Close Operation to Exit everything on Close
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Open the Window
main.setVisible(true);
}
}
How to insert a line break <br> in markdown
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
Sorting int array in descending order
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
Test process.env with Jest
In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a utility (you probably want to include a check to fail fast if an environment variable is not set anyway), and then you can just mock the utility.
// util.js
exports.getEnv = (key) => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`Missing required environment variable ${key}`);
}
return value;
};
// app.test.js
const util = require('./util');
jest.mock('./util');
util.getEnv.mockImplementation(key => `fake-${key}`);
test('test', () => {...});
programming a servo thru a barometer
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
findViewById in Fragment
try
private View myFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentView;
}
How do I localize the jQuery UI Datepicker?
$.datepicker.regional["vi-VN"] =
{
closeText: "Ðóng",
prevText: "Tru?c",
nextText: "Sau",
currentText: "Hôm nay",
monthNames: ["Tháng m?t", "Tháng hai", "Tháng ba", "Tháng tu", "Tháng nam", "Tháng sáu", "Tháng b?y", "Tháng tám", "Tháng chín", "Tháng mu?i", "Tháng mu?i m?t", "Tháng mu?i hai"],
monthNamesShort: ["M?t", "Hai", "Ba", "B?n", "Nam", "Sáu", "B?y", "Tám", "Chín", "Mu?i", "Mu?i m?t", "Mu?i hai"],
dayNames: ["Ch? nh?t", "Th? hai", "Th? ba", "Th? tu", "Th? nam", "Th? sáu", "Th? b?y"],
dayNamesShort: ["CN", "Hai", "Ba", "Tu", "Nam", "Sáu", "B?y"],
dayNamesMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"],
weekHeader: "Tu?n",
dateFormat: "dd/mm/yy",
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ""
};
$.datepicker.setDefaults($.datepicker.regional["vi-VN"]);
python-dev installation error: ImportError: No module named apt_pkg
I see everyone saying how to fix it with strange copying etc, but no one really said why the problem occurs.
So let me explain, for those of you who like me don't want to mess with system files only because someone on SO told them so.
The problem is that:
- many system scripts have python3 shebang hardcoded into them. You can check it yourself:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*
/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3
- python apt package
python-apt
/python3-apt
is a system package, so it's for default system python
Thus, the scripts will always get the version currently linked to python3
, but fail because the apt package is not present.
General solution: NEVER change default python3
link. Ever. This also applies to python
link - if an app was written in Python2 with some old syntax elements that don't work in Python3, the app will not work.
[My terminal broke that way because I use Terminator, which is apparently written in Python2.7 not compatible with Python3.]
Solutions presented here either suggest copying/linking the apt package files or changing python3
link.
Let's analyse both:
- Copying/linking the apt package
This shouldn't be a problem because from around Python3.4 all python scripts work on newer versions as well.
So far. But it may break in the future - if you keep your system long enough.
- Changing
python3
link back
This is a great solution because we can get back to "never ever changing the link"
"But I like having to type just python
!" - I like it too! That's how I got to this problem in the first place!
In general, you should avoid manually changing system links - use update-alternatives
instead to link different versions. This applies to any app with many versions. This will still break those system scripts (because it does change the link), but you can switch back and forth easily, without worrying whether you put link and dest in the right order or made a typo.
Consider using other name than python
/python3
for your link or alias.
Or add your own python
/python3
link to PATH (just like virtual environments do), without changing system links.
How to update Android Studio automatically?
If you go to help>>check for updates it will tell you if there's an update.
You don't have to change from the stable channel. If you aren't offered an update and restart button, kindly close the window and try again. After about 4 or 5 checks like this, it will eventually show you update and restart button.
Why? because google.
Post multipart request with Android SDK
I can recomend Ion library it use 3 dependences and you can find all three jar files at these two sites:
https://github.com/koush/ion#jars (ion and androidasync)
https://code.google.com/p/google-gson/downloads/list (gson)
try {
Ion.with(this, "http://www.urlthatyouwant.com/post/page")
.setMultipartParameter("field1", "This is field number 1")
.setMultipartParameter("field2", "Field 2 is shorter")
.setMultipartFile("imagefile",
new File(Environment.getExternalStorageDirectory()+"/testfile.jpg"))
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
System.out.println(result);
}});
} catch(Exception e) {
// Do something about exceptions
System.out.println("exception: " + e);
}
this will run async and the callback will be executed in the UI thread once a response is received
I strongly recomned that you go to the https://github.com/koush/ion
for futher information
SQL Inner Join On Null Values
I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:
create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)
Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null
Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null
select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid
select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)
select * from #test2 t2
join #test1 t1 on
t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )
select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2 where qid is null
Difference between style = "position:absolute" and style = "position:relative"
Absolute places the object (div, span, etc.) at an absolute forced location (usually determined in pixels) and relative will place it a certain amount away from where it's location would normally be. For example:
position:relative; left:-20px;
Might make the left side of the text disappear if it was within 20px to the left edge of the screen.
How can I explicitly free memory in Python?
Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".
The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing
module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.
In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when you're all done with them).
Print a string as hex bytes?
Some complements to Fedor Gogolev answer:
First, if the string contains characters whose 'ASCII code' is below 10, they will not be displayed as required. In that case, the correct format should be {:02x}
:
>>> s = "Hello unicode \u0005 !!"
>>> ":".join("{0:x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:5:20:21:21'
^
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:05:20:21:21'
^^
Second, if your "string" is in reality a "byte string" -- and since the difference matters in Python 3 -- you might prefer the following:
>>> s = b"Hello bytes \x05 !!"
>>> ":".join("{:02x}".format(c) for c in s)
'48:65:6c:6c:6f:20:62:79:74:65:73:20:05:20:21:21'
Please note there is no need for conversion in the above code as a bytes objects is defined as "an immutable sequence of integers in the range 0 <= x < 256".
Error ITMS-90717: "Invalid App Store Icon"
I tried several of the things mentioned in this post (besides swapping to a .jpg) with no success. I solved it by opening the file in photoshop and using 'export to web'. Within that process/window is a checkbox for transparency.
How to limit depth for recursive file list?
tree -L 2 -u -g -p -d
Prints the directory tree in a pretty format up to depth 2 (-L 2).
Print user (-u) and group (-g) and permissions (-p).
Print only directories (-d).
tree has a lot of other useful options.
How do I make a transparent canvas in html5?
I believe you are trying to do exactly what I just tried to do:
I want two stacked canvases... the bottom one has a static image and the top one contains animated sprites. Because of the animation, you need to clear the background of the top layer to transparent at the start of rendering every new frame. I finally found the answer: it's not using globalAlpha, and it's not using a rgba() color. The simple, effective answer is:
context.clearRect(0,0,width,height);
Calling Javascript function from server side
This works for me. Hope it will work for you too.
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
I have edited the html page which you have provided. The updated page is as below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("Hello Test!!!!");
$('#ButtonRow').css("display", "block");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow" style="display: none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$("#<%=SearchCategory.ClientID%> input").change(function () {
alert("hi");
$("#ButtonRow").show();
});
</script>
HTML tag inside JavaScript
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write
to display things on browser.
Also if your document.write
exceeds one line, make sure to put concatenation +
at the end of each line.
Example
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>
Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it
This happens when you somehow confused java itself. You are trying to run a java 6 VM where it found a JRE 7. It might show this problem even if you type in the command line just java
or java -version
in a misconfigured environment. The JAR is not the problem, except in the very unlikely case where the code in JAR is looking in the Windows Registry for that (which probably is not your case).
In my case, I had the java.exe
, javaw.exe
and javaws.exe
from Java 6 in the Windows/System32
folder (don't know how it got to be there). The rest of the JDK and JRE where found in the PATH inside C:\Java\jdk_1.7.0\bin
. Oops!
Mongoose (mongodb) batch insert?
It seems that using mongoose there is a limit of more than 1000 documents, when using
Potato.collection.insert(potatoBag, onInsert);
You can use:
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
But this is almost twice as fast when testing with 10000 documents:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
Using filesystem in node.js with async / await
Recommend using an npm package such as https://github.com/davetemplin/async-file, as compared to custom functions. For example:
import * as fs from 'async-file';
await fs.rename('/tmp/hello', '/tmp/world');
await fs.appendFile('message.txt', 'data to append');
await fs.access('/etc/passd', fs.constants.R_OK | fs.constants.W_OK);
var stats = await fs.stat('/tmp/hello', '/tmp/world');
Other answers are outdated
Add URL link in CSS Background Image?
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
Increase days to php current Date()
php
supports c style date functions. You can add or substract date-periods with English-language style phrases via the strtotime
function. examples...
$Today=date('y:m:d');
// add 3 days to date
$NewDate=Date('y:m:d', strtotime('+3 days'));
// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime('-3 days'));
// PHP returns last sunday's date
$NewDate=Date('y:m:d', strtotime('Last Sunday'));
// One week from last sunday
$NewDate=Date('y:m:d', strtotime('+7 days Last Sunday'));
or
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
Can you call Directory.GetFiles() with multiple filters?
/// <summary>
/// Returns the names of files in a specified directories that match the specified patterns using LINQ
/// </summary>
/// <param name="srcDirs">The directories to seach</param>
/// <param name="searchPatterns">the list of search patterns</param>
/// <param name="searchOption"></param>
/// <returns>The list of files that match the specified pattern</returns>
public static string[] GetFilesUsingLINQ(string[] srcDirs,
string[] searchPatterns,
SearchOption searchOption = SearchOption.AllDirectories)
{
var r = from dir in srcDirs
from searchPattern in searchPatterns
from f in Directory.GetFiles(dir, searchPattern, searchOption)
select f;
return r.ToArray();
}
SyntaxError: missing ; before statement
I got this error, hope this will help someone:
const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';
The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.
Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.