Kill detached screen session
You can kill a detached session which is not responding within the screen session by doing the following.
Type screen -list
to identify the detached screen session.
~$ screen -list
There are screens on:
20751.Melvin_Peter_V42 (Detached)
Note: 20751.Melvin_Peter_V42
is your session id.
Get attached to the detached screen session
screen -r 20751.Melvin_Peter_V42
Once connected to the session press Ctrl + A then type :quit
How do I create a HTTP Client Request with a cookie?
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
How to change the Jupyter start-up folder
This is what I do for Jupyter/Anaconda on Windows. This method
also passes jupyter a python configuration script. I use this to add a path to my project parent folder:
1 Create jnote.bat somewhere:
@echo off
call activate %1
call jupyter notebook "%CD%" %2 %3
pause
In the same folder create a windows shortcut jupyter-notebook
TARGET: D:\util\jnote.bat py3-jupyter --config=jupyter_notebook_config.py
START IN: %CD%
Add the jupyter icon to the shortcut.
2 In your jupyter projects folders(s) do the following:
Create jupyter_notebook_config.py, put what you like in here:
import os
import sys
import inspect
# Add parent folder to sys path
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
os.environ['PYTHONPATH'] = parentdir
Then paste the jupyter-notebook
shortcut. Double-click the
shortcut and your jupyter should light up and the packages in
the parent folder will be available.
How to preventDefault on anchor tags?
You can do as follows
1.Remove href
attribute from anchor(a
) tag
2.Set pointer cursor in css to ng click elements
[ng-click],
[data-ng-click],
[x-ng-click] {
cursor: pointer;
}
Is there a way to word-wrap long words in a div?
Most of the previous answer didn't work for me in Firefox 38.0.5. This did...
<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
// Content goes here
</div>
Documentation:
Pandas get topmost n records within each group
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
AttributeError: 'str' object has no attribute
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Free XML Formatting tool
Another method to reindent XML in Notepad++:
From menu select Plugins -> XML Tools -> Pretty print (XML only – with line breaks)
or press Ctrl+Alt+Shift+B.
jquery .html() vs .append()
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML
is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes
) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes
as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div>
to jQuery()
, jQuery will take a shortcut and simply do document.createElement('div')
.
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML
is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ...
-- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
Proper usage of Java -D command-line parameters
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
Pointer to class data member "::*"
Pointer to members are C++'s type safe equivalent for C's offsetof()
, which is defined in stddef.h
: Both return the information, where a certain field is located within a class
or struct
. While offsetof()
may be used with certain simple enough classes also in C++, it fails miserably for the general case, especially with virtual base classes. So pointer to members were added to the standard. They also provide easier syntax to reference an actual field:
struct C { int a; int b; } c;
int C::* intptr = &C::a; // or &C::b, depending on the field wanted
c.*intptr += 1;
is much easier than:
struct C { int a; int b; } c;
int intoffset = offsetof(struct C, a);
* (int *) (((char *) (void *) &c) + intoffset) += 1;
As to why one wants to use offsetof()
(or pointer to members), there are good answers elsewhere on stackoverflow. One example is here: How does the C offsetof macro work?
Memory errors and list limits?
If you want to circumvent this problem you could also use the shelve. Then you would create files that would be the size of your machines capacity to handle, and only put them on the RAM when necessary, basically writing to the HD and pulling the information back in pieces so you can process it.
Create binary file and check if information is already in it if yes make a local variable to hold it else write some data you deem necessary.
Data = shelve.open('File01')
for i in range(0,100):
Matrix_Shelve = 'Matrix' + str(i)
if Matrix_Shelve in Data:
Matrix_local = Data[Matrix_Shelve]
else:
Data[Matrix_Selve] = 'somenthingforlater'
Hope it doesn't sound too arcaic.
Use a content script to access the page context variables and functions
The only thing missing hidden from Rob W's excellent answer is how to communicate between the injected page script and the content script.
On the receiving side (either your content script or the injected page script) add an event listener:
document.addEventListener('yourCustomEvent', function (e) {
var data = e.detail;
console.log('received', data);
});
On the initiator side (content script or injected page script) send the event:
var data = {
allowedTypes: 'those supported by structured cloning, see the list below',
inShort: 'no DOM elements or classes/functions',
};
document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));
Notes:
- DOM messaging uses structured cloning algorithm, which can transfer only some types of data in addition to primitive values. It can't send class instances or functions or DOM elements.
In Firefox, to send an object (i.e. not a primitive value) from the content script to the page context you have to explicitly clone it into the target using cloneInto
(a built-in function), otherwise it'll fail with a security violation error.
document.dispatchEvent(new CustomEvent('yourCustomEvent', {
detail: cloneInto(data, document.defaultView),
}));
Converting stream of int's to char's in java
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
Reactjs - setting inline styles correctly
It's not immediately obvious from the documentation why the following does not work:
<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>
But when doing it entirely inline:
- You need double curly brackets
- You don't need to put your values in quotes
- React will add some default if you omit
"em"
- Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
class
is className
The correct way looks like this:
<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>
How to load npm modules in AWS Lambda?
A .zip
file is required in order to include npm modules in Lambda. And you really shouldn't be using the Lambda web editor for much of anything- as with any production code, you should be developing locally, committing to git, etc.
MY FLOW:
1) My Lambda functions are usually helper utilities for a larger project, so I create a /aws/lambdas directory within that to house them.
2) Each individual lambda directory contains an index.js file containing the function code, a package.json file defining dependencies, and a /node_modules subdirectory. (The package.json file is not used by Lambda, it's just so we can locally run the npm install
command.)
package.json:
{
"name": "my_lambda",
"dependencies": {
"svg2png": "^4.1.1"
}
}
3) I .gitignore all node_modules directories and .zip files so that the files generated from npm installs and zipping won't clutter our repo.
.gitignore:
# Ignore node_modules
**/node_modules
# Ignore any zip files
*.zip
4) I run npm install
from within the directory to install modules, and develop/test the function locally.
5) I .zip the lambda directory and upload it via the console.
(IMPORTANT: Do not use Mac's 'compress' utility from Finder to zip the file! You must run zip from the CLI from within the root of the directory- see here)
zip -r ../yourfilename.zip *
NOTE:
You might run into problems if you install the node modules locally on your Mac, as some platform-specific modules may fail when deployed to Lambda's Linux-based environment. (See https://stackoverflow.com/a/29994851/165673)
The solution is to compile the modules on an EC2 instance launched from the AMI that corresponds with the Lambda Node.js runtime you're using (See this list of Lambda runtimes and their respective AMIs).
See also AWS Lambda Deployment Package in Node.js - AWS Lambda
convert streamed buffers to utf8-string
Single Buffer
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
Streamed Buffers
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
Entity Framework is Too Slow. What are my options?
You say that you have profiled the application. Have you profiled the ORM too? There is an EF profiler from Ayende that will highlight where you can optimise your EF code. You can find it here:
http://efprof.com/
Remember that you can use a traditional SQL approach alongside your ORM if you need to to gain performance.
If there a faster/better ORM? Depending on your object/data model, you could consider using a one of the micro-ORMs, such as Dapper, Massive or PetaPoco.
The Dapper site publishes some comparitive benchmarks that will give you an idea how they compare to other ORMs. But it's worth noting that the micro-ORMs do not support the rich feature set of the full ORMs like EF and NH.
You may want to take a look at RavenDB. This is a non-relational database (from Ayende again) that lets you store POCOs directly with no mapping needed. RavenDB is optimised for reads and makes the developers life a whole lot easier by removing need to manipulate schema and to map your objects to that schema. However, be aware that this is a significantly different approach to using an ORM approach and these are outlined in the product's site.
How do you use window.postMessage across domains?
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
Install Chrome extension form outside the Chrome Web Store
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
- Visit
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).
- Enable Developer mode by ticking the checkbox in the upper-right corner.
- Click on the "Load unpacked extension..." button.
- Select the directory containing your unpacked extension.
If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
Laravel migration default value
Might be a little too late to the party, but hope this helps someone with similar issue.
The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.
Let me illustrate with an example.
This line means Laravel is generating a new Book instance, as specified in your model. The new Book
object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.
$book = new Book();
Now the following lines are setting up the values of each property of the Book
object. Same still, nothing is written on the database yet.
$book->author = 'Test'
$book->title = 'Test'
This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).
$book->save();
And thus, the default value will not pop up before you save it to the database.
But, that is not enough. If you try to access $book->price
, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.
So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the
Book::find($book->id);
Or, a more sophisticated way by refreshing the instance
$book->refresh();
And then, the next time you try to access the object, it will be filled with the default values.
How to change the interval time on bootstrap carousel?
The best way to get rid on it is adding or modifying the data-interval attribute like this:
<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">
It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.
By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.
<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">
Can't draw Histogram, 'x' must be numeric
Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:
we <- gsub(",", "", we) # remove comma
we <- as.numeric(we) # turn into numbers
and now you can do
hist(we)
and other numeric operations.
Add a new line to the end of a JtextArea
Instead of using JTextArea.setText(String text)
, use JTextArea.append(String text)
.
Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.
This will add text on to the end of your JTextArea
.
Another option would be to use getText()
to get the text from the JTextArea
, then manipulate the String (add or remove or change the String), then use setText(String text)
to set the text of the JTextArea
to be the new String.
How can I remove the decimal part from JavaScript number?
u can also show a certain number of digit after decimal point(here 2 digits) using following code :
_x000D_
_x000D_
var num = (15.46974).toFixed(2)_x000D_
console.log(num) // 15.47_x000D_
console.log(typeof num) // string
_x000D_
_x000D_
_x000D_
Maximum number of threads in a .NET app?
There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this article by Raymond Chen for specifics.
If you need to ask what the maximum number of threads is, you are probably doing something wrong.
[Update: Just out of interest: .NET Thread Pool default numbers of threads:
- 1023 in Framework 4.0 (32-bit environment)
- 32767 in Framework 4.0 (64-bit environment)
- 250 per core in Framework 3.5
- 25 per core in Framework 2.0
(These numbers may vary depending upon the hardware and OS)]
SQL Server SELECT LAST N Rows
Is "Id" indexed? If not, that's an important thing to do (I suspect it is already indexed).
Also, do you need to return ALL columns? You may be able to get a substantial improvement in speed if you only actually need a smaller subset of columns which can be FULLY catered for by the index on the ID column - e.g. if you have a NONCLUSTERED index on the Id column, with no other fields included in the index, then it would have to do a lookup on the clustered index to actually get the rest of the columns to return and that could be making up a lot of the cost of the query. If it's a CLUSTERED index, or a NONCLUSTERED index that includes all the other fields you want to return in the query, then you should be fine.
Is Google Play Store supported in avd emulators?
Yes, you can enable/use Play Store on Android Emulator(AVD):
Before that you have to set up some prerequisites:
- Start Android SDK Manager and select Google Play Intel x86 Atom System Image (Recomended: because it will work comparatively faster) of your required android version (For Example: Android 7.1.1 or API 25)
[Note: Please keep all other thing as it is, if you are going to
install it for first time]
Or Install as the image below:
After download is complete Goto Tools->Manage AVDs...->Create from your Android SDK Manager
Check you have provided following option correctly. Not sure about internal and SD card storage. You can choose different. And Target must be your downloaded android version
Also check Google Play Intel Atom (x86) in CPU/ABI is provided
Click OK
Then Start your Android Emulator. There you will see the Android Play Store. See ---
Why use sys.path.append(path) instead of sys.path.insert(1, path)?
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
virtualenv
is a tool to create isolated Python environments.
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global site-packages
directory? For instance, on a shared host.
In all these cases, virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
That's why people consider insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.
How do I close an Android alertdialog
If you already use positive and negative button (like I do in my project) you can use Neutral Button to close the dialog.
I also noticed that in Android version >5 the dialog is closed by clicking outside of dialog window but in older version this is not happening.
ad.setNeutralButton("CLOSE", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// close dialog
}
});
Seaborn plots not showing up
To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.
In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline
would not work.
I was just having the same issue and suggest you use Jupyter Notebook for the visualization.
What do parentheses surrounding an object/function/class declaration mean?
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
Set maxlength in Html Textarea
simple way to do maxlength for textarea in html4 is:
<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>
Change the "100" to however many characters you want
Android SQLite: Update Statement
You can try:
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
Or
ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");
db.update("YOUR_TABLE", newValues, "id=6", null);
Or
ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");
String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);
Move view with keyboard using Swift
Swift 3 code
var activeField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func textFieldDidBeginEditing(_ textField: UITextField){
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if (self.activeField?.frame.origin.y)! >= keyboardSize.height {
self.view.frame.origin.y = keyboardSize.height - (self.activeField?.frame.origin.y)!
} else {
self.view.frame.origin.y = 0
}
}
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = 0
}
Python URLLib / URLLib2 POST
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
PHP check file extension
pathinfo
is what you're looking for
PHP.net
$file_parts = pathinfo($filename);
switch($file_parts['extension'])
{
case "jpg":
break;
case "exe":
break;
case "": // Handle file extension for files ending in '.'
case NULL: // Handle no file extension
break;
}
Count the number of times a string appears within a string
Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:
public int countTrue(string data)
{
string[] splitdata = data.Split(',');
var results = from p in splitdata
where p.Contains("true")
select p;
return results.Count();
}
How do I handle ImeOptions' done button click?
Kotlin Solution
The base way to handle it in Kotlin is:
edittext.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
Kotlin Extension
Use this to just call edittext.onDone{/*action*/}
in your main code. Makes your code far more readable and maintainable
fun EditText.onDone(callback: () -> Unit) {
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
}
Don't forget to add these options to your edittext
<EditText ...
android:imeOptions="actionDone"
android:inputType="text"/>
If you need inputType="textMultiLine"
support, read this post
Switch tabs using Selenium WebDriver with Java
public void switchToNextTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void closeAndSwitchToNextTab() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void switchToPreviousTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void closeTabAndReturn() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void switchToPreviousTabAndClose() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
driver.close();
}
Reading and writing to serial port in C on Linux
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
Set attribute without value
You can do it without jQuery!
Example:
_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
From MDN Element.setAttribute()
How to access at request attributes in JSP?
Just noting this here in case anyone else has a similar issue.
If you're directing a request directly to a JSP, using Apache Tomcat web.xml configuration, then ${requestScope.attr}
doesn't seem to work, instead ${param.attr}
contains the request attribute attr
.
"Press Any Key to Continue" function in C
Use the C Standard Library function getchar()
instead as getch()
is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getchar();
Here, getchar()
expects you to press the return key so the printf
statement should be press ENTER to continue
. Even if you press another key, you still need to press ENTER:
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
getchar();
If you are using Windows then you can use getch()
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
//if you press any character it will continue ,
//but this is not a standard c function.
char ch;
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
//here also if you press any other key will wait till pressing ENTER
scanf("%c",&ch); //works as getchar() but here extra variable is required.
Convert URL to File or Blob for FileReader.readAsDataURL
Here is my code using async awaits and promises
const getBlobFromUrl = (myImageUrl) => {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('GET', myImageUrl, true);
request.responseType = 'blob';
request.onload = () => {
resolve(request.response);
};
request.onerror = reject;
request.send();
})
}
const getDataFromBlob = (myBlob) => {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsDataURL(myBlob);
})
}
const convertUrlToImageData = async (myImageUrl) => {
try {
let myBlob = await getBlobFromUrl(myImageUrl);
console.log(myBlob)
let myImageData = await getDataFromBlob(myBlob);
console.log(myImageData)
return myImageData;
} catch (err) {
console.log(err);
return null;
}
}
export default convertUrlToImageData;
urlencoded Forward slash is breaking URL
Replace %2F with %252F after url encoding
PHP
function custom_http_build_query($query=array()){
return str_replace('%2F','%252F', http_build_query($query));
}
Handle the request via htaccess
.htaccess
RewriteCond %{REQUEST_URI} ^(.*?)(%252F)(.*?)$ [NC]
RewriteRule . %1/%3 [R=301,L,NE]
Resources
http://www.leakon.com/archives/865
Inserting multiple rows in mysql
INSERT
statements that use VALUES
syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
Vue.js - How to properly watch for nested data
None of the answer for me was working. Actually if you want to watch on nested data with Components being called multiple times. So they are called with different props to identify them.
For example <MyComponent chart="chart1"/> <MyComponent chart="chart2"/>
My workaround is to create an addionnal vuex state variable, that I manually update to point to the property that was last updated.
Here is a Vuex.ts implementation example:
export default new Vuex.Store({
state: {
hovEpacTduList: {}, // a json of arrays to be shared by different components,
// for example hovEpacTduList["chart1"]=[2,6,9]
hovEpacTduListChangeForChart: "chart1" // to watch for latest update,
// here to access "chart1" update
},
mutations: {
setHovEpacTduList: (state, payload) => {
state.hovEpacTduListChangeForChart = payload.chart // we will watch hovEpacTduListChangeForChart
state.hovEpacTduList[payload.chart] = payload.list // instead of hovEpacTduList, which vuex cannot watch
},
}
On any Component function to update the store:
const payload = {chart:"chart1", list: [4,6,3]}
this.$store.commit('setHovEpacTduList', payload);
Now on any Component to get the update:
computed: {
hovEpacTduListChangeForChart() {
return this.$store.state.hovEpacTduListChangeForChart;
}
},
watch: {
hovEpacTduListChangeForChart(chart) {
if (chart === this.chart) // the component was created with chart as a prop <MyComponent chart="chart1"/>
console.log("Update! for", chart, this.$store.state.hovEpacTduList[chart]);
},
},
Convert string to datetime in vb.net
As an alternative, if you put a space between the date and time, DateTime.Parse
will recognize the format for you. That's about as simple as you can get it. (If ParseExact
was still not being recognized)
Marker in leaflet, click event
The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:
Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.
So you could create a marker as suggested by the question above:
L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);
Then create the onClick function:
function onClick(e) {
alert(this.getLatLng());
}
Now anytime you mouseover that marker it will fire an alert of the current lat/long.
However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:
L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
console.log(e.latlng);
});
Here is the documentation: http://leafletjs.com/reference.html#events
Set adb vendor keys
I tried almost anything but no help...
Everytime was just this
? ~ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e unauthorized
However I've managed to connect device!
There is tutor, step by step.
- Remove existing adb keys on PC:
$ rm -v .android/adbkey*
.android/adbkey
.android/adbkey.pub
Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys
Now create new adb keypair
? ~ adb keygen .android/adbkey
adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey'
adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'
Manually copy from PC .android/adbkey.pub
(pubkic key) to Device on path /data/misc/adb/adb_keys
Reboot device and check adb devices
:
? ~ adb devices
List of devices attached
aeef5e4e device
Permissions of /data/misc/adb/adb_keys
are (766/-rwxrw-rw-)
on my device
How to bind WPF button to a command in ViewModelBase?
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
How to find and return a duplicate value in array
- Let's create duplication method that take array of elements as input
- In the method body, let's create 2 new array objects one is seen and another one is duplicate
- finally lets iterate through each object in given array and for every iteration lets find that object existed in seen array.
- if object existed in the seen_array, then it is considered as duplicate object and push that object into duplication_array
- if object not-existed in the seen, then it is considered as unique object and push that object into seen_array
let's demonstrate in Code Implementation
def duplication given_array
seen_objects = []
duplication_objects = []
given_array.each do |element|
duplication_objects << element if seen_objects.include?(element)
seen_objects << element
end
duplication_objects
end
Now call duplication method and output return result -
dup_elements = duplication [1,2,3,4,4,5,6,6]
puts dup_elements.inspect
ES6 map an array of objects, to return an array of objects with new keys
You just need to wrap object in ()
_x000D_
_x000D_
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_
What is the best way to auto-generate INSERT statements for a SQL Server table?
My contribution to the problem, a Powershell INSERT script generator that lets you script multiple tables without having to use the cumbersome SSMS GUI. Great for rapidly persisting "seed" data into source control.
- Save the below script as "filename.ps1".
- Make your own modifications to the areas under "CUSTOMIZE ME".
- You can add the list of tables to script in any order.
- You can open the script in Powershell ISE and hit the Play button, or simply execute the script in the Powershell command prompt.
By default, the INSERT script generated will be "SeedData.sql" under the same folder as the script.
You will need the SQL Server Management Objects assemblies installed, which should be there if you have SSMS installed.
Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
#CUSTOMIZE ME
$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true
$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
#CUSTOMIZE ME
$tables.Add($db.Tables["Category"].Urn)
$tables.Add($db.Tables["Product"].Urn)
$tables.Add($db.Tables["Vendor"].Urn)
[void]$scr.EnumScript($tables)
$sqlConnection.Close()
A hex viewer / editor plugin for Notepad++?
Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.
I used to use the Notepad++ plugin, but not anymore.
Typescript export vs. default export
Named export
In TS you can export with the export
keyword. It then can be imported via import {name} from "./mydir";
. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same dir
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import
, export
, and export default
are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.
Create a date time with month and day only, no year
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
How do I correctly clone a JavaScript object?
In ECMAScript 6 there is Object.assign method, which copies values of all enumerable own properties from one object to another. For example:
var x = {myProp: "value"};
var y = Object.assign({}, x);
But be aware that nested objects are still copied as reference.
Asyncio.gather vs asyncio.wait
A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.
I'll use this example to simulate a coroutine that will raise exceptions, sometimes -
import asyncio
import random
async def a_flaky_tsk(i):
await asyncio.sleep(i) # bit of fuzz to simulate a real-world example
if i % 2 == 0:
print(i, "ok")
else:
print(i, "crashed!")
raise ValueError
coros = [a_flaky_tsk(i) for i in range(10)]
await asyncio.gather(*coros)
outputs -
0 ok
1 crashed!
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
asyncio.run(main())
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
await asyncio.gather(*coros)
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
As you can see, the coros after index 1
never got to execute.
But await asyncio.wait(coros)
continues to execute tasks, even if some of them fail -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Ofcourse, this behavior can be changed for both by using -
asyncio.gather(..., return_exceptions=True)
or,
asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)
But it doesn't end here!
Notice:
Task exception was never retrieved
in the logs above.
asyncio.wait()
won't re-raise exceptions from the child tasks until you await
them individually. (The stacktrace in the logs are just messages, they cannot be caught!)
done, pending = await asyncio.wait(coros)
for tsk in done:
try:
await tsk
except Exception as e:
print("I caught:", repr(e))
Output -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
On the other hand, to catch exceptions with asyncio.gather()
, you must -
results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
if isinstance(result_or_exc, Exception):
print("I caught:", repr(result_or_exc))
(Same output as before)
Creating a class object in c++
First of all, both cases calls a constructor. If you write
Example *example = new Example();
then you are creating an object, call the constructor and retrieve a pointer to it.
If you write
Example example;
The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.
As for the singleton question, you must simple invoke your static method by writing:
Example *e = Singleton::getExample();
How to delete stuff printed to console by System.out.println()?
this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.
PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {}
}));
System.out.println("It will not print");
//To again enable it.
System.setOut(ps);
System.out.println("It will print");
How to import data from one sheet to another
Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.
NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)
Here is a link with the appropriate formulas.
The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))
- IF(A2="","", means if A2 is blank, return a blank value
- INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
- Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
- Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
- ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.
More information on the Index/Match formula
Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.
I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.
Good luck! Hope this helps.
Invalid column count in CSV input on line 1 Error
Your solution seems to assume you wish to create an entirely new table.
However if you want to add content to an already existing table, look up the structure of the table and note the number of columns (the id column, if you have one still counts->even though it may be auto increment/unique)
So if you table looks like this
id Name Age Sex
make sure your excel table looks like
A1 id B1 Name C1 Age D1 Sex
and now they both have 4 columns.
Also right under partial import, beside the skip the number of queries.... increase the number to skip the appropriate line. choosing 1 will skip automatically the first line. For those who may have headers in the excel files
How to use filesaver.js
Here is a guide to JSZIP to create ZIP files by JavaScript. To download files you need to have filesaver.js, You can include those libraries by:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>
Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.
<script type="text/javascript">
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "file.zip");
});
</script>
Now let's get in to deeper. Create an instance of JSZip.
var zip = new JSZip();
Add a file with a Hello World text:
zip.file("hello.txt", "Hello World\n");
Download the filie with name archive.zip
zip.generateAsync({type:"blob"}).then(function(zip) {
saveAs(zip, "archive.zip");
});
Read More from here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library
How do I convert a column of text URLs into active hyperlinks in Excel?
I had a list of numbers that feed into url's I want hotlinked.
For example I have Column A with question numbers (i.e., 2595692, 135171) and I want to turn these question numbers into hotlinks and to display only the question numbers.
So I built a text-only hyperlink pointing to Column A, and copied it down for all my question numbers:
="=HYPERLINK("&"""http""&"":"""&""&"&"&"""//stackoverflow.com/questions/"&A1&""""&","&A1&")"
Then I copy - paste value this column of text hyperlinks to another column.
You end up with a column of text that looks like the following:
=HYPERLINK("http"&":"&"//stackoverflow.com/questions/2595692",2595692)
Then I selected these pasted items and ran the F2Entry Macro that follows:
Sub F2Enter()
Dim cell As Range
Application.Calculation = xlCalculationManual
For Each cell In Selection
cell.Activate
cell = Trim(cell)
Next cell
Application.Calculation = xlCalculationAutomatic
EndSub
I then deleted the text entry column and Column A.
I ended up with a single column of hotlinked question numbers:
2595692
135171
etc.
Cheers
Check if one date is between two dates
I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
_x000D_
_x000D_
var dateFrom = "02/06/2013";_x000D_
var dateTo = "02/09/2013";_x000D_
_x000D_
var d1 = dateFrom.split("/");_x000D_
var d2 = dateTo.split("/");_x000D_
_x000D_
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11_x000D_
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]); _x000D_
_x000D_
_x000D_
_x000D_
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];_x000D_
_x000D_
dates.forEach(element => {_x000D_
let parts = element.split("/");_x000D_
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);_x000D_
if (date >= from && date < to) {_x000D_
console.log('dates in range', date);_x000D_
}_x000D_
})
_x000D_
_x000D_
_x000D_
How to wrap async function calls into a sync function in Node.js or Javascript?
There is a npm sync module also. which is used for synchronize the process of executing the query.
When you want to run parallel queries in synchronous way then node restrict to do that because it never wait for response. and sync module is much perfect for that kind of solution.
Sample code
/*require sync module*/
var Sync = require('sync');
app.get('/',function(req,res,next){
story.find().exec(function(err,data){
var sync_function_data = find_user.sync(null, {name: "sanjeev"});
res.send({story:data,user:sync_function_data});
});
});
/*****sync function defined here *******/
function find_user(req_json, callback) {
process.nextTick(function () {
users.find(req_json,function (err,data)
{
if (!err) {
callback(null, data);
} else {
callback(null, err);
}
});
});
}
reference link: https://www.npmjs.com/package/sync
select2 changing items dynamically
I've made an example for you showing how this could be done.
Notice the js but also that I changed #value into an input element
<input id="value" type="hidden" style="width:300px"/>
and that I am triggering the change
event for getting the initial values
$('#attribute').select2().on('change', function() {
$('#value').select2({data:data[$(this).val()]});
}).trigger('change');
Code Example
Edit:
In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen
class which positions the element way outside the page limits.
To fix this problem all that's needed is to add removeClass('select2-offscreen')
before applying select2 a second time on the same element.
$('#attribute').select2().on('change', function() {
$('#value').removeClass('select2-offscreen').select2({data:data[$(this).val()]});
}).trigger('change');
I've added a new Code Example to address this issue.
Sum values in a column based on date
Following up on Niketya's answer, there's a good explanation of Pivot Tables here:
http://peltiertech.com/WordPress/grouping-by-date-in-a-pivot-table/
For Excel 2007 you'd create the Pivot Table, make your Date column a Row Label, your Amount column a value. You'd then right click on one of the row labels (ie a date), right click and select Group. You'd then get the option to group by day, month, etc.
Personally that's the way I'd go.
If you prefer formulae, Smandoli's answer would get you most of the way there. To be able to use Sumif by day, you'd add a column with a formula like:
=DATE(YEAR(C1), MONTH(C1), DAY(C1))
where column C contains your datetimes.
You can then use this in your sumif.
jQuery datepicker, onSelect won't work
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect: function(value, date) {
window.location = 'day.jsp' ;
}
});
});
</script>
<div id="datepicker"></div>
I think you can try this .It works fine .
Multiple rows to one comma-separated value in Sql Server
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
Commands out of sync; you can't run this command now
I ran into this error using Doctrine DBAL QueryBuilder.
I created a query with QueryBuilder that uses column subselects, also created with QueryBuilder. The subselects were only created via $queryBuilder->getSQL()
and not executed. The error happened on creating the second subselect. By provisionally executing each subselect with $queryBuilder->execute()
before using $queryBuilder->getSQL()
, everything worked. It is as if the connection $queryBuilder->connection
remains in an invalid state for creating a new SQL before executing the currently prepared SQL, despite the new QueryBuilder instance on each subselect.
My solution was to write the subselects without QueryBuilder.
Wildcard string comparison in Javascript
I used the answer by @Spenhouet and added more "replacements"-possibilities than "*". For example "?". Just add your needs to the dict in replaceHelper
.
/**
* @param {string} str
* @param {string} rule
* checks match a string to a rule
* Rule allows * as zero to unlimited numbers and ? as zero to one character
* @returns {boolean}
*/
function matchRule(str, rule) {
const escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + replaceHelper(rule, {"*": "\\d*", "?": ".?"}, escapeRegex) + "$").test(str);
}
function replaceHelper(input, replace_dict, last_map) {
if (Object.keys(replace_dict).length === 0) {
return last_map(input);
}
const split_by = Object.keys(replace_dict)[0];
const replace_with = replace_dict[split_by];
delete replace_dict[split_by];
return input.split(split_by).map((next_input) => replaceHelper(next_input, replace_dict, last_map)).join(replace_with);
}
What is the syntax for an inner join in LINQ to SQL?
basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer
But for IQueryable<> it is not the case. Also join is less flexible.
Return value in a Bash function
I like to do the following if running in a script where the function is defined:
POINTER= # used for function return values
my_function() {
# do stuff
POINTER="my_function_return"
}
my_other_function() {
# do stuff
POINTER="my_other_function_return"
}
my_function
RESULT="$POINTER"
my_other_function
RESULT="$POINTER"
I like this, becase I can then include echo statements in my functions if I want
my_function() {
echo "-> my_function()"
# do stuff
POINTER="my_function_return"
echo "<- my_function. $POINTER"
}
TypeError: module.__init__() takes at most 2 arguments (3 given)
In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
How to implement a binary tree?
Binary Tree in Python
class Tree(object):
def __init__(self):
self.data=None
self.left=None
self.right=None
def insert(self, x, root):
if root==None:
t=node(x)
t.data=x
t.right=None
t.left=None
root=t
return root
elif x<root.data:
root.left=self.insert(x, root.left)
else:
root.right=self.insert(x, root.right)
return root
def printTree(self, t):
if t==None:
return
self.printTree(t.left)
print t.data
self.printTree(t.right)
class node(object):
def __init__(self, x):
self.x=x
bt=Tree()
root=None
n=int(raw_input())
a=[]
for i in range(n):
a.append(int(raw_input()))
for i in range(n):
root=bt.insert(a[i], root)
bt.printTree(root)
matplotlib: colorbars and its text labels
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
How do I set up the database.yml file in Rails?
The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.
The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.
Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template
). When deploying, the convention is to create this database.yml file in /shared/config
directly on the server.
With SVN: svn propset svn:ignore config "database.yml"
With Git: Add config/database.yml
to the .gitignore file or with git-extra git ignore config/database.yml
... and now, some examples:
SQLite
adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000
MYSQL
adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password:
socket: /tmp/mysql.sock
pool: 5
timeout: 5000
MongoDB with MongoID (called mongoid.yml, but basically the same thing)
host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
# - host: slave1.local
# port: 27018
# - host: slave2.local
# port: 27019
Incrementing in C++ - When to use x++ or ++x?
The most important thing to keep in mind, imo, is that x++ needs to return the value before the increment actually took place -- therefore, it has to make a temporary copy of the object (pre increment). This is less effecient than ++x, which is incremented in-place and returned.
Another thing worth mentioning, though, is that most compilers will be able to optimize such unnecessary things away when possible, for instance both options will lead to same code here:
for (int i(0);i<10;++i)
for (int i(0);i<10;i++)
Chrome not rendering SVG referenced via <img> tag
Adding the width attribute to the [svg] tag (by editing the svg source XML) worked for me:
eg:
<!-- This didn't render -->
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
...
</svg>
<!-- This did -->
<svg version="1.1" baseProfile="full" width="1000" xmlns="http://www.w3.org/2000/svg">
...
</svg>
Laravel whereIn OR whereIn
You could have searched just for whereIn
function in the core to see that. Here you are. This must answer all your questions
/**
* Add a "where in" clause to the query.
*
* @param string $column
* @param mixed $values
* @param string $boolean
* @param bool $not
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
$type = $not ? 'NotIn' : 'In';
// If the value of the where in clause is actually a Closure, we will assume that
// the developer is using a full sub-select for this "in" statement, and will
// execute those Closures, then we can re-construct the entire sub-selects.
if ($values instanceof Closure)
{
return $this->whereInSub($column, $values, $boolean, $not);
}
$this->wheres[] = compact('type', 'column', 'values', 'boolean');
$this->bindings = array_merge($this->bindings, $values);
return $this;
}
Look that it has a third boolean param. Good luck.
How do I set the selected item in a drop down box
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
How to round a number to n decimal places in Java
new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);
will get you a BigDecimal
. To get the string out of it, just call that BigDecimal
's toString
method, or the toPlainString
method for Java 5+ for a plain format string.
Sample program:
package trials;
import java.math.BigDecimal;
public class Trials {
public static void main(String[] args) {
int yourScale = 10;
System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP));
}
get list of pandas dataframe columns based on data type
If you want a list of columns of a certain type, you can use groupby
:
>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
A B C D E
0 1 2.3456 c d 78
[1 rows x 5 columns]
>>> df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// This line pops up the error
destination.nameLabel.text = item.name
}
}
}
Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.
So I solved it this way:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DestinationVC{
if let item = sender as? DataItem{
// Created this method in the destination Controller to update its outlets after it's being initialized and loaded
destination.updateView(itemData: item)
}
}
}
Destination Controller:
// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""
// Outlets
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameLabel.text = name
}
func updateView(itemDate: ObjectModel) {
name = itemDate.name
}
I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.
How to set layout_gravity programmatically?
I use someting like that: (Xamarin and C# code)
LinearLayout linLayout= new LinearLayout(this);
linLayout.SetGravity(GravityFlags.Center);
TextView txtView= new TextView(this);
linLayout.AddView(txtView);
the SetGravity puts my textView in the center of the layout.
So SetGravity layout property refer to layout content
C++ correct way to return pointer to array from function
you can (sort of) return an array
instead of
int m1[5] = {1, 2, 3, 4, 5};
int m2[5] = {6, 7, 8, 9, 10};
int* m3 = test(m1, m2);
write
struct mystruct
{
int arr[5];
};
int m1[5] = {1, 2, 3, 4, 5};
int m2[5] = {6, 7, 8, 9, 10};
mystruct m3 = test(m1,m2);
where test looks like
struct mystruct test(int m1[5], int m2[5])
{
struct mystruct s;
for (int i = 0; i < 5; ++i ) s.arr[i]=m1[i]+m2[i];
return s;
}
not very efficient since one is copying it delivers a copy of the array
Export Postgresql table data using pgAdmin
In the pgAdmin4, Right click on table select backup like this
After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.
Display milliseconds in Excel
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
How do I resolve a path relative to an ASP.NET MVC 4 application root?
In your controller use:
var path = HttpContext.Server.MapPath("~/Data/data.html");
This allows you to test the controller with Moq like so:
var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;
How do I delete a Git branch locally and remotely?
Executive Summary
$ git push -d <remote_name> <branch_name>
$ git branch -d <branch_name>
Note that in most cases the remote name is origin
.
In such a case you'll have to use the command like so.
$ git push -d origin <branch_name>
Delete Local Branch
To delete the local branch use one of the following:
$ git branch -d branch_name
$ git branch -D branch_name
Note: The -d
option is an alias for --delete
, which only deletes the branch if it has already been fully merged in its upstream branch. You could also use -D
, which is an alias for --delete --force
, which deletes the branch "irrespective of its merged status." [Source: man git-branch
]
Also note that git branch -d branch_name
will fail if you are currently
in the branch you want to remove. The message starts with
error: Cannot delete the branch 'branch_name'
. If so, first switch
to some other branch, for example: git checkout master
.
Delete Remote Branch [Updated on 8-Sep-2017]
As of Git v1.7.0, you can delete a remote branch using
$ git push <remote_name> --delete <branch_name>
which might be easier to remember than
$ git push <remote_name> :<branch_name>
which was added in Git v1.5.0 "to delete a remote branch or a tag."
Starting on Git v2.8.0 you can also use git push
with the -d
option as an alias for --delete
.
Therefore, the version of Git you have installed will dictate whether you need to use the easier or harder syntax.
Delete Remote Branch [Original Answer from 5-Jan-2010]
From Chapter 3 of Pro Git by Scott Chacon:
Deleting Remote Branches
Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s master branch (or whatever branch your stable code-line is in). You can delete a remote branch using the rather obtuse syntax git push [remotename] :[branch]
. If you want to delete your server-fix branch from the server, you run the following:
$ git push origin :serverfix
To [email protected]:schacon/simplegit.git
- [deleted] serverfix
Boom. No more branches on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the git push [remotename] [localbranch]:[remotebranch]
syntax that we went over a bit earlier. If you leave off the [localbranch]
portion, then you’re basically saying, “Take nothing on my side and make it be [remotebranch]
.”
I issued git push origin: bugfix
and it worked beautifully. Scott Chacon was right—I will want to dog ear that page (or virtually dog ear by answering this on Stack Overflow).
Then you should execute this on other machines
# Fetch changes from all remotes and locally delete
# remote deleted branches/tags etc
# --prune will do the job :-;
git fetch --all --prune
to propagate changes.
How to make an introduction page with Doxygen
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
Using Node.JS, how do I read a JSON file into (server) memory?
If you are looking for a complete solution for Async
loading a JSON file from Relative Path
with Error Handling
// Global variables
// Request path module for relative path
const path = require('path')
// Request File System Module
var fs = require('fs');
// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
console.log("Got a GET request for list of users");
// Create a relative path URL
let reqPath = path.join(__dirname, '../mock/users.json');
//Read JSON from relative path of this file
fs.readFile(reqPath , 'utf8', function (err, data) {
//Handle Error
if(!err) {
//Handle Success
console.log("Success"+data);
// Parse Data to JSON OR
var jsonObj = JSON.parse(data)
//Send back as Response
res.end( data );
}else {
//Handle Error
res.end("Error: "+err )
}
});
})
Directory Structure:
Python DNS module import error
I ran into the same issue with dnspython.
My solution was to build the source from their official GitHub project.
So my steps were:
git clone https://github.com/rthalley/dnspython
cd dnspython/
python setup.py install
After doing this, I was able to import the dns
module.
EDIT
It seems the pip install doesn't work for this module. Install from source as described.
SQL ORDER BY multiple columns
It depends on the size of your database.
SQL is based on the SET theory: there is no order inherently used when querying a table.
So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.
If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.
How to write a:hover in inline CSS?
So this isn't quite what the user was looking for, but I found this question searching for an answer and came up with something sort of related. I had a bunch of repeating elements that needed a new color/hover for a tab within them. I use handlebars, which is key to my solution, but other templateing languages may also work.
I defined some colors and passed them into the handlebars template for each element. At the top of the template I defined a style tag, and put in my custom class and hover color.
<style type="text/css">
.{{chart.type}}-tab-hover:hover {
background-color: {{chart.chartPrimaryHighlight}} !important;
}
</style>
Then I used the style in the template:
<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
Payouts
</span>
You may not need the !important
How to make picturebox transparent?
Just use the Form Paint method and draw every Picturebox on it, it allows transparency :
private void frmGame_Paint(object sender, PaintEventArgs e)
{
DoubleBuffered = true;
for (int i = 0; i < Controls.Count; i++)
if (Controls[i].GetType() == typeof(PictureBox))
{
var p = Controls[i] as PictureBox;
p.Visible = false;
e.Graphics.DrawImage(p.Image, p.Left, p.Top, p.Width, p.Height);
}
}
How to create correct JSONArray in Java using JSONObject
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put
vs add
here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put
method and in java 7 javax.json contains the add
method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
taking input of a string word by word
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
Where is Java Installed on Mac OS X?
Java package structure of Mac OS is a bit different from Windows. Don't be upset for this as a developer just needs to set PATH
and JAVA_HOME
.
So in .bash_profile
set JAVA_HOME
and PATH
as below. This example is for Java 6:
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
export PATH=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin:$PATH
How to take off line numbers in Vi?
Display line numbers:
:set nu
Stop showing the line numbers:
:set nonu
Its short for :set nonumber
ps. These commands are to be run in normal mode.
How can I add the new "Floating Action Button" between two widgets/layouts
Add this to your gradle file
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.1'
}
This to your activity_main.xml
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/viewOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.6"
android:background="@android:color/holo_blue_light"
android:orientation="horizontal"/>
<LinearLayout
android:id="@+id/viewTwo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.4"
android:background="@android:color/holo_orange_light"
android:orientation="horizontal"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/floatingButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:clickable="true"
android:src="@drawable/ic_done"
app:layout_anchor="@id/viewOne"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#FF0000"
app:rippleColor="#FFF" />
</android.support.design.widget.CoordinatorLayout>
You can find the full example with android studio project to download at http://www.ahotbrew.com/android-floating-action-button/
How to choose between Hudson and Jenkins?
As chmullig wrote, use Jenkins. Some additional points:
...and a little background info:
The creator of Hudson, Kohsuke Kawaguchi, started the project on his free time, even if he was working for Sun Microsystems and later paid by them to develop it further. As @erickson noted at another SO question,
[Hudson/Jenkins] is the product of a single genius
intellect—Kohsuke Kawaguchi. Because
of that, it's consistent, coherent,
and rock solid.
After the acquisition by Oracle, Kohsuke didn't hang around for long (due to lack of monitors...? ;-]), and went to work for CloudBees. What started in late 2010 as conflict over tools between the dev community and Oracle and ended in the rename/fork/split is well documented in the links chmullig provided. To me, that whole conundrum speaks, perhaps more than anything else, to Oracle's utter inability or unwillingness to sponsor an open-source project in a way that keeps all parties (Oracle, developers, users) happy. It's not in their DNA or something, as we've seen in other cases too.
Given all of the above, I would personally follow Kohsuke and other core developers in this matter, and go with Jenkins.
Questions every good Java/Java EE Developer should be able to answer?
You said "Good","Developer". Here are my 2 cents too.. :)
- What does a "checked exception" mean?
- Which one is better to use and when: Assertions or Exceptions to handle unexpected conditions?
- Why String class is final? (or is it not? ;) )
- are the wait, notify and notifyAll methods in Object class?
- Why isn't Thread class final? Why would I extend Thread, ever?
- Why there are two Date classes; one in java.util package and another in java.sql?
- What happens if an exception is thrown in finally block? Is the remaining finally executed or not?
- There is a garbage collector alright, but then is memory leak totally absent in a Java applications? If not, how so?
For J2EE:
- Is it good to have instance/static variables in a servlet? Why not? Then where do you store "state"?
- continuing on above question: what & where is a "state" for a (web) application?
- What happens if I started creating/closing DB connections in "JSP"?
- What are the ways to handle JSP exceptions? try-catch? Hmmm.. is there anything else?
I can think many, many, many more of 'em but this'll do for now :)
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How to get current user in asp.net core
I have to say I was quite surprised that HttpContext is null inside the constructor. I'm sure it's for performance reasons. Have confirmed that using IPrincipal
as described below does get it injected into the constructor. Its essentially doing the same as the accepted answer, but in a more interfacey-way.
For anyone finding this question looking for an answer to the generic "How to get current user?" you can just access User
directly from Controller.User
. But you can only do this inside action methods (I assume because controllers don't only run with HttpContexts and for performance reasons).
However - if you need it in the constructor (as OP did) or need to create other injectable objects that need the current user then the below is a better approach:
Inject IPrincipal to get user
First meet IPrincipal
and IIdentity
public interface IPrincipal
{
IIdentity Identity { get; }
bool IsInRole(string role);
}
public interface IIdentity
{
string AuthenticationType { get; }
bool IsAuthenticated { get; }
string Name { get; }
}
IPrincipal
and IIdentity
represents the user and username. Wikipedia will comfort you if 'Principal' sounds odd.
Important to realize that whether you get it from IHttpContextAccessor.HttpContext.User
, ControllerBase.User
or ControllerBase.HttpContext.User
you're getting an object that is guaranteed to be a ClaimsPrincipal
object which implements IPrincipal
.
There's no other type of User that ASP.NET uses for User
right now, (but that's not to say other something else couldn't implement IPrincipal
).
So if you have something which has a dependency of 'the current user name' that you want injected you should be injecting IPrincipal
and definitely not IHttpContextAccessor
.
Important: Don't waste time injecting IPrincipal
directly to your controller, or action method - it's pointless since User
is available to you there already.
In startup.cs
:
// Inject IPrincipal
services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
Then in your DI object that needs the user you just inject IPrincipal
to get the current user.
The most important thing here is if you're doing unit tests you don't need to send in an HttpContext
, but only need to mock something that represents IPrincipal
which can just be ClaimsPrincipal
.
One extra important thing that I'm not 100% sure about. If you need to access the actual claims from ClaimsPrincipal
you need to cast IPrincipal
to ClaimsPrincipal
. This is fine since we know 100% that at runtime it's of that type (since that's what HttpContext.User
is). I actually like to just do this in the constructor since I already know for sure any IPrincipal
will be a ClaimsPrincipal
.
If you're doing mocking, just create a ClaimsPrincipal
directly and pass it to whatever takes IPrincipal
.
Exactly why there is no interface for IClaimsPrincipal
I'm not sure. I assume MS decided that ClaimsPrincipal
was just a specialized 'collection' that didn't warrant an interface.
How do I call a non-static method from a static method in C#?
Static method never allows a non-static method call directly.
Reason: Static method belongs to its class only, and to nay object or any instance.
So, whenever you try to access any non-static method from static method inside the same class: you will receive:
"An object reference is required for the non-static field, method or property".
Solution: Just declare a reference like:
public class <classname>
{
static method()
{
new <classname>.non-static();
}
non-static method()
{
}
}
How can I read a text file in Android?
First you store your text file in to raw folder.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
Bootstrap dropdown not working
Add following lines within the body tags.
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files
as needed -->
<script src="js/bootstrap.min.js"></script>
Oracle date "Between" Query
As APC rightly pointed out, your start_date column appears to be a TIMESTAMP but it could be a TIMESTAMP WITH LOCAL TIMEZONE or TIMESTAMP WITH TIMEZONE datatype too. These could well influence any queries you were doing on the data if your database server was in a different timezone to yourself. However, let's keep this simple and assume you are in the same timezone as your server. First, to give you the confidence, check that the start_date is a TIMESTAMP data type.
Use the SQLPlus DESCRIBE command (or the equivalent in your IDE) to verify this column is a TIMESTAMP data type.
eg
DESCRIBE mytable
Should report :
Name Null? Type
----------- ----- ------------
NAME VARHAR2(20)
START_DATE TIMESTAMP
If it is reported as a Type = TIMESTAMP then you can query your date ranges with simplest TO_TIMESTAMP date conversion, one which requires no argument (or picture).
We use TO_TIMESTAMP to ensure that any index on the START_DATE column is considered by the optimizer. APC's answer also noted that a function based index could have been created on this column and that would influence the SQL predicate but we cannot comment on that in this query. If you want to know how to find out what indexes have been applied to table, post another question and we can answer that separately.
So, assuming there is an index on start_date, which is a TIMESTAMP datatype and you want the optimizer to consider it, your SQL would be :
select * from mytable where start_date between to_timestamp('15-JAN-10') AND to_timestamp('17-JAN-10')+.9999999
+.999999999 is very close to but isn't quite 1 so the conversion of 17-JAN-10 will be as close to midnight on that day as possible, therefore you query returns both rows.
The database will see the BETWEEN as from 15-JAN-10 00:00:00:0000000 to 17-JAN-10 23:59:59:99999 and will therefore include all dates from 15th,16th and 17th Jan 2010 whatever the time component of the timestamp.
Hope that helps.
Dazzer
Draw Circle using css alone
Yep, draw a box and give it a border radius that is half the width of the box:
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
}
Working demo:
http://jsfiddle.net/DsW9h/1/
_x000D_
_x000D_
#circle {_x000D_
background: #f00;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div id="circle"></div>
_x000D_
_x000D_
_x000D_
Missing Authentication Token while accessing API Gateway?
For the record, if you wouldn't be using credentials, this error also shows when you are setting the request validator in your POST/PUT method to "validate body, query string parameters and HEADERS", or the other option "validate query string parameters and HEADERS"....in that case it will look for the credentials on the header and reject the request. To sum it up, if you don't intend to send credentials and want to keep it open you should not set that option in request validator(set it to either NONE or to validate body)
WPF binding to Listbox selectedItem
First off, you need to implement INotifyPropertyChanged
interface in your view model and raise the PropertyChanged
event in the setter of the Rule
property. Otherwise no control that binds to the SelectedRule
property will "know" when it has been changed.
Then, your XAML
<TextBlock Text="{Binding Path=SelectedRule.Name}" />
is perfectly valid if this TextBlock
is outside the ListBox
's ItemTemplate
and has the same DataContext
as the ListBox
.
No log4j2 configuration file found. Using default configuration: logging only errors to the console
I am working on TestNG Maven project, This worked for me by adding <resources>
tag in pom.xml
, this happens to be the path of my custom configuration file log4j2.xml
.
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<resources>
<resource>
<directory>src/main/java/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
How to pass a type as a method parameter in Java
If you want to pass the type, than the equivalent in Java would be
java.lang.Class
If you want to use a weakly typed method, then you would simply use
java.lang.Object
and the corresponding operator
instanceof
e.g.
private void foo(Object o) {
if(o instanceof String) {
}
}//foo
However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.
The real question is what you actually want to achieve here, otherwise it is difficult to answer:
Or is there a better way?
Command line tool to dump Windows DLL version?
For some DLLs I found version info manually with objdump
in .rsrc. With objdump -s -j .rsrc zlib1.dll
:
zlib1.dll: file format pei-x86-64
Contents of section .rsrc:
62e9e000 00000000 00000000 00000000 00000100 ................
62e9e010 10000000 18000080 00000000 00000000 ................
62e9e020 00000000 00000100 01000000 30000080 ............0...
62e9e030 00000000 00000000 00000000 00000100 ................
62e9e040 09040000 48000000 58e00100 34030000 ....H...X...4...
62e9e050 00000000 00000000 34033400 00005600 ........4.4...V.
62e9e060 53005f00 56004500 52005300 49004f00 S._.V.E.R.S.I.O.
62e9e070 4e005f00 49004e00 46004f00 00000000 N._.I.N.F.O.....
62e9e080 bd04effe 00000100 02000100 00000b00 ................
62e9e090 02000100 00000b00 3f000000 00000000 ........?.......
62e9e0a0 04000000 02000000 00000000 00000000 ................
62e9e0b0 00000000 94020000 01005300 74007200 ..........S.t.r.
62e9e0c0 69006e00 67004600 69006c00 65004900 i.n.g.F.i.l.e.I.
62e9e0d0 6e006600 6f000000 70020000 01003000 n.f.o...p.....0.
62e9e0e0 34003000 39003000 34004500 34000000 4.0.9.0.4.E.4...
62e9e0f0 64001e00 01004600 69006c00 65004400 d.....F.i.l.e.D.
62e9e100 65007300 63007200 69007000 74006900 e.s.c.r.i.p.t.i.
62e9e110 6f006e00 00000000 7a006c00 69006200 o.n.....z.l.i.b.
62e9e120 20006400 61007400 61002000 63006f00 .d.a.t.a. .c.o.
62e9e130 6d007000 72006500 73007300 69006f00 m.p.r.e.s.s.i.o.
62e9e140 6e002000 6c006900 62007200 61007200 n. .l.i.b.r.a.r.
62e9e150 79000000 2e000700 01004600 69006c00 y.........F.i.l.
62e9e160 65005600 65007200 73006900 6f006e00 e.V.e.r.s.i.o.n.
62e9e170 00000000 31002e00 32002e00 31003100 ....1...2...1.1.
62e9e180 00000000 34000a00 01004900 6e007400 ....4.....I.n.t.
62e9e190 65007200 6e006100 6c004e00 61006d00 e.r.n.a.l.N.a.m.
62e9e1a0 65000000 7a006c00 69006200 31002e00 e...z.l.i.b.1...
62e9e1b0 64006c00 6c000000 7c002c00 01004c00 d.l.l...|.,...L.
62e9e1c0 65006700 61006c00 43006f00 70007900 e.g.a.l.C.o.p.y.
62e9e1d0 72006900 67006800 74000000 28004300 r.i.g.h.t...(.C.
62e9e1e0 29002000 31003900 39003500 2d003200 ). .1.9.9.5.-.2.
62e9e1f0 30003100 37002000 4a006500 61006e00 0.1.7. .J.e.a.n.
62e9e200 2d006c00 6f007500 70002000 47006100 -.l.o.u.p. .G.a.
62e9e210 69006c00 6c007900 20002600 20004d00 i.l.l.y. .&. .M.
62e9e220 61007200 6b002000 41006400 6c006500 a.r.k. .A.d.l.e.
62e9e230 72000000 3c000a00 01004f00 72006900 r...<.....O.r.i.
62e9e240 67006900 6e006100 6c004600 69006c00 g.i.n.a.l.F.i.l.
62e9e250 65006e00 61006d00 65000000 7a006c00 e.n.a.m.e...z.l.
62e9e260 69006200 31002e00 64006c00 6c000000 i.b.1...d.l.l...
62e9e270 2a000500 01005000 72006f00 64007500 *.....P.r.o.d.u.
62e9e280 63007400 4e006100 6d006500 00000000 c.t.N.a.m.e.....
62e9e290 7a006c00 69006200 00000000 32000700 z.l.i.b.....2...
62e9e2a0 01005000 72006f00 64007500 63007400 ..P.r.o.d.u.c.t.
62e9e2b0 56006500 72007300 69006f00 6e000000 V.e.r.s.i.o.n...
62e9e2c0 31002e00 32002e00 31003100 00000000 1...2...1.1.....
62e9e2d0 78003000 01004300 6f006d00 6d006500 x.0...C.o.m.m.e.
62e9e2e0 6e007400 73000000 46006f00 72002000 n.t.s...F.o.r. .
62e9e2f0 6d006f00 72006500 20006900 6e006600 m.o.r.e. .i.n.f.
62e9e300 6f007200 6d006100 74006900 6f006e00 o.r.m.a.t.i.o.n.
62e9e310 20007600 69007300 69007400 20006800 .v.i.s.i.t. .h.
62e9e320 74007400 70003a00 2f002f00 77007700 t.t.p.:././.w.w.
62e9e330 77002e00 7a006c00 69006200 2e006e00 w...z.l.i.b...n.
62e9e340 65007400 2f000000 44000000 01005600 e.t./...D.....V.
62e9e350 61007200 46006900 6c006500 49006e00 a.r.F.i.l.e.I.n.
62e9e360 66006f00 00000000 24000400 00005400 f.o.....$.....T.
62e9e370 72006100 6e007300 6c006100 74006900 r.a.n.s.l.a.t.i.
62e9e380 6f006e00 00000000 0904e404 00000000 o.n.............
How do I update pip itself from inside my virtual environment?
Single Line Python Program
The best way I have found is to write a single line program that downloads and runs the official get-pip script. See below for the code.
The official docs recommend using curl to download the get-pip script, but since I work on windows and don't have curl installed I prefer using python itself to download and run the script.
Here is the single line program that can be run via the command line using Python 3:
python -c "import urllib.request; exec(urllib.request.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"
This line gets the official "get-pip.py" script as per the installation notes and executes the script with the "exec" command.
For Python2 you would replace "urllib.request" with "urllib2":
python -c "import urllib2; exec(urllib2.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"
Precautions
It's worth noting that running any python script blindly is inherently dangerous. For this reason, the official instructions recommend downloading the script and inspecting it before running.
That said, many people don't actually inspect the code and just run it. This one-line program makes that easier.
What is the difference between a strongly typed language and a statically typed language?
Both are poles on two different axis:
- strongly typed vs. weakly typed
- statically typed vs. dynamically typed
Strongly typed means, a will not be automatically converted from one type to another. Weakly typed is the opposite: Perl can use a string like "123"
in a numeric context, by automatically converting it into the int 123
. A strongly typed language like python will not do this.
Statically typed means, the compiler figures out the type of each variable at compile time. Dynamically typed languages only figure out the types of variables at runtime.
In AngularJS, what's the difference between ng-pristine and ng-dirty?
As already stated in earlier answers, ng-pristine
is for indicating that the field has not been modified, whereas ng-dirty
is for telling it has been modified. Why need both?
Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty
and ng-pristine
together:
<form name="myForm">
<input name="email" ng-model="data.email" ng-required="!data.phone">
<div class="error"
ng-show="myForm.email.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.email.$invalid && myForm.email.$dirty">
E-mail is invalid
</div>
<input name="phone" ng-model="data.phone" ng-required="!data.email">
<div class="error"
ng-show="myForm.phone.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
Phone is invalid
</div>
</form>
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();
Here's what I've been doing:
public void displayError(final String errorText) {
Runnable doDisplayError = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), errorText, Toast.LENGTH_LONG).show();
}
};
messageHandler.post(doDisplayError);
}
That should allow the method to be called from either thread.
Where messageHandler is declared in the activity as ..
Handler messageHandler = new Handler();
Get index of a key in json
In principle, it is wrong to look for an index of a key. Keys of a hash map are unordered, you should never expect specific order.
Android Text over image
You may want to take if from a diffrent side: It seems easier to have a TextView with a drawable on the background:
<TextView
android:id="@+id/text"
android:background="@drawable/rounded_rectangle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</TextView>
How to check variable type at runtime in Go language
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) {
switch v := param.(type) {
default:
fmt.Printf("unexpected type %T", v)
case uint64:
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
case string:
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
}
}
TypeError: got multiple values for argument
Simply put you can't do the following:
class C(object):
def x(self, y, **kwargs):
# Which y to use, kwargs or declaration?
pass
c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS
Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.
Equivalent of Math.Min & Math.Max for Dates?
There's no built in method to do that. You can use the expression:
(date1 > date2 ? date1 : date2)
to find the maximum of the two.
You can write a generic method to calculate Min
or Max
for any type (provided that Comparer<T>.Default
is set appropriately):
public static T Max<T>(T first, T second) {
if (Comparer<T>.Default.Compare(first, second) > 0)
return first;
return second;
}
You can use LINQ too:
new[]{date1, date2, date3}.Max()
paint() and repaint() in Java
The paint()
method supports painting via a Graphics object.
The repaint()
method is used to cause paint()
to be invoked by the AWT painting thread.
How to retrieve a single file from a specific revision in Git?
Using git show $REV:$FILE
as it was already pointed out by others is probably the right answer. I'm posting another answer because when I tried this method, I sometimes got the following error from git:
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem occurs when parts of the path to the file are a symbolic link. In those cases, the git show $REV:$FILE
method will not work. Steps to reproduce:
$ git init .
$ mkdir test
$ echo hello > test/foo
$ ln -s test link
$ git add .
$ git commit -m "initial commit"
$ cat link/foo
hello
$ git show HEAD:link/foo
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem is, that utilities like realpath
don't help here, because the symlink might not exist in the current commit anymore. I don't know about a good general solution. In my case, I knew that the symlink could only exist in the first component of the path, so I solved the problem by using the git show $REV:$FILE
method twice. This works, because when git show $REV:$FILE
is used on a symlink, then its target gets printed:
$ git show HEAD:link
test
Whereas with directories, the command will output a header, followed by the directory content:
$ git show HEAD:test
tree HEAD:test
foo
So in my case, I just checked the output of the first call to git show $REV:$FILE
and if it was only a single line, then I replaced the first component of my path with the result to resolve the symlink through git.
Setting environment variables in Linux using Bash
export VAR=value
will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'
. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR"
.
What is the difference between required and ng-required?
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
What is and how to fix System.TypeInitializationException error?
I have the error of system.typeintialzationException, which is due to when I tried to move the file like:
File.Move(DestinationFilePath, SourceFilePath)
That error was due to I had swapped the path actually, correct one is:
File.Move(SourceFilePath, DestinationFilePath)
Responsive css styles on mobile devices ONLY
I had to solve a similar problem--I wanted certain styles to only apply to mobile devices in landscape mode. Essentially the fonts and line spacing looked fine in every other context, so I just needed the one exception for mobile landscape. This media query worked perfectly:
@media all and (max-width: 600px) and (orientation:landscape)
{
/* styles here */
}
Is there a CSS selector by class prefix?
You can't do this no. There is one attribute selector that matches exactly or partial until a - sign, but it wouldn't work here because you have multiple attributes. If the class name you are looking for would always be first, you could do this:
<html>
<head>
<title>Test Page</title>
<style type="text/css">
div[class|=status] { background-color:red; }
</style>
</head>
<body>
<div id='A' class='status-important bar-class'>A</div>
<div id='B' class='bar-class'>B</div>
<div id='C' class='status-low-priority bar-class'>C</div>
</body>
</html>
Note that this is just to point out which CSS attribute selector is the closest, it is not recommended to assume class names will always be in front since javascript could manipulate the attribute.
How to remove all debug logging calls before building the release version of an Android app?
ProGuard will do it for you on your release build and now the good news from android.com:
http://developer.android.com/tools/help/proguard.html
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.
ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
This document describes how to enable and configure ProGuard as well as use the retrace tool to decode obfuscated stack traces
Where should I put the log4j.properties file?
I know it's a bit late to answer this question, and maybe you already found the solution, but I'm posting the solution I found (after I googled a lot) so it may help a little:
- Put log4j.properties under WEB-INF\classes of the project as mentioned previously in this thread.
- Put log4j-xx.jar under WEB-INF\lib
- Test if log4j was loaded: add
-Dlog4j.debug
@ the end of your java options of tomcat
Hope this will help.
rgds
No suitable records were found verify your bundle identifier is correct
I got the error when uploading a React Native Expo bundle to Apple App Store Connect using Transporter. The problem was that I had transferred the app from my personal account to our company account but forgot to sign into our company account in Transporter.
Click the profile icon in the top right corner and sign in to the correct account that you are using in your bundle.
'python' is not recognized as an internal or external command
Option 1 : Select on add environment var during installation
Option 2 : Go to C:\Users-> AppData (hidden file) -> Local\Programs\Python\Python38-32(depends on version installed)\Scripts
Copy path and add to env vars path.
For me this path worked : C:\Users\Username\AppData\Local\Programs\Python\Python38-32\Scripts
c# replace \" characters
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
What is time_t ultimately a typedef to?
Standards
William Brendel quoted Wikipedia, but I prefer it from the horse's mouth.
C99 N1256 standard draft 7.23.1/3 "Components of time" says:
The types declared are size_t (described in 7.17) clock_t and time_t which are arithmetic types capable of representing times
and 6.2.5/18 "Types" says:
Integer and floating types are collectively called arithmetic types.
POSIX 7 sys_types.h says:
[CX] time_t shall be an integer type.
where [CX]
is defined as:
[CX] Extension to the ISO C standard.
It is an extension because it makes a stronger guarantee: floating points are out.
gcc one-liner
No need to create a file as mentioned by Quassnoi:
echo | gcc -E -xc -include 'time.h' - | grep time_t
On Ubuntu 15.10 GCC 5.2 the top two lines are:
typedef long int __time_t;
typedef __time_t time_t;
Command breakdown with some quotes from man gcc
:
-E
: "Stop after the preprocessing stage; do not run the compiler proper."
-xc
: Specify C language, since input comes from stdin which has no file extension.
-include file
: "Process file as if "#include "file"" appeared as the first line of the primary source file."
-
: input from stdin
Using context in a fragment
Since API level 23 there is getContext()
but if you want to support older versions you can use getActivity().getApplicationContext()
while I still recommend using the support version of Fragment
which is android.support.v4.app.Fragment
.