Automated Python to Java translation
Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc
In fact, this is probably pretty easy to knock up in Python.
I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.
Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.
Is there an effective tool to convert C# code to Java code?
Although this is an old-ish question, take a look at xmlVM http://www.xmlvm.org/clr2jvm, I'm not sure if it's mature enough yet, although it has been around for several years now. XMLvm was made, I believe, primarily for translating Android Java apps to the iPhone, however, its XML-code-translation-based framework is flexible enough to do other combinations (see the diagrams on the site).
As for a reason to do this conversion, maybe there is a need to 'hijack' some of the highly abundant oss code out there and use it within his/their own [Java] project.
Cheers
Rich
How to convert C++ Code to C
A compiler consists of two major blocks: the 'front end' and the 'back end'.
The front end of a compiler analyzes the source code and builds some form of a 'intermediary representation' of said source code which is much easier to analyze by a machine algorithm than is the source code (i.e. whereas the source code e.g. C++ is designed to help the human programmer to write code, the intermediary form is designed to help simplify the algorithm that analyzes said intermediary form easier).
The back end of a compiler takes the intermediary form and then converts it to a 'target language'.
Now, the target language for general-use compilers are assembler languages for various processors, but there's nothing to prohibit a compiler back end to produce code in some other language, for as long as said target language is (at least) as flexible as a general CPU assembler.
Now, as you can probably imagine, C is definitely as flexible as a CPU's assembler, such that a C++ to C compiler is really no problem to implement from a technical pov.
So you have: C++ ---frontEnd---> someIntermediaryForm ---backEnd---> C
You may want to check these guys out: http://www.edg.com/index.php?location=c_frontend
(the above link is just informative for what can be done, they license their front ends for tens of thousands of dollars)
PS
As far as i know, there is no such a C++ to C compiler by GNU, and this totally beats me (if i'm right about this). Because the C language is fairly small and it's internal mechanisms are fairly rudimentary, a C compiler requires something like one man-year work (i can tell you this first hand cause i wrote such a compiler myself may years ago, and it produces a [virtual] stack machine intermediary code), and being able to have a maintained, up-to-date C++ compiler while only having to write a C compiler once would be a great thing to have...
How do I set ANDROID_SDK_HOME environment variable?
Android SDK
Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
Cordova requires the ANDROID_HOME
environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk
directory (for example c:\android\android-sdk).
Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME
, you would add both %ANDROID_HOME%\tools
and %ANDROID_HOME%\platform-tools
.
Reference : http://ionicframework.com/docs/v1/guide/installation.html
Jquery function BEFORE form submission
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
Why use 'virtual' for class properties in Entity Framework model definitions?
It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.
Edit to clarify "create a proxy around":
By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".
The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.
If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.
Edit to describe why properties would be marked as virtual
Properties such as:
public ICollection<RSVP> RSVPs { get; set; }
Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.
//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
return _RSVPs;
}
public void set_RSVPs(RSVP value)
{
_RSVPs = value;
}
private RSVP _RSVPs;
That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get
and set
functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:
public virtual ICollection<RSVP> RSVPs;
support FragmentPagerAdapter holds reference to old fragments
Just so you know...
Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.
I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).
The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.
I don't have a clean workaround. I used something like this:
public void onSaveInstanceState(Bundle outState) {
IFragmentListener listener = (IFragmentListener)getActivity();
if (listener!= null)
{
if (!listener.isStillInTheAdapter(this.getAdapterItem()))
{
return; // return empty state.
}
}
super.onSaveInstanceState(outState);
// normal saving of state for flips and
// paging out of the activity follows
....
}
An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.
Python: For each list element apply a function across the list
If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.
from __future__ import division
import numpy
data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))
print dists
which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering
# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]
How to POST the data from a modal form of Bootstrap?
I was facing same issue not able to post form without ajax.
but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code :
call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
JavaScript/jQuery to download file via POST with JSON data
Another approach instead of saving the file on the server and retrieving it, is to use .NET 4.0+ ObjectCache with a short expiration until the second Action (at which time it can be definitively dumped). The reason that I want to use JQuery Ajax to do the call, is that it is asynchronous. Building my dynamic PDF file takes quite a bit of time, and I display a busy spinner dialog during that time (it also allows other work to be done). The approach of using the data returned in the "success:" to create a Blob does not work reliably. It depends on the content of the PDF file. It is easily corrupted by data in the response, if it is not completely textual which is all that Ajax can handle.
Javascript - removing undefined fields from an object
Another Javascript Solution
for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){
if(typeof obj[keys[i]] === 'undefined'){
delete obj[keys[i]];
}
}
No additional hasOwnProperty
check is required as Object.keys
does not look up the prototype chain and returns only the properties of obj
.
DEMO
Undo a merge by pull request?
To undo a github pull request with commits throughout that you do not want to delete, you have to run a:
git reset --hard --merge <commit hash>
with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.
A good way to find this is to go to the now closed pull request and finding this field:
Pull Request Image
After you run the git reset
, run a:
git push origin --force <branch name>
This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.
EDIT:
If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.
How to create an Array, ArrayList, Stack and Queue in Java?
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
What are .dex files in Android?
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
Postgres: How to do Composite keys?
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
Embedding Base64 Images
Update: 2017-01-10
Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.
http://caniuse.com/#feat=datauri
Data URIs are now supported by the following web browsers:
- Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
- Konqueror, via KDE's KIO slaves input/output system
- Opera (including devices such as the Nintendo DSi or Wii)
- WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
- Trident
- Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
- Data URIs are supported only for the following elements and/or attributes[4]:
- object (images only)
- img
- input type=image
- link
- CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
- Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
- TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme
http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support
ggplot combining two plots from different data.frames
As Baptiste said, you need to specify the data argument at the geom level. Either
#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) +
geom_point() +
geom_step(data = df2)
)
or
#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) +
geom_point(data = df1) +
geom_step(data = df2)
)
Disable time in bootstrap date time picker
I know this is late, but the answer is simply removing "time" from the word, datetimepicker
to change it to datepicker
. You can format it with dateFormat
.
jQuery( "#datetimepicker4" ).datepicker({
dateFormat: "MM dd, yy",
});
Can't concatenate 2 arrays in PHP
+
is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
With the example:
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Since both your arrays have one entry with the key 0
, the result is expected.
To concatenate, use array_merge
.
How do I run a single test using Jest?
From the command line, use the --testNamePattern
or -t
flag:
jest -t 'fix-order-test'
This will only run tests that match the test name pattern you provide. It's in the Jest documentation.
Another way is to run tests in watch mode, jest --watch
, and then press P to filter the tests by typing the test file name or T to run a single test name.
If you have an it
inside of a describe
block, you have to run
jest -t '<describeString> <itString>'
How to use relative/absolute paths in css URLs?
i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.
Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like
.icon{
background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}
and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.
Good Luck!
How do I convert a list of ascii values to a string in python?
Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
mystring = mystring + chr(char)
print mystring
How to place a JButton at a desired location in a JFrame using Java
Define somewhere the consts :
private static final int BUTTON_LOCATION_X = 300; // location x
private static final int BUTTON_LOCATION_Y = 50; // location y
private static final int BUTTON_SIZE_X = 140; // size height
private static final int BUTTON_SIZE_Y = 50; // size width
and then below :
JButton startButton = new JButton("Click Me To Start!");
// startButton.setBounds(300, 50,140, 50 );
startButton.setBounds(BUTTON_LOCATION_X
, BUTTON_LOCATION_Y,
BUTTON_SIZE_X,
BUTTON_SIZE_Y );
contentPane.add(startButton);
where contentPane
is the Container
object that holds the entire frame :
JFrame frame = new JFrame("Some name goes here");
Container contentPane = frame.getContentPane();
I hope this helps , works great for me ...
Download text/csv content as files from server in Angular
Using angular 1.5.9
I made it working like this by setting the window.location to the csv file download url. Tested and its working with the latest version of Chrome and IE11.
Angular
$scope.downloadStats = function downloadStats{
var csvFileRoute = '/stats/download';
$window.location = url;
}
html
<a target="_self" ng-click="downloadStats()"><i class="fa fa-download"></i> CSV</a>
In php set the below headers for the response:
$headers = [
'content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="export.csv"',
'Cache-control' => 'private, must-revalidate, post-check=0, pre-check=0',
'Content-transfer-encoding' => 'binary',
'Expires' => '0',
'Pragma' => 'public',
];
UNIX export command
export
is used to set environment variables. For example:
export EDITOR=pico
Will set your default text editor to be the pico
command.
Print all but the first three columns
use cut
$ cut -f4-13 file
or if you insist on awk and $13 is the last field
$ awk '{$1=$2=$3="";print}' file
else
$ awk '{for(i=4;i<=13;i++)printf "%s ",$i;printf "\n"}' file
Time complexity of Euclid's Algorithm
The suitable way to analyze an algorithm is by determining its worst case scenarios.
Euclidean GCD's worst case occurs when Fibonacci Pairs are involved.
void EGCD(fib[i], fib[i - 1])
, where i > 0.
For instance, let's opt for the case where the dividend is 55, and the divisor is 34 (recall that we are still dealing with fibonacci numbers).
As you may notice, this operation costed 8 iterations (or recursive calls).
Let's try larger Fibonacci numbers, namely 121393 and 75025. We can notice here as well that it took 24 iterations (or recursive calls).
You can also notice that each iterations yields a Fibonacci number. That's why we have so many operations. We can't obtain similar results only with Fibonacci numbers indeed.
Hence, the time complexity is going to be represented by small Oh (upper bound), this time. The lower bound is intuitively Omega(1): case of 500 divided by 2, for instance.
Let's solve the recurrence relation:
We may say then that Euclidean GCD can make log(xy) operation at most.
How do I find out what keystore my JVM is using?
Keystore Location
Each keytool command has a -keystore
option for specifying the name and location of the persistent keystore file for the keystore managed by keytool. The keystore is by default stored in a file named .keystore
in the user's home directory, as determined by the "user.home" system property. Given user name uName, the "user.home" property value defaults to
C:\Users\uName on Windows 7 systems
C:\Winnt\Profiles\uName on multi-user Windows NT systems
C:\Windows\Profiles\uName on multi-user Windows 95 systems
C:\Windows on single-user Windows 95 systems
Thus, if the user name is "cathy", "user.home" defaults to
C:\Users\cathy on Windows 7 systems
C:\Winnt\Profiles\cathy on multi-user Windows NT systems
C:\Windows\Profiles\cathy on multi-user Windows 95 systems
http://docs.oracle.com/javase/1.5/docs/tooldocs/windows/keytool.html
How to display text in pygame?
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
Rails 4 Authenticity Token
These features were added for security and forgery protection purposes.
However, to answer your question, here are some inputs.
You can add these lines after your the controller name.
Like so,
class NameController < ApplicationController
skip_before_action :verify_authenticity_token
Here are some lines for different versions of rails.
Rails 3
skip_before_filter :verify_authenticity_token
Rails 4:
skip_before_action :verify_authenticity_token
Should you intend to disable this security feature for all controller routines, you can change the value of protect_from_forgery to :null_session on your application_controller.rb file.
Like so,
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
The simplest possible JavaScript countdown timer?
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
How can I make a thumbnail <img> show a full size image when clicked?
Use this as an example
https://www.w3schools.com/jquerymobile/tryit.asp?filename=tryjqmob_popup_image
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div data-role="page">_x000D_
<div data-role="header">_x000D_
<h1>Welcome To My Homepage</h1>_x000D_
</div>_x000D_
_x000D_
<div id="pageone" data-role="main" class="ui-content">_x000D_
<p>Click on the image to enlarge it.</p>_x000D_
<p>Notice that we have added a "back button" in the top right corner.</p>_x000D_
<a href="#myPopup" data-rel="popup" data-position-to="window">_x000D_
<img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" alt="Skaret View" style="width:200px;"></a>_x000D_
_x000D_
<div data-role="popup" id="myPopup">_x000D_
<p>This is my picture!</p> _x000D_
<a href="#pageone" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" style="width:800px;height:400px;" alt="Skaret View">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div data-role="footer">_x000D_
<h1>Footer Text</h1>_x000D_
</div>_x000D_
</div> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
How do I create a foreign key in SQL Server?
Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script
What are the different NameID format used for?
1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:
Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:
urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:
Returning Promises from Vuex actions
Just for an information on a closed topic:
you don’t have to create a promise, axios returns one itself:
Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4
Example:
export const loginForm = ({ commit }, data) => {
return axios
.post('http://localhost:8000/api/login', data)
.then((response) => {
commit('logUserIn', response.data);
})
.catch((error) => {
commit('unAuthorisedUser', { error:error.response.data });
})
}
Another example:
addEmployee({ commit, state }) {
return insertEmployee(state.employee)
.then(result => {
commit('setEmployee', result.data);
return result.data; // resolve
})
.catch(err => {
throw err.response.data; // reject
})
}
Another example with async-await
async getUser({ commit }) {
try {
const currentUser = await axios.get('/user/current')
commit('setUser', currentUser)
return currentUser
} catch (err) {
commit('setUser', null)
throw 'Unable to fetch current user'
}
},
calling java methods in javascript code
Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax()
method. Or if you wanted to do it using plain javascript, here's a tutorial.
Unable to open debugger port in IntelliJ IDEA
I had this exact message.
The reason was that some IDE (I use Eclipse and Intellij) failed to shutdown the tomcat server. Or maybe crashed before it could do so.
The solution was to navigate to C:\...\apache-tomcat-xxx\bin
and run shutdown
.
Setting action for back button in navigation controller
The solution I have found so far is not very nice, but it works for me. Taking this answer, I also check whether I'm popping programmatically or not:
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ((self.isMovingFromParentViewController || self.isBeingDismissed)
&& !self.isPoppingProgrammatically) {
// Do your stuff here
}
}
You have to add that property to your controller and set it to YES before popping programmatically:
self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];
How to set RelativeLayout layout params in code not in xml?
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.setLayoutParams(labelLayoutParams);
// If you want to add some controls in this Relative Layout
labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView mImage = new ImageView(this);
mImage.setBackgroundResource(R.drawable.popupnew_bg);
layout.addView(mImage,labelLayoutParams);
setContentView(layout);
Oracle Error ORA-06512
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum
is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
Install tkinter for Python
The situation on macOS is still a bit complicated, but do-able:
Python.org strongly suggest downloading tkinter from ActiveState, but you should read their license first (hint: don't redistribute or want Support).
When the download is opened OS X 10.11 rejected it because it couldn't find my receipt: "ActiveTcl-8.6.pkg can’t be opened because it is from an unidentified developer".
I followed an OSXDaily fix from 2012 which suggested allowing from anywhere. But OS X has now added an "Open Anyway" option to allow (e.g.) Active-Tcl as a once off, and the "Anywhere" option has gained a timeout.
How can I group data with an Angular filter?
You can use groupBy of angular.filter module.
so you can do something like this:
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin Remember the basic requirements to use angular.filter
, specifically note you must add it to your module's dependencies:
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running $ bower install angular-filter from your terminal
- via npm: by running $ npm install angular-filter from your terminal
- via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.
(3) Add 'angular.filter' to your main module's list of dependencies.
Only variables should be passed by reference
$file_extension = end(explode('.', $file_name)); //ERROR ON THIS LINE
change this line as,
$file_extension = end((explode('.', $file_name))); //no errors
Technique is simple please put one more brackets for explode,
(explode()), then only it can perform independently..
Why catch and rethrow an exception in C#?
It depends what you are doing in the catch block, and if you are wanting to pass the error on to the calling code or not.
You might say Catch io.FileNotFoundExeption ex
and then use an alternative file path or some such, but still throw the error on.
Also doing Throw
instead of Throw Ex
allows you to keep the full stack trace. Throw ex restarts the stack trace from the throw statement (I hope that makes sense).
Comprehensive methods of viewing memory usage on Solaris
Here are the basics. I'm not sure that any of these count as "clear and simple" though.
ps(1)
For process-level view:
$ ps -opid,vsz,rss,osz,args
PID VSZ RSS SZ COMMAND
1831 1776 1008 222 ps -opid,vsz,rss,osz,args
1782 3464 2504 433 -bash
$
vsz/VSZ: total virtual process size (kb)
rss/RSS: resident set size (kb, may be inaccurate(!), see man)
osz/SZ: total size in memory (pages)
To compute byte size from pages:
$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"
vmstat(1M)
$ vmstat 5 5
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr rm s3 -- -- in sy cs us sy id
0 0 0 535832 219880 1 2 0 0 0 0 0 -0 0 0 0 402 19 97 0 1 99
0 0 0 514376 203648 1 4 0 0 0 0 0 0 0 0 0 402 19 96 0 1 99
^C
prstat(1M)
PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP
1852 martin 4840K 3600K cpu0 59 0 0:00:00 0.3% prstat/1
1780 martin 9384K 2920K sleep 59 0 0:00:00 0.0% sshd/1
...
swap(1)
"Long listing" and "summary" modes:
$ swap -l
swapfile dev swaplo blocks free
/dev/zvol/dsk/rpool/swap 256,1 16 1048560 1048560
$ swap -s
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$
top(1)
An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported".
More recent binary packages available from sunfreeware.com or blastwave.org.
load averages: 0.02, 0.00, 0.00; up 2+12:31:38 08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle, 0.0% user, 2.0% kernel, 0.0% iowait, 0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap
PID USERNAME LWP PRI NICE SIZE RES STATE TIME CPU COMMAND
1898 martin 1 54 0 3336K 1808K cpu 0:00 0.96% top
7 root 11 59 0 10M 7912K sleep 0:09 0.02% svc.startd
sar(1M)
And just what's wrong with sar
? :)
Laravel Advanced Wheres how to pass variable into function?
@kajetons' answer is fully functional.
You can also pass multiple variables by passing them like: use($var1, $var2)
DB::table('users')->where(function ($query) use ($activated,$var2) {
$query->where('activated', '=', $activated);
$query->where('var2', '>', $var2);
})->get();
What is 'Context' on Android?
An Android Context is an Interface (in the general sense, not in the Java sense; in Java, Context
is actually an abstract class!) that allows access to application specific resources and class and information about application environment.
If your android app was a web app, your context would be something similar to ServletContext
(I am not making an exact comparison here).
Your activities and services also extend Context
, so they inherit all those methods to access the environment information in which the app is running.
How to use std::sort to sort an array in C++
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size);
In C++11:
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end());
Display unescaped HTML in Vue.js
Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.
So for your specific example you would need:
<div id="logapp">
<table>
<tbody>
<tr v-repeat="logs">
<td v-html="fail"></td>
<td v-html="type"></td>
<td v-html="description"></td>
<td v-html="stamp"></td>
<td v-html="id"></td>
</tr>
</tbody>
</table>
</div>
Twitter Bootstrap and ASP.NET GridView
You need to set useaccessibleheader
attribute of the gridview to true
and also then also specify a TableSection
to be a header after calling the DataBind()
method on you GridView object. So if your grid view is mygv
mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader
This should result in a proper formatted grid with thead
and tbody
tags
Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?
Here is my favorite way, which I think is a little less tedious than the "Select for Compare, then Compare With..." steps.
- Open the left side file (not editable)
F1
Compare Active File With...
- Select the right side file (editable) - You can either select a recent file from the dropdown list, or click any file in the Explorer panel.
This works with any arbitrary files, even ones that are not in the project dir. You can even just create 2 new Untitled files and copy/paste text in there too.
psycopg2: insert multiple rows with one query
Using aiopg - The snippet below works perfectly fine
# items = [10, 11, 12, 13]
# group = 1
tup = [(gid, pid) for pid in items]
args_str = ",".join([str(s) for s in tup])
# insert into group values (1, 10), (1, 11), (1, 12), (1, 13)
yield from cur.execute("INSERT INTO group VALUES " + args_str)
Print the address or pointer for value in C
Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:
char **a;
char *b;
char c = 'H';
b = &c;
a = &b;
You would be able to access the address of the double pointer a
by doing:
printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);
Reactjs convert html string to jsx
You can use the following if you want to render raw html in React
<div dangerouslySetInnerHTML={{__html: `html-raw-goes-here`}} />
Example - Render
Test is a good day
Command to run a .bat file
There are many possibilities to solve this task.
1. RUN the batch file with full path
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat
is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat
is the current directory of the current process. In case of Template.bat
requires that the directory of this batch file is the current directory, the batch file Template.bat
should contain after @echo off
as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /?
for getting displayed the help of this command explaining parameter /D
... change to specified directory also on a different drive.
Run in a command prompt window call /?
for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0
... drive and path of argument 0 which is the name of the batch file.
2. CALL the batch file with full path
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat
is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
3. Change directory and RUN batch file with one command line
There are 3 operators for running multiple commands on one command line: &
, &&
and ||
.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the &&
operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat
is successful.
4. Change directory and CALL batch file with one command line
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat
.
5. Change directory and CALL batch file with keeping current environment with one command line
The four solutions above change the current directory and it is unknown what Template.bat
does regarding
- current directory
- environment variables
- command extensions state
- delayed expansion state
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat
changes on environment for itself, it is advisable to use setlocal
and endlocal
.
Run in a command prompt window setlocal /?
and endlocal /?
for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only &
instead of &&
used as it is important here that after setlocal
is executed the command endlocal
is finally also executed.
ONE MORE NOTE
If batch file Template.bat
contains the command exit
without parameter /B
and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat
contains exit /B
or goto :EOF
instead of just exit
if there is exit
used at all in this batch file.
How do I get extra data from intent on Android?
If used in a FragmentActivity, try this:
The first page extends FragmentActivity
Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);
In the fragment, you just need to call getActivity()
first,
The second page extends Fragment:
String receive = getActivity().getIntent().getExtras().getString("name");
jQuery multiselect drop down menu
Are you looking to do something like this http://jsfiddle.net/robert/xhHkG/
$('#transactionType').attr({
'multiple': true,
'size' : 10
});
Put that in a $(function() {...})
or some other onload
Edit
Reread your question, you're not really looking for a multiple select... but a dropdown box that allows you to select multiple. Yeah, probably best to use a plugin for that or write it from the ground up, it's not a "quick answer" type deal though.
Leading zeros for Int in Swift
Using Swift 5’s fancy new extendible interpolation:
extension DefaultStringInterpolation {
mutating func appendInterpolation(pad value: Int, toWidth width: Int, using paddingCharacter: Character = "0") {
appendInterpolation(String(format: "%\(paddingCharacter)\(width)d", value))
}
}
print("I ate \(pad: pieCount, toWidth: 3, using: "0") pies") // => `I ate 003 pies`
Converting String To Float in C#
Your thread's locale is set to one in which the decimal mark is "," instead of ".".
Try using this:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.
SQL Query NOT Between Two Dates
For there to be an overlap the table's start_date has to be LESS THAN the interval end date (i.e. it has to start before the end of the interval) AND the table's end_date has to be GREATER THAN the interval start date. You may need to use <= and >= depending on your requirements.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
Pass arguments into C program from command line
You could use getopt.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Random word generator- Python
Reading a local word list
If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words
.
Example:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
Pulling from a remote dictionary
If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests
):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
Simplest way to wait some asynchronous tasks complete, in Javascript?
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
How can I trigger a JavaScript event click
Fair warning:
element.onclick()
does not behave as expected. It only runs the code within onclick="" attribute
, but does not trigger default behavior.
I had similar issue with radio button not setting to checked, even though onclick
custom function was running fine. Had to add radio.checked = "true";
to set it. Probably the same goes and for other elements (after a.onclick()
there should be also window.location.href = "url";
)
Don't understand why UnboundLocalError occurs (closure)
You need to use the global statement so that you are modifying the global variable counter, instead of a local variable:
counter = 0
def increment():
global counter
counter += 1
increment()
If the enclosing scope that counter
is defined in is not the global scope, on Python 3.x you could use the nonlocal statement. In the same situation on Python 2.x you would have no way to reassign to the nonlocal name counter
, so you would need to make counter
mutable and modify it:
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
How to copy file from host to container using Dockerfile
Use COPY command like this:
COPY foo.txt /data/foo.txt
# where foo.txt is the relative path on host
# and /data/foo.txt is the absolute path in the image
read more details for COPY in the official documentation
An alternative would be to use ADD but this is not the best practise if you dont want to use some advanced features of ADD like decompression of tar.gz files.If you still want to use ADD command, do it like this:
ADD abc.txt /data/abc.txt
# where abc.txt is the relative path on host
# and /data/abc.txt is the absolute path in the image
read more details for ADD in the official documentation
Javascript change date into format of (dd/mm/yyyy)
This will ensure you get a two-digit day and month.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Or terser:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
How to create a HTML Table from a PHP array?
Here is my answer.
function array2Html($array, $table = true)
{
$out = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
if (!isset($tableHeader)) {
$tableHeader =
'<th>' .
implode('</th><th>', array_keys($value)) .
'</th>';
}
array_keys($value);
$out .= '<tr>';
$out .= array2Html($value, false);
$out .= '</tr>';
} else {
$out .= "<td>$value</td>";
}
}
if ($table) {
return '<table>' . $tableHeader . $out . '</table>';
} else {
return $out;
}
}
However, your table headers have to be a part of the array, which is pretty common when it comes from a database. e.g.
$shop = array(
array(
'title' => 'rose',
'price' => 1.25,
'number' => 15,
),
array(
'title' => 'daisy',
'price' => 0.75,
'number' => 25,
),
array(
'title' => 'orchid',
'price' => 1.15,
'number' => 7,
),
);
print arrayToHtml($shop);
Hope it helps ;)
The meaning of NoInitialContextException error
You should set jndi.properties. I've given below some piece of code that explain how the properties are set for activemq. Like that you can set for your application. Inside a J2EE container like JBoss no need to set these properties.
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL,"tcp://localhost:61616");
InitialContext ctx = new InitialContext(props);
// get the initial context
// InitialContext ctx = new InitialContext();
QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
// create a queue connection
QueueConnection queueConn = connFactory.createQueueConnection();
queueConn.start();
// lookup the queue object
Queue queue = (Queue) ctx.lookup("dynamicQueues/Payment_Check");
I know this is a late answer, but just giving for future reference.
Extract month and year from a zoo::yearmon object
The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:
cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012
How do I create a simple 'Hello World' module in Magento?
I've been wrestling with Magento for the last month or so and I'm still trying to figure it out. So this is a case of the blind leading the blind. There's little in the way of documentation and the forum/wiki is chaotic at best. Not only that, but there are several solutions that are either outdated or far from optimal.
I'm not sure if you have a project or just trying to figure it out, but it's probably easier if you started with modifying existing functionality as opposed to creating something completely new. For that I'd definately go with the "Recommended articles for developers" in the wiki. The new payment method one was a real eye-opener.
For debugging I'd definitely recommend using FirePHP and looking at your HTML source when something goes wrong. The ole echo debug method doesn't really work all that well.
The general architecture is so mind-numbingly complex, that even if I completely understood it, I'd need to write a book to cover it. The best I can do is give you advice I wish someone had given me when I first started...
Stay away from core files. Don't modify them, instead write your own module and override what you need.
Magento uses config files consisting of XML to decide what it needs to do. In order to get it to run your own stuff as opposed to core functionality you need the correct xml. Unfortunately there is no guide on how to build you XML; you need to look at examples and do some serious testing. To complicate things the content of these files is largely case-sensitive. However if you master these you can override any part of the basic functionality which makes for a very powerful system.
Magento uses methods like Mage::getModel('mymodel')
, Mage::getSingleton('mysingleton')
, Mage::helper('myhelper')
to return objects of certain classes. It finds these by default in its core namespace. If you want it to use your own, you need to override these in your config.xml
file.
The name of your classes must correspond to the folder they're in.
A lot of the objects in Magento ultimately extend something called a Varien_Object
. This is a general purpose class (kind of like a swiss army knife) and its purpose in life is to allow you to define your own methods/variables on the fly. For example you'll see it used as a glorified array to pass data from one method to another.
During development make sure you caching is disabled. It'll make magento excruciatingly slow, but it'll save you a lot of head trauma (from banging it on your desk).
You'll see $this
being used a lot. It means a different class depending on what file you see it. get_class($this)
is your friend, especially in conjunction with FirePHP.
Jot things down on paper. A lot. There are countless little factoids that you're gonna need 1-2 days after you encounter them.
Magento loves OO. Don't be surprised if tracing a method takes you through 5-10 different classes.
Read the designer's guide here. It's meant mostly for graphics designers, but you need it to understand where and why the output from your module will end up. For that don't forget to turn on "Template path hints" in the developer section of the admin panel.
There's more, but I'll stop here before this turns into a dissertation.
Setting a divs background image to fit its size?
You can achieve this with the background-size property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
Location Services not working in iOS 8
I was pulling my hair out with the same problem. Xcode gives you the error:
Trying to start MapKit
location updates without prompting for
location authorization. Must call -[CLLocationManager
requestWhenInUseAuthorization]
or -[CLLocationManager
requestAlwaysAuthorization]
first.
But even if you implement one of the above methods, it won't prompt the user unless there is an entry in the info.plist for NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
.
Add the following lines to your info.plist where the string values represent the reason you you need to access the users location
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
I think these entries may have been missing since I started this project in Xcode 5. I'm guessing Xcode 6 might add default entries for these keys but have not confirmed.
You can find more information on these two Settings here
The type List is not generic; it cannot be parameterized with arguments [HTTPClient]
Your import has a subtle error:
import java.awt.List;
It should be:
import java.util.List;
The problem is that both awt
and Java's util package provide a class called List
. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList
extends java.util.List
, not java.awt.List
so if it wasn't for the generics, it would have still been a problem.
Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.
import org.omg.DynamicAny.NameValuePair;
should be
import org.apache.http.NameValuePair
nameValuePairs
now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity
, which is List<? extends NameValuePair>
, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair
did not extend org.apache.http.NameValuePair
and the shortened type name NameValuePair
evaluated to org.omg...
in your file, but org.apache...
in their code.
List rows after specific date
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
if (typeof jQuery == 'undefined') {
// or if ( ! window.jQuery)
// or if ( ! 'jQuery' in window)
// or if ( ! window.hasOwnProperty('jQuery'))
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/libs/jquery.js';
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
After you attempt to include Google's copy from the CDN.
In HTML5, you don't need to set the type
attribute.
You can also use...
window.jQuery || document.write('<script src="/libs/jquery.js"><\/script>');
How to npm install to a specified directory?
In the documentation it's stated:
Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On
most systems, this is /usr/local. On windows, this is the exact
location of the node.exe binary. On Unix systems, it's one level up,
since node is typically installed at {prefix}/bin/node rather than
{prefix}/node.exe.
When the global flag is set, npm installs things into this prefix.
When it is not set, it uses the root of the current package, or the
current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
What is the use of BindingResult interface in spring MVC?
Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.
Then, you can check this object looking for validation errors:
validator.validate(modelObject, bindingResult);
if (bindingResult.hasErrors()) {
// do something
}
INSTALL_FAILED_NO_MATCHING_ABIS when install apk
Basically if you tried Everything above and still you have the same error "Because i am facing this issue before too" then check which .jar or .aar or module you added may be the one library using ndk , and that one is not supporting 8.0 (Oreo)+ , likewise i am using Microsoft SignalR socket Library adding its .jar files and latterly i found out app not installing in Oreo then afterwards i remove that library because currently there is no solution on its git page and i go for another one.
So please check the library you are using and search about it if you eagerly needed that one.
SQL to LINQ Tool
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
calling server side event from html button control
On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.
If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.
<button id="cmdAction"
runat="server" onserverclick="cmdAction_Click()"
class="Button Styles"
title="Does something on the server"
<!-- for databound controls -->
CommandName="cmdname">
CommandArgument="args..."
>
<!-- content -->
<span class="ui-icon ..."></span>
<span class="push">Click Me</span>
</button>
On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.
protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}
There are other solutions as in using custom controls, etc. Also
note that I am using this live on projects in VS2K8.
Hoping this helps.
Enjoy!
Extract values in Pandas value_counts()
First you have to sort
the dataframe
by the count
column max
to min
if it's not sorted that way already. In your post, it is in the right order already but I will sort
it anyways:
dataframe.sort_index(by='count', ascending=[False])
col count
0 apple 5
1 sausage 2
2 banana 2
3 cheese 1
Then you can output the col
column to a list:
dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']
Detect Click into Iframe using JavaScript
You can achieve this by using the blur event on window element.
Here is a jQuery plugin for tracking click on iframes (it will fire a custom callback function when an iframe is clicked) :
https://github.com/finalclap/iframeTracker-jquery
Use it like this :
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
How to rename a table in SQL Server?
If you try exec sp_rename
and receieve a LockMatchID error then it might help to add a use [database] statement first:
I tried
exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
-- Invalid EXECUTE statement using object "Object", method "LockMatchID".
What I had to do to fix it was to rewrite it to:
use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';
CSS Background Opacity
.transbg{/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}
In C#, can a class inherit from another class and an interface?
No, not exactly. But it can inherit from a class and implement one or more interfaces.
Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.
TypeError: string indices must be integers, not str // working with dict
Actually I think that more general approach to loop through dictionary is to use iteritems():
# get tuples of term, courses
for term, term_courses in courses.iteritems():
# get tuples of course number, info
for course, info in term_courses.iteritems():
# loop through info
for k, v in info.iteritems():
print k, v
output:
assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian
Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():
for term_courses in courses.itervalues():
for info in term_courses.itervalues():
for k, v in info.iteritems():
print k, v
What does it mean when Statement.executeUpdate() returns -1?
As the statement executed is not actually DML (eg UPDATE
, INSERT
or EXECUTE
), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.
Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):
When the method execute
returns true, the method getResultSet
is called to
retrieve the ResultSet object. When execute
returns false, the method
getUpdateCount
returns an int. If this number is greater than or equal to zero, it
indicates the update count returned by the statement. If it is -1, it indicates that there
are no more results.
Given this information, I guess that executeUpdate()
internally does an execute()
, and then - as execute()
will return false
- it will return the value of getUpdateCount()
, which in this case - in accordance with the JDBC spec - will return -1
.
This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate()
says:
Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
And 2) that the Javadoc for Statement.getUpdateCount() specifies:
the current result as an update count; -1 if the current result is a ResultSet object or there are no more results
Just to clarify: given the Javadoc for executeUpdate()
the behavior is probably wrong, but it can be explained.
Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).
urlencode vs rawurlencode?
It will depend on your purpose. If interoperability with other systems is important then it seems rawurlencode is the way to go. The one exception is legacy systems which expect the query string to follow form-encoding style of spaces encoded as + instead of %20 (in which case you need urlencode).
rawurlencode follows RFC 1738 prior to PHP 5.3.0 and RFC 3986 afterwards (see http://us2.php.net/manual/en/function.rawurlencode.php)
Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).
Note on RFC 3986 vs 1738. rawurlencode prior to php 5.3 encoded the tilde character (~
) according to RFC 1738. As of PHP 5.3, however, rawurlencode follows RFC 3986 which does not require encoding tilde characters.
urlencode encodes spaces as plus signs (not as %20
as done in rawurlencode)(see http://us2.php.net/manual/en/function.urlencode.php)
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.
This corresponds to the definition for application/x-www-form-urlencoded in RFC 1866.
Additional Reading:
You may also want to see the discussion at http://bytes.com/groups/php/5624-urlencode-vs-rawurlencode.
Also, RFC 2396 is worth a look. RFC 2396 defines valid URI syntax. The main part we're interested in is from 3.4 Query Component:
Within a query component, the characters ";", "/", "?", ":", "@",
"&", "=", "+", ",", and "$"
are reserved.
As you can see, the +
is a reserved character in the query string and thus would need to be encoded as per RFC 3986 (as in rawurlencode).
How do you normalize a file path in Bash?
A portable and reliable solution is to use python, which is preinstalled pretty much everywhere (including Darwin). You have two options:
abspath
returns an absolute path but does not resolve symlinks:
python -c "import os,sys; print(os.path.abspath(sys.argv[1]))" path/to/file
realpath
returns an absolute path and in doing so resolves symlinks, generating a canonical path:
python -c "import os,sys; print(os.path.realpath(sys.argv[1]))" path/to/file
In each case, path/to/file
can be either a relative or absolute path.
Sort hash by key, return hash in Ruby
Note: Ruby >= 1.9.2 has an order-preserving hash: the order keys are inserted will be the order they are enumerated. The below applies to older versions or to backward-compatible code.
There is no concept of a sorted hash. So no, what you're doing isn't right.
If you want it sorted for display, return a string:
"{" + h.sort.map{|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ") + "}"
or, if you want the keys in order:
h.keys.sort
or, if you want to access the elements in order:
h.sort.map do |key,value|
# keys will arrive in order to this block, with their associated value.
end
but in summary, it makes no sense to talk about a sorted hash. From the docs, "The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order." So inserting keys in a specific order into the hash won't help.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"
Sometime we should see the note from the warnin SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
.
This happens when no appropriate SLF4J binding could be found on the class path
You can search the reason why this warning comes.
Adding one of the jar from *slf4j-nop.jar
, slf4j-simple.jar
, slf4j-log4j12.jar
, slf4j-jdk14.jar
or logback-classic.jar*
to the class path should solve the problem.
compile "org.slf4j:slf4j-simple:1.6.1"
for example add the above code to your build.gradle
or the corresponding code to pom.xml
for maven project.
Center a DIV horizontally and vertically
For modern browsers
When you have that luxury. There's flexbox too, but that's not broadly supported at the time of this writing.
HTML:
<div class="content">This works with any content</div>
CSS:
.content {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Tinker with it further on Codepen or on JSBin
For older browser support, look elsewhere in this thread.
How to print an unsigned char in C?
Because char
is by default signed
declared that means the range of the variable is
-127 to +127>
your value is overflowed. To get the desired value you have to declared the unsigned
modifier. the modifier's (unsigned
) range is:
0 to 255
to get the the range of any data type follow the process 2^bit
example char
is 8 bit length to get its range just 2 ^(power) 8
.
Android: How to add R.raw to project?
(With reference to Android Studio)
Create a new directory in res folder. Make sure to create new "Android Resource Directory" and not new "Directory".
Then ensure that there is at least one valid file in it. It should show up now.
Difference between `constexpr` and `const`
An overview of the const and constexpr keywords
In C ++, if a const object is initialized with a constant expression, we can use our const object wherever a constant expression is required.
const int x = 10;
int a[x] = {0};
For example, we can make a case statement in switch.
constexpr can be used with arrays.
constexpr is not a type.
The constexpr keyword can be used in conjunction with the auto keyword.
constexpr auto x = 10;
struct Data { // We can make a bit field element of struct.
int a:x;
};
If we initialize a const object with a constant expression, the expression generated by that const object is now a constant expression as well.
Constant Expression : An expression whose value can be calculated at compile time.
x*5-4 // This is a constant expression. For the compiler, there is no difference between typing this expression and typing 46 directly.
Initialize is mandatory. It can be used for reading purposes only. It cannot be changed. Up to this point, there is no difference between the "const" and "constexpr" keywords.
NOTE: We can use constexpr and const in the same declaration.
constexpr const int* p;
Constexpr Functions
Normally, the return value of a function is obtained at runtime.
But calls to constexpr functions will be obtained as a constant in compile time when certain conditions are met.
NOTE : Arguments sent to the parameter variable of the function in function calls or to all parameter variables if there is more than one parameter, if C.E the return value of the function will be calculated in compile time. !!!
constexpr int square (int a){
return a*a;
}
constexpr int a = 3;
constexpr int b = 5;
int arr[square(a*b+20)] = {0}; //This expression is equal to int arr[35] = {0};
In order for a function to be a constexpr function, the return value type of the function and the type of the function's parameters must be in the type category called "literal type".
The constexpr functions are implicitly inline functions.
An important point :
None of the constexpr functions need to be called with a constant expression.It is not mandatory. If this happens, the computation will not be done at compile time. It will be treated like a normal function call. Therefore, where the constant expression is required, we will no longer be able to use this expression.
The conditions required to be a constexpr function are shown below;
1 ) The types used in the parameters of the function and the type of the return value of the function must be literal type.
2 ) A local variable with static life time should not be used inside the function.
3 ) If the function is legal, when we call this function with a constant expression in compile time, the compiler calculates the return value of the function in compile time.
4 ) The compiler needs to see the code of the function, so constexpr functions will almost always be in the header files.
5 ) In order for the function we created to be a constexpr function, the definition of the function must be in the header file.Thus, whichever source file includes that header file will see the function definition.
Bonus
Normally with Default Member Initialization, static data members with const and integral types can be initialized within the class. However, in order to do this, there must be both "const" and "integral types".
If we use static constexpr then it doesn't have to be an integral type to initialize it inside the class. As long as I initialize it with a constant expression, there is no problem.
class Myclass {
const static int sx = 15; // OK
constexpr static int sy = 15; // OK
const static double sd = 1.5; // ERROR
constexpr static double sd = 1.5; // OK
};
Good MapReduce examples
Map reduce is a framework that was developed to process massive amounts of data efficiently.
For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.
For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases.
Map Reduce provides a cluster based implementation where data is processed in a distributed manner
Here is a wikipedia article explaining what map-reduce
is all about
Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and
a well used use-case.
Personally, found this link quite useful to understand the concept
Copying the explanation provided in the blog (In case the link goes stale)
Finding Friends
MapReduce is a framework originally developed at Google that allows
for easy large scale distributed computing across a number of domains.
Apache Hadoop is an open source implementation.
I'll gloss over the details, but it comes down to defining two
functions: a map function and a reduce function. The map function
takes a value and outputs key:value pairs. For instance, if we define
a map function that takes a string and outputs the length of the word
as the key and the word itself as the value then map(steve) would
return 5:steve and map(savannah) would return 8:savannah. You may have
noticed that the map function is stateless and only requires the input
value to compute it's output value. This allows us to run the map
function against values in parallel and provides a huge advantage.
Before we get to the reduce function, the mapreduce framework groups
all of the values together by key, so if the map functions output the
following key:value pairs:
3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research
They get grouped as:
3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]
Each of these lines would then be passed as an argument to the reduce
function, which accepts a key and a list of values. In this instance,
we might be trying to figure out how many words of certain lengths
exist, so our reduce function will just count the number of items in
the list and output the key with the size of the list, like:
3 : 3
4 : 3
5 : 2
8 : 2
The reductions can also be done in parallel, again providing a huge
advantage. We can then look at these final results and see that there
were only two words of length 5 in our corpus, etc...
The most common example of mapreduce is for counting the number of
times words occur in a corpus. Suppose you had a copy of the internet
(I've been fortunate enough to have worked in such a situation), and
you wanted a list of every word on the internet as well as how many
times it occurred.
The way you would approach this would be to tokenize the documents you
have (break it into words), and pass each word to a mapper. The mapper
would then spit the word back out along with a value of 1
. The
grouping phase will take all the keys (in this case words), and make a
list of 1's. The reduce phase then takes a key (the word) and a list
(a list of 1's for every time the key appeared on the internet), and
sums the list. The reducer then outputs the word, along with it's
count. When all is said and done you'll have a list of every word on
the internet, along with how many times it appeared.
Easy, right? If you've ever read about mapreduce, the above scenario
isn't anything new... it's the "Hello, World" of mapreduce. So here is
a real world use case (Facebook may or may not actually do the
following, it's just an example):
Facebook has a list of friends (note that friends are a bi-directional
thing on Facebook. If I'm your friend, you're mine). They also have
lots of disk space and they serve hundreds of millions of requests
everyday. They've decided to pre-compute calculations when they can to
reduce the processing time of requests. One common processing request
is the "You and Joe have 230 friends in common" feature. When you
visit someone's profile, you see a list of friends that you have in
common. This list doesn't change frequently so it'd be wasteful to
recalculate it every time you visited the profile (sure you could use
a decent caching strategy, but then I wouldn't be able to continue
writing about mapreduce for this problem). We're going to use
mapreduce so that we can calculate everyone's common friends once a
day and store those results. Later on it's just a quick lookup. We've
got lots of disk, it's cheap.
Assume the friends are stored as Person->[List of Friends], our
friends list is then:
A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D
Each line will be an argument to a mapper. For every friend in the
list of friends, the mapper will output a key-value pair. The key will
be a friend along with the person. The value will be the list of
friends. The key will be sorted so that the friends are in order,
causing all pairs of friends to go to the same reducer. This is hard
to explain with text, so let's just do it and see if you can see the
pattern. After all the mappers are done running, you'll have a list
like this:
For map(A -> B C D) :
(A B) -> B C D
(A C) -> B C D
(A D) -> B C D
For map(B -> A C D E) : (Note that A comes before B in the key)
(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :
(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :
(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):
(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:
(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)
Each line will be passed as an argument to a reducer. The reduce
function will simply intersect the lists of values and output the same
key with the result of the intersection. For example, reduce((A B) ->
(A C D E) (B C D)) will output (A B) : (C D) and means that friends A
and B have C and D as common friends.
The result after reduction is:
(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)
Now when D visits B's profile, we can quickly look up (B D)
and see
that they have three friends in common, (A C E)
.
How do I use reflection to call a generic method?
Adding on to Adrian Gallero's answer:
Calling a generic method from type info involves three steps.
TLDR: Calling a known generic method with a type object can be accomplished by:
((Action)GenericMethod<object>)
.Method
.GetGenericMethodDefinition()
.MakeGenericMethod(typeof(string))
.Invoke(this, null);
where GenericMethod<object>
is the method name to call and any type that satisfies the generic constraints.
(Action) matches the signature of the method to be called i.e. (Func<string,string,int>
or Action<bool>
)
Step 1 is getting the MethodInfo for the generic method definition
Method 1: Use GetMethod() or GetMethods() with appropriate types or binding flags.
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
Method 2: Create a delegate, get the MethodInfo object and then call GetGenericMethodDefinition
From inside the class that contains the methods:
MethodInfo method = ((Action)GenericMethod<object>)
.Method
.GetGenericMethodDefinition();
MethodInfo method = ((Action)StaticMethod<object>)
.Method
.GetGenericMethodDefinition();
From outside of the class that contains the methods:
MethodInfo method = ((Action)(new Sample())
.GenericMethod<object>)
.Method
.GetGenericMethodDefinition();
MethodInfo method = ((Action)Sample.StaticMethod<object>)
.Method
.GetGenericMethodDefinition();
In C#, the name of a method, i.e. "ToString" or "GenericMethod" actually refers to a group of methods that may contain one or more methods. Until you provide the types of the method parameters, it is not known which
method you are referring to.
((Action)GenericMethod<object>)
refers to the delegate for a specific method. ((Func<string, int>)GenericMethod<object>)
refers to a different overload of GenericMethod
Method 3: Create a lambda expression containing a method call expression, get the MethodInfo object and then GetGenericMethodDefinition
MethodInfo method = ((MethodCallExpression)((Expression<Action<Sample>>)(
(Sample v) => v.GenericMethod<object>()
)).Body).Method.GetGenericMethodDefinition();
This breaks down to
Create a lambda expression where the body is a call to your desired method.
Expression<Action<Sample>> expr = (Sample v) => v.GenericMethod<object>();
Extract the body and cast to MethodCallExpression
MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;
Get the generic method definition from the method
MethodInfo methodA = methodCallExpr.Method.GetGenericMethodDefinition();
Step 2 is calling MakeGenericMethod to create a generic method with the appropriate type(s).
MethodInfo generic = method.MakeGenericMethod(myType);
Step 3 is invoking the method with the appropriate arguments.
generic.Invoke(this, null);
SQL Server: Query fast, but slow from procedure
I found the problem, here's the script of the slow and fast versions of the stored procedure:
dbo.ViewOpener__RenamedForCruachan__Slow.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
dbo.ViewOpener__RenamedForCruachan__Fast.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
Slow: SET ANSI_NULLS OFF
Fast: SET ANSI_NULLS ON
This answer also could be made to make sense, since the view does have a join clause that says:
(table.column IS NOT NULL)
So there is some NULL
s involved.
The explanation is further proved by returning to Query Analizer, and running
SET ANSI_NULLS OFF
.
DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
.
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
And the query is slow.
So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off
, rather than ANSI_NULLS on
, which is QA's default.
Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS
option in the stored procedure dialog:
Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....
refresh div with jquery
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect.
you can try like this
_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
How to get domain root url in Laravel 4?
This is for Laravel 5.1 and I am not sure does it work for earlier versions but if somebody search on Google and lands here it might be handy in middleware handle function gets $request parameter:
$request->server->get('SERVER_NAME')
outside of middleware handle method you can access it by helper function request()
request()->server->get('SERVER_NAME')
Unable to use Intellij with a generated sources folder
You can just change the project structure to add that folder as a "source" directory.
Project Structure ? Modules ? Click the generated-sources
folder and make it a sources
folder.
Or:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>test</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/target/generated-sources</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?
I used an approach described by Eric Daugherty: I created a special servlet that always answers with 403 code and put its mapping before the general one.
Mapping fragment:
<servlet>
<servlet-name>generalServlet</servlet-name>
<servlet-class>project.servlet.GeneralServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>specialServlet</servlet-name>
<servlet-class>project.servlet.SpecialServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>specialServlet</servlet-name>
<url-pattern>/resources/restricted/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>generalServlet</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
And the servlet class:
public class SpecialServlet extends HttpServlet {
public SpecialServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
Change CSS properties on click
This code seems to work fine (see this jsfiddle). Is your javascript defined before your body?
When the browser reads onclick="myFunction()"
it has to know what myFunction
is.
clear javascript console in Google Chrome
There's always the good ol' trick:
console.log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
or a shorter variation of the above:
console.log('\n'.repeat('25'));
Not the most elegant solution, I know :) ... but works.
For me, I usually just print a long "-----" separator line to help make the logs easier to read.
hexadecimal string to byte array in python
A good one liner is:
byte_list = map(ord, hex_string)
This will iterate over each char in the string and run it through the ord() function. Only tested on python 2.6, not too sure about 3.0+.
-Josh
How to select the first element with a specific attribute using XPath
<bookstore>
<book location="US">A1</book>
<category>
<book location="US">B1</book>
<book location="FIN">B2</book>
</category>
<section>
<book location="FIN">C1</book>
<book location="US">C2</book>
</section>
</bookstore>
So Given the above; you can select the first book with
(//book[@location='US'])[1]
And this will find the first one anywhere that has a location US. [A1]
//book[@location='US']
Would return the node set with all books with location US. [A1,B1,C2]
(//category/book[@location='US'])[1]
Would return the first book location US that exists in a category anywhere in the document. [B1]
(/bookstore//book[@location='US'])[1]
will return the first book with location US that exists anywhere under the root element bookstore; making the /bookstore part redundant really. [A1]
In direct answer:
/bookstore/book[@location='US'][1]
Will return you the first node for book element with location US that is under bookstore [A1]
Incidentally if you wanted, in this example to find the first US book that was not a direct child of bookstore:
(/bookstore/*//book[@location='US'])[1]
onchange file input change img src and change image color
Below solution tested and its working, hope it will support in your project.
HTML code:
<input type="file" name="asgnmnt_file" id="asgnmnt_file" class="span8"
style="display:none;" onchange="fileSelected(this)">
<br><br>
<img id="asgnmnt_file_img" src="uploads/assignments/abc.jpg" width="150" height="150"
onclick="passFileUrl()" style="cursor:pointer;">
JavaScript code:
function passFileUrl(){
document.getElementById('asgnmnt_file').click();
}
function fileSelected(inputData){
document.getElementById('asgnmnt_file_img').src = window.URL.createObjectURL(inputData.files[0])
}
Vagrant shared and synced folders
shared folders VS synced folders
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
Vagrantfile directory mounted as /vagrant
in guest
Vagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Why synced folder is not working
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
How to do case insensitive search in Vim
Some important information, if u want to find out more about the commands of vim, as mentioned below u can give a try the following steps :
- invoke the command "help" follow by a space and then complete the word with TAB key, once u find the right command press return key.
:help ignorecase
- information like the following will be displayed :
- you will be able to move forward and backward and also watch the short command, such as the case of "ignorecase" ( 'ic' ). In addition, another short example could be the case of 'smartcase' ('scs' and some more) :
- In order to leave of the documentation just type ":q" as usual and you will return to "command mode" .
:q
I really hope the information provided would be helpful for someone.
Best regards,
Why is exception.printStackTrace() considered bad practice?
In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger and is filled with useless data because usually you have no context and no timestamp and so on.
e.g. catalina.out when using tomcat as container
Python get current time in right timezone
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
How to disable margin-collapsing?
In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root
. However, you would still need other techniques to prevent adjacent element collapsing.
DEMO (before)
_x000D_
_x000D_
.parent {_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
DEMO (after)
_x000D_
_x000D_
.parent {_x000D_
display: flow-root;_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Docker command can't connect to Docker daemon
Had the same issue and what worked for me was:
Checking the ownership of /var/run/docker.sock
ls -l /var/run/docker.sock
If you're not the owner then change ownership with the command
sudo chown *your-username* /var/run/docker.sock
Then you can go ahead and try executing the docker commands hassle-free :D
CMake not able to find OpenSSL library
This is what I added in the CMakeList.txt
(which worked):
# https://cmake.org/cmake/help/latest/command/find_package.html
# in the above link, it states:
# "In Module mode, CMake searches for a file called Find<PackageName>.cmake.
# The file is first searched in the CMAKE_MODULE_PATH, then among the Find
# Modules provided by the CMake installation. If the file is found, it is
# read and processed by CMake. It is responsible for finding the package,
# checking the version, and producing any needed messages. Some find-modules
# provide limited or no support for versioning; check the module documentation."
#
# FindOpenSSL.cmake can be found in path/to/cmake/Modules
#
# https://cmake.org/cmake/help/latest/module/FindOpenSSL.html
#
find_package(OpenSSL REQUIRED)
if (OPENSSL_FOUND)
# Add the include directories for compiling
target_include_directories(${PROJECT_NAME} PUBLIC ${OPENSSL_INCLUDE_DIR})
# Add the static lib for linking
target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto)
message(STATUS "Found OpenSSL ${OPENSSL_VERSION}")
else()
message(STATUS "OpenSSL Not Found")
endif()
remove legend title in ggplot
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
Setting selected values for ng-options bound select elements
Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2
_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId" >_x000D_
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
How to comment out particular lines in a shell script
Yes (although it's a nasty hack). You can use a heredoc thus:
#!/bin/sh
# do valuable stuff here
touch /tmp/a
# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF
What's this doing ? A heredoc
feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with
echo <<EOF
...
EOF
and it'll take all the code contained between the two EOFs and feed them to echo
(echo
doesn't read from stdin so it all gets thrown away).
Note that with the above you can put anything in the heredoc
. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).
This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */
Android: Access child views from a ListView
A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.
Found it here
When do I use the PHP constant "PHP_EOL"?
I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.
For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.
Check out this simple example below:
<?php
$output = 'This is line 1' . PHP_EOL .
'This is line 2' . PHP_EOL .
'This is line 3';
$file = "filename.txt";
if (is_writable($file)) {
// In our example we're opening $file in append mode.
// The file pointer is at the bottom of the file hence
// that's where $output will go when we fwrite() it.
if (!$handle = fopen($file, 'a')) {
echo "Cannot open file ($file)";
exit;
}
// Write $output to our opened file.
if (fwrite($handle, $output) === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
echo "Success, content ($output) wrote to file ($file)";
fclose($handle);
} else {
echo "The file $file is not writable";
}
?>
npm ERR! network getaddrinfo ENOTFOUND
does your proxy require you to authenticate? because if it does, you might want you configure your proxy like this.
placeholder names.
username is a placeholder for your actual username.
password is a placeholder for your actual password.
proxy.company.com is a placeholder for your actualy proxy
*port" is your actualy port the proxy goes through. its usualy 8080
npm config set proxy "http://username:[email protected]:port"
npm config set https-proxy "http://username:[email protected]:port"
How to convert comma-separated String to List?
An example using Collections
.
import java.util.Collections;
...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
...
setImmediate vs. nextTick
I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:
We have two calls that are similar as far as users are concerned, but their names are confusing.
In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.
npm install from Git in a specific version
I needed to run two versions of tfjs-core and found that both needed to be built after being installed.
package.json:
"dependencies": {
"tfjs-core-0.14.3": "git://github.com/tensorflow/tfjs-core#bb0a830b3bda1461327f083ceb3f889117209db2",
"tfjs-core-1.1.0": "git://github.com/tensorflow/tfjs-core#220660ed8b9a252f9d0847a4f4e3c76ba5188669"
}
Then:
cd node_modules/tfjs-core-0.14.3 && yarn install && yarn build-npm && cd ../../
cd node_modules/tfjs-core-1.1.0 && yarn install && yarn build-npm && cd ../../
And finally, to use the libraries:
import * as tf0143 from '../node_modules/tfjs-core-0.14.3/dist/tf-core.min.js';
import * as tf110 from '../node_modules/tfjs-core-1.1.0/dist/tf-core.min.js';
This worked great but is most certainly #hoodrat
bootstrap responsive table content wrapping
EDIT
I think the reason that your table is not responsive to start with was you did not wrap in .container
, .row
and .col-md-x
classes like this one
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- or use any other number .col-md- -->
<div class="table-responsive">
<div class="table">
</div>
</div>
</div>
</div>
</div>
With this, you can still use <p>
tags and even make it responsive.
Please see the Bootply example here
Disable back button in react navigation
The SwitchNavigator would be the way to accomplish this. SwitchNavigator
resets the default routes and unmounts the authentication screen when the navigate
action is invoked.
import { createSwitchNavigator, createStackNavigator, createAppContainer } from 'react-navigation';
// Implementation of HomeScreen, OtherScreen, SignInScreen, AuthLoadingScreen
// goes here.
const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen });
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
));
After the user goes to the SignInScreen and enters their credentials, you would then call
this.props.navigation.navigate('App');
SQL: how to use UNION and order by a specific select?
@Adrien's answer is not working. It gives an ORA-01791.
The correct answer (for the question that is asked) should be:
select id
from
(SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
UNION ALL
SELECT id, 1 as ordered FROM b -- returns 2,1
)
group by id
order by min(ordered)
Explanation:
- The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
- The "group by" is then eliminating duplicates
- The "order by min (ordered)" is assuring the elements of table b are first
This solves all the cases, even when table b has more or different elements then table a
How do I dynamically assign properties to an object in TypeScript?
Index types
It is possible to denote obj
as any
, but that defeats the whole purpose of using typescript. obj = {}
implies obj
is an Object
. Marking it as any
makes no sense. To accomplish the desired consistency an interface could be defined as follows.
interface LooseObject {
[key: string]: any
}
var obj: LooseObject = {};
OR to make it compact:
var obj: {[k: string]: any} = {};
LooseObject
can accept fields with any string as key and any
type as value.
obj.prop = "value";
obj.prop2 = 88;
The real elegance of this solution is that you can include typesafe fields in the interface.
interface MyType {
typesafeProp1?: number,
requiredProp1: string,
[key: string]: any
}
var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number
obj.prop = "value";
obj.prop2 = 88;
Record<Keys,Type>
utility type
Update (August 2020): @transang brought this up in comments
Record<Keys,Type>
is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known.
It's worth noting that Record<Keys,Type>
is a named alias to {[k: Keys]: Type}
where Keys
and Type
are generics.
IMO, this makes it worth mentioning here
For comparison,
var obj: {[k: string]: any} = {};
becomes
var obj: Record<string,any> = {}
MyType
can now be defined by extending Record type
interface MyType extends Record<string,any> {
typesafeProp1?: number,
requiredProp1: string,
}
While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.
Javascript "Not a Constructor" Exception while creating objects
The code as posted in the question cannot generate that error, because Project
is not a user-defined function / valid constructor.
function x(a,b,c){}
new x(1,2,3); // produces no errors
You've probably done something like this:
function Project(a,b,c) {}
Project = {}; // or possibly Project = new Project
new Project(1,2,3); // -> TypeError: Project is not a constructor
Variable declarations using var
are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:
function Project(){}
function localTest() {
new Project(1,2,3); // `Project` points to the local variable,
// not the global constructor!
//...some noise, causing you to forget that the `Project` constructor was used
var Project = 1; // Evaluated first
}
How do the post increment (i++) and pre increment (++i) operators work in Java?
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
<embed> vs. <object>
Answer updated for 2020:
Both <object>
and <embed>
are included in the WHAT-WG HTML Living Standard (Sept 2020).
The object element can represent an external resource, which,
depending on the type of the resource, will either be treated as an
image, as a child browsing context, or as an external resource to be
processed by a plugin.
The embed element provides an integration point for an external (typically non-HTML) application or interactive content.
Are there advantages/disadvantages to using one tag vs. the other?
The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object>
over <embed>
but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.
[...] you are unlikely to use these elements very much — Applets
haven't been used for years, Flash is no longer very popular, due to a
number of reasons (see The case against plugins, below), PDFs tend to
be better linked to than embedded, and other content such as images
and video have much better, easier elements to handle those. Plugins
and these embedding methods are really a legacy technology, and we are
mainly mentioning them in case you come across them in certain
circumstances like intranets, or enterprise projects.
Once upon a time, plugins were indispensable on the Web. Remember the
days when you had to install Adobe Flash Player just to watch a movie
online? And then you constantly got annoying alerts about updating
Flash Player and your Java Runtime Environment. Web technologies have
since grown much more robust, and those days are over. For virtually
all applications, it's time to stop delivering content that depends on
plugins and start taking advantage of Web technologies instead.
Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies#The_%3Cembed%3E_and_%3Cobject%3E_elements
Import Python Script Into Another?
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py
in the same directory.
How to round up a number to nearest 10?
I wanted to round up to the next number in the largest digits place (is there a name for that?), so I made the following function (in php):
//Get the max value to use in a graph scale axis,
//given the max value in the graph
function getMaxScale($maxVal) {
$maxInt = ceil($maxVal);
$numDigits = strlen((string)$maxInt)-1; //this makes 2150->3000 instead of 10000
$dividend = pow(10,$numDigits);
$maxScale= ceil($maxInt/ $dividend) * $dividend;
return $maxScale;
}
Heap space out of memory
I also faced the same problem.I resolved by doing the build by following steps as.
-->Right click on the project select RunAs ->Run configurations
Select your project as BaseDirectory. In place of goals give eclipse:eclipse install
-->In the second tab give -Xmx1024m as VM arguments.
How to calculate the number of days between two dates?
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
How can I simulate an anchor click via jquery?
Do you need to fake an anchor click? From the thickbox site:
ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).
If that is acceptable it should be as easy as putting the thickbox class on the input itself:
<input id="thickboxButton" type="button" class="thickbox" value="Click me">
If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.
Edit:
Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:
<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>
The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.
Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.
Easy way to pull latest of all git submodules
Edit:
In the comments was pointed out (by philfreo ) that the latest version is required. If there is any nested submodules that need to be in their latest version :
git submodule foreach --recursive git pull
-----Outdated comment below-----
Isn't this the official way to do it ?
git submodule update --init
I use it every time. No problems so far.
Edit:
I just found that you can use:
git submodule foreach --recursive git submodule update --init
Which will also recursively pull all of the submodules, i.e. dependancies.
How can I set the 'backend' in matplotlib in Python?
The errors you posted are unrelated. The first one is due to you selecting a backend that is not meant for interactive use, i.e. agg. You can still use (and should use) those for the generation of plots in scripts that don't require user interaction.
If you want an interactive lab-environment, as in Matlab/Pylab, you'd obviously import a backend supporting gui usage, such as Qt4Agg (needs Qt and AGG), GTKAgg (GTK an AGG) or WXAgg (wxWidgets and Agg).
I'd start by trying to use WXAgg, apart from that it really depends on how you installed Python and matplotlib (source, package etc.)
How to catch an Exception from a thread
It is almost always wrong to extend Thread
. I cannot state this strongly enough.
Multithreading Rule #1: Extending Thread
is wrong.*
If you implement Runnable
instead you will see your expected behaviour.
public class Test implements Runnable {
public static void main(String[] args) {
Test t = new Test();
try {
new Thread(t).start();
} catch (RuntimeException e) {
System.out.println("** RuntimeException from main");
}
System.out.println("Main stoped");
}
@Override
public void run() {
try {
while (true) {
System.out.println("** Started");
Thread.sleep(2000);
throw new RuntimeException("exception from thread");
}
} catch (RuntimeException e) {
System.out.println("** RuntimeException from thread");
throw e;
} catch (InterruptedException e) {
}
}
}
produces;
Main stoped
** Started
** RuntimeException from threadException in thread "Thread-0" java.lang.RuntimeException: exception from thread
at Test.run(Test.java:23)
at java.lang.Thread.run(Thread.java:619)
* unless you want to change the way your application uses threads, which in 99.9% of cases you don't. If you think you are in the 0.1% of cases, please see rule #1.
Java Strings: "String s = new String("silly");"
I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.
To illustrate, the following code will print true for the first line, but false for the second:
System.out.println("foo" == "foo");
System.out.println(new String("bar") == new String("bar"));
How to set cookies in laravel 5 independently inside controller
Here is a sample code with explanation.
//Create a response instance
$response = new Illuminate\Http\Response('Hello World');
//Call the withCookie() method with the response method
$response->withCookie(cookie('name', 'value', $minutes));
//return the response
return $response;
Cookie can be set forever by using the forever method as shown in the below code.
$response->withCookie(cookie()->forever('name', 'value'));
Retrieving a Cookie
//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');
How to apply CSS to iframe?
I met this issue with Google Calendar. I wanted to style it on a darker background and change font.
Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents
it is possible to get the
entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php
, which will contain the original content with modifications:
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
Adding the path to your stylesheet:
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
(This will place your stylesheet last just before the head
end tag.)
Specify the base url form the original url in case css and js are called relatively:
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
The final google.php
file should look like this:
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;
Then you change the iframe
embed code to:
<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
Good luck!