How do I get the domain originating the request in express.js?
You have to retrieve it from the HOST
header.
var host = req.get('host');
It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.
If this is for supporting cross-origin requests, you would instead use the Origin
header.
var origin = req.get('origin');
Note that some cross-origin requests require validation through a "preflight" request:
req.options('/route', function (req, res) {
var origin = req.get('origin');
// ...
});
If you're looking for the client's IP, you can retrieve that with:
var userIP = req.socket.remoteAddress;
Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.
How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!
I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:
- The image aspect ratio is preserved
- The image's original size is maintained (that is, it can never shrink only grow)
The markup relies on a wrapper element:
<div id="wrap"><img src="test.png" /></div>
Given the above markup you then use these rules:
#wrap {
height: 100px;
width: 100px;
}
#wrap img {
min-height: 100%;
min-width: 100%;
}
If you then control the size of wrapper you get the interesting scale effects that I list above.
To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.
- Starting at the base state, the
container resized to 20x100, the
image stays resized at 100x100.
- Starting at the base state, the
image is changed to 10x20, the image
resizes to 100x200.
So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.
This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.
Using LINQ to concatenate strings
Here it is using pure LINQ as a single expression:
static string StringJoin(string sep, IEnumerable<string> strings) {
return strings
.Skip(1)
.Aggregate(
new StringBuilder().Append(strings.FirstOrDefault() ?? ""),
(sb, x) => sb.Append(sep).Append(x));
}
And its pretty damn fast!
How do I call an Angular.js filter with multiple arguments?
In templates, you can separate filter arguments by colons.
{{ yourExpression | yourFilter: arg1:arg2:... }}
From Javascript, you call it as
$filter('yourFilter')(yourExpression, arg1, arg2, ...)
There is actually an example hidden in the orderBy filter docs.
Example:
Let's say you make a filter that can replace things with regular expressions:
myApp.filter("regexReplace", function() { // register new filter
return function(input, searchRegex, replaceRegex) { // filter arguments
return input.replace(RegExp(searchRegex), replaceRegex); // implementation
};
});
Invocation in a template to censor out all digits:
<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>
Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
For embeding youtube video into your angularjs page, you can simply use following filter for your video
_x000D_
_x000D_
app.filter('scrurl', function($sce) {_x000D_
return function(text) {_x000D_
text = text.replace("watch?v=", "embed/");_x000D_
return $sce.trustAsResourceUrl(text);_x000D_
};_x000D_
});
_x000D_
<iframe class="ytplayer" type="text/html" width="100%" height="360" src="{{youtube_url | scrurl}}" frameborder="0"></iframe>
_x000D_
_x000D_
_x000D_
How can I git stash a specific file?
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
PHP fwrite new line
Use PHP_EOL
which produces \r\n
or \n
$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);
// File output
my data
my data
SQL Server 2008 can't login with newly created user
If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start
->Programs
->Microsoft SQL Server
-> Configuration tools
-> SQL Server configuration manager
-> Restart Server
.
It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.
Create new XML file and write data to it?
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
String variable interpolation Java
Note that there is no variable interpolation in Java.
Variable interpolation is variable substitution with its value inside a string.
An example in Ruby:
#!/usr/bin/ruby
age = 34
name = "William"
puts "#{name} is #{age} years old"
The Ruby interpreter automatically replaces variables with its values inside a string.
The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby,
it is #{}. In Perl, it could be $, % or @. Java would only print such characters,
it would not expand them.
Variable interpolation is not supported in Java. Instead of this, we
have string formatting.
package com.zetcode;
public class StringFormatting
{
public static void main(String[] args)
{
int age = 34;
String name = "William";
String output = String.format("%s is %d years old.", name, age);
System.out.println(output);
}
}
In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.
See http://en.wikipedia.org/wiki/Variable_interpolation
Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
However, still no string interpolation:
Non-Goals: …
Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method String::formatted
aids in situations where interpolation might be desired.
How to set an iframe src attribute from a variable in AngularJS
Please remove call to trustSrc
function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}.
Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview
But according to the Angular Js 1.2 Documentation, you should write a function for getting
src
url. Have a look on the following code.
Before:
Javascript
scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;
Html
<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"
But for security reason they are recommending following method
Javascript
var baseUrl = "page";
scope.getIframeSrc = function() {
// One should think about their particular case and sanitize accordingly
var qs = ["a", "b"].map(function(value, name) {
return encodeURIComponent(name) + "=" +
encodeURIComponent(value);
}).join("&");
// `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
return baseUrl + "?" + qs;
};
Html
<iframe src="{{getIframeSrc()}}">
How to refresh token with Google API client?
here is the snippet to set token, before that make sure the access type should be set to offline
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
}
To refresh token
$google_token= json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);
this will refresh your token, you have to update it in session for that you can do
$_SESSION['access_token']= $client->getAccessToken()
What's the difference between Sender, From and Return-Path?
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
How to set IE11 Document mode to edge as default?
The rendering mode in Internet Explorer 11 can appear stuck if the site is added to your local Compatibility View list. When this happens, the rendering mode inside the developer tools and out will default to the specified compatibility settings.
While this may not be the only way a site can get on this list, Microsoft does document the steps for how to manually add a site to this list.
To add a site to the Compatibility View list
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button, and then tap or click Compatibility View settings.
Under Add this website, enter the URL of the site you want to add to the list, and then tap or click Add.
Site Compatibility View Removal Instructions:
To remove a site from this list, follow these instructions.
- Go to Tools > Compatibility View settings.
- In the resulting dialog, click on the site you want to remove from the list.
- Click the Remove button.
Screenshots:
Android RelativeLayout programmatically Set "centerInParent"
I have done for
1. centerInParent
2. centerHorizontal
3. centerVertical
with
true and
false.
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
What is the cleanest way to get the progress of JQuery ajax request?
Something like this for $.ajax
(HTML5 only though):
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});
Understanding unique keys for array children in React.js
I fixed this using Guid for each key like this:
Generating Guid:
guid() {
return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
this.s4() + '-' + this.s4() + this.s4() + this.s4();
}
s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
And then assigning this value to markers:
{this.state.markers.map(marker => (
<MapView.Marker
key={this.guid()}
coordinate={marker.coordinates}
title={marker.title}
/>
))}
How to send an object from one Android Activity to another using Intents?
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
For situations where you know the activities are running in the same
process, you can just share data through globals. For example, you
could have a global HashMap<String, WeakReference<MyInterpreterState>>
and when you make a new MyInterpreterState come up with a unique name
for it and put it in the hash map; to send that state to another
activity, simply put the unique name into the hash map and when the
second activity is started it can retrieve the MyInterpreterState from
the hash map with the name it receives.
Nginx 403 error: directory index of [folder] is forbidden
I encountered similar error
--- "403 Forbidden" in the webpage
--- "13: Permission denied" in the error log at /var/log/nginx/error.log
Below 3 Steps worked for me:
1: Open Terminal, saw something like below
user1@comp1:/home/www/
So, my user name is "user1" (from above)
2: Changed user in /etc/nginx/nginx.conf
# user www-data;
user user1;
3: Reloaded the nginx
sudo nginx -s reload
Additionally, I have applied file/folder permissions (before I did above 3 steps)
(755 to my directory, say /dir1/) & (644 for files under that directory):
(I am not sure, if this additional step is really required, just above 3 steps might be enough):
chmod 755 ./dir1/
chmod 644 ./dir1/*.*
Hope this helps quick someone. Best of luck.
SQL JOIN vs IN performance?
The optimizer should be smart enough to give you the same result either way for normal queries. Check the execution plan and they should give you the same thing. If they don't, I would normally consider the JOIN to be faster. All systems are different, though, so you should profile the code on your system to be sure.
How to use HTML Agility pack
I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.
The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.
SQLAlchemy ORDER BY DESCENDING?
You can try: .order_by(ClientTotal.id.desc())
session = Session()
auth_client_name = 'client3'
result_by_auth_client = session.query(ClientTotal).filter(ClientTotal.client ==
auth_client_name).order_by(ClientTotal.id.desc()).all()
for rbac in result_by_auth_client:
print(rbac.id)
session.close()
openCV video saving in python
Try this. It's working for me (Windows 10).
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Jquery Open in new Tab (_blank)
Replace this line:
$(this).target = "_blank";
With:
$( this ).attr( 'target', '_blank' );
That will set its HREF to _blank.
How can you determine a point is between two other points on a line segment?
The scalar product between (c-a) and (b-a) must be equal to the product of their lengths (this means that the vectors (c-a) and (b-a) are aligned and with the same direction). Moreover, the length of (c-a) must be less than or equal to that of (b-a). Pseudocode:
# epsilon = small constant
def isBetween(a, b, c):
lengthca2 = (c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y)
lengthba2 = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if lengthca2 > lengthba2: return False
dotproduct = (c.x - a.x)*(b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0.0: return False
if abs(dotproduct*dotproduct - lengthca2*lengthba2) > epsilon: return False
return True
How to grant "grant create session" privilege?
You can grant system privileges with or without the admin option. The default being without admin option.
GRANT CREATE SESSION TO username
or with admin option:
GRANT CREATE SESSION TO username WITH ADMIN OPTION
The Grantee with the ADMIN OPTION
can grant and revoke privileges to other users
Match linebreaks - \n or \r\n?
Gonna answer in opposite direction.
2) For a full explanation about \r
and \n
I have to refer to this question, which is far more complete than I will post here: Difference between \n and \r?
Long story short, Linux uses \n
for a new-line, Windows \r\n
and old Macs \r
. So there are multiple ways to write a newline. Your second tool (RegExr) does for example match on the single \r
.
1) [\r\n]+
as Ilya suggested will work, but will also match multiple consecutive new-lines. (\r\n|\r|\n)
is more correct.
Why is it bad style to `rescue Exception => e` in Ruby?
Because this captures all exceptions. It's unlikely that your program can recover from any of them.
You should handle only exceptions that you know how to recover from. If you don't anticipate a certain kind of exception, don't handle it, crash loudly (write details to the log), then diagnose logs and fix code.
Swallowing exceptions is bad, don't do this.
Cell Style Alignment on a range
Based on this comment from the OP, "I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment", I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell's alignment property directly, only that cell is affected.
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.
Iterating through all nodes in XML file
This is what I quickly wrote for myself:
public static class XmlDocumentExtensions
{
public static void IterateThroughAllNodes(
this XmlDocument doc,
Action<XmlNode> elementVisitor)
{
if (doc != null && elementVisitor != null)
{
foreach (XmlNode node in doc.ChildNodes)
{
doIterateNode(node, elementVisitor);
}
}
}
private static void doIterateNode(
XmlNode node,
Action<XmlNode> elementVisitor)
{
elementVisitor(node);
foreach (XmlNode childNode in node.ChildNodes)
{
doIterateNode(childNode, elementVisitor);
}
}
}
To use it, I've used something like:
var doc = new XmlDocument();
doc.Load(somePath);
doc.IterateThroughAllNodes(
delegate(XmlNode node)
{
// ...Do something with the node...
});
Maybe it helps someone out there.
Throwing exceptions from constructors
Yes, throwing an exception from the failed constructor is the standard way of doing this. Read this FAQ about Handling a constructor that fails for more information. Having a init() method will also work, but everybody who creates the object of mutex has to remember that init() has to be called. I feel it goes against the RAII principle.
What are ABAP and SAP?
Attempt to provide simplified explanation:
SAP
- Firstly it is a product.
- Owner company, derives its name with the product name "SAP"
- It is a management system (i.e. referred as ERP). Which means, this is a tool used for "managing the system" (domain specific - finance etc.).
Now, that SAP has created an environment around SAP. In order to operate in SAP environment (i.e. for customisations etc.), language-abstraction was required. Here comes ABAP.
ABAP
- It is a language (high level), which is used in the SAP environment for customisations or new feature implementations.
- It is high-level, because, it is known only in SAP environment.
Therefore, any customisation on the basic version of SAP given to some customer of SAP would require ABAP usage, otherwise, just delivered SAP is good enough for usage (i.e. no ABAP required).
Now is another term HANA.
HANA
- This is an in-memory RDBMS.
- Another tool/product by SAP, you would say, and its prime focus is to facilitate "analytics".
- The way, this is designed, gives high compression (column-wise storage) and hence is majorly used for "READ" operations, which is why it is associated with "analysis".
SAP and HANA together abstracts the underlying complexity of database-access queries and UI (developed in java), together, to make the user experience good for the management system (used majorly in analytics, and so that the main focus stays in analytics). This very specific tool/product, is said as "technology", as it has an environment of its own (terminologies etc.). ABAP facilitates further development of the SAP-ERP.
The underlying development is in C, C++ (and ABAP) for SAP.
How can I display an RTSP video stream in a web page?
Roughly you can have 3 choices to display RTSP video stream in a web page:
- Realplayer
- Quicktime player
- VLC player
You can find the code to embed the activeX via google search.
As far as I know, there are some limitations for each player.
- Realplayer does not support H.264 video natively, you must install a quicktime plugin for Realplayer to achieve H.264 decoding.
- Quicktime player does not support RTP/AVP/TCP transport, and it's RTP/AVP (UDP) transport does not include NAT hole punching. Thus the only feasible transport is HTTP tunneling in WAN deployment.
- VLC neither supports NAT hole punching for RTP/AVP transport, but RTP/AVP/TCP transport is available.
MacOSX homebrew mysql root password
Just run this command (where NEWPASS
is your password):
$(brew --prefix mysql)/bin/mysqladmin -u root password NEWPASS
I have had the same error and fixed it this way.
What is ANSI format?
ASCII just defines a 7 bit code page with 128 symbols. ANSI extends this to 8 bit and there are several different code pages for the symbols 128 to 255.
The naming ANSI is not correct because it is actually the ISO/IEC 8859 norm that defines this code pages. See ISO/IEC 8859 for reference. There are 16 code pages ISO/IEC 8859-1 to ISO/IEC 8859-16.
Windows-1252 is again based on ISO/IEC 8859-1 with some modification mainly in the range of the C1 control set in the range 128 to 159. Wikipedia states that Windows-1252 is also refered as ISO-8859-1 with a second hyphen between ISO and 8859. (Unbelievable! Who does something like that?!?)
How add class='active' to html menu with php
seperate your page from nav bar.
pageOne.php:
$page="one";
include("navigation.php");
navigation.php
if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }
<ul class="nav">
<li <?php echo $oneIsActive; ?>><a href="pageOne.php">One</a></li>
<li <?php echo $twoIsActive; ?>><a href="pageTwo.php"><a href="#">Page 2</a></li>
<li <?php echo $threeIsActive; ?>><a href="pageThree.php"><a href="#">Page 3</a></li>
</ul>
I found that I could also set the title of my pages with this method as well.
$page="one";
$title="This is page one."
include("navigation.php");
and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.
Func vs. Action vs. Predicate
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
In a javascript array, how do I get the last 5 elements, excluding the first element?
_x000D_
_x000D_
var y = [1,2,3,4,5,6,7,8,9,10];_x000D_
_x000D_
console.log(y.slice((y.length - 5), y.length))
_x000D_
_x000D_
_x000D_
you can do this!
Changing selection in a select with the Chosen plugin
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
Load arrayList data into JTable
"The problem is that i cant find a way to set a fixed number of rows"
You don't need to set the number of rows. Use a TableModel
. A DefaultTableModel
in particular.
String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
// The 0 argument is number rows.
JTable table = new JTable(tableModel);
Then you can add rows to the tableModel
with an Object[]
Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};
tableModel.addRow(objs);
You can loop to add your Object[] arrays.
Note: JTable does not currently allow instantiation with the input data as an ArrayList
. It must be a Vector
or an array.
See JTable and DefaultTableModel. Also, How to Use JTable tutorial
"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."
You can do something like this to add the data
ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();
originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));
for (int i = 0; i < originalLeagueList.size(); i++){
int position = originalLeagueList.get(i).getPosition();
String name = originalLeagueList.get(i).getName();
int points = originalLeagueList.get(i).getPoinst();
int wins = originalLeagueList.get(i).getWins();
int defeats = originalLeagueList.get(i).getDefeats();
int draws = originalLeagueList.get(i).getDraws();
int totalMatches = originalLeagueList.get(i).getTotalMathces();
int goalF = originalLeagueList.get(i).getGoalF();
int goalA = originalLeagueList.get(i).getGoalA();
in ttgoalD = originalLeagueList.get(i).getTtgoalD();
Object[] data = {position, name, points, wins, defeats, draws,
totalMatches, goalF, goalA, ttgoalD};
tableModel.add(data);
}
How to add elements to an empty array in PHP?
$cart = array();
$cart[] = 11;
$cart[] = 15;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i = 0; $i <= 5; $i++){
$cart[] = $i;
//if you write $cart = [$i]; you will only take last $i value as first element in array.
}
echo "<pre>";
print_r($cart);
echo "</pre>";
How should I pass an int into stringWithFormat?
Is the snippet you posted just a sample to show what you are trying to do?
The reason I ask is that you've named a method increment
, but you seem to be using that to set the value of a text label, rather than incrementing a value.
If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g
You declare a property count
and your increment
action sets this value to whatever, and then in IB, you bind the label's text to the value of count
. As long as you follow Key Value Coding (KVC) with count
, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.
tsconfig.json: Build:No inputs were found in config file
Changing index.js
to index.ts
fixed this error for me. (I did not have any .ts
files before this).
Note: remember to change anywhere you reference index.js
to index.ts
except of course, where you reference your main file. By convention this is probably in your lib
or dist
folders.
My tsconfig.json:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"inlineSourceMap": true,
"noImplicitAny": false
}
}
My outDir
is ./dist
so I reference my main in my package.json as "main": "dist/index.js"
How do I update zsh to the latest version?
If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):
Get the latest version of the ZSH sourcecode
Untar the download into its own directory then install: ./configure && make && make test && sudo make install
This installs the the zsh binary at /usr/local/bin/zsh
.
You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...
To make it your default shell you must first edit /etc/shells
and add the new path. Then you can either run chsh -s /usr/local/bin/zsh
or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".
Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION
. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).
PKIX path building failed: unable to find valid certification path to requested target
If you do not need the SSL security then you might want to switch it off.
/**
* disable SSL
*/
private void disableSslVerification() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
What are Unwind segues for and how do you use them?
Swift iOS:
Step 1: define this method into your MASTER controller view. in which you want to go back:
//pragma mark - Unwind Seques
@IBAction func goToSideMenu(segue: UIStoryboardSegue) {
println("Called goToSideMenu: unwind action")
}
Step 2: (StoryBoard) Right click on you SLAVE/CHILD EXIT button and Select "goToSideMenu" As action to Connect you Button on which you will click to return back to you MASTER controller view:
step 3: Build and Run ...
String comparison using '==' vs. 'strcmp()'
The reason to use it is because strcmp
returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
===
only returns true
or false
, it doesn't tell you which is the "greater" string.
Tools for making latex tables in R
The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.
Change input text border color without changing its height
Try this
<input type="text"/>
It will display same in all cross browser like mozilla , chrome and internet explorer.
<style>
input{
border:2px solid #FF0000;
}
</style>
Dont add style inline because its not good practise, use class to add style for your input box.
How do you implement a re-try-catch?
All a Try-Catch does is allow your program to fail gracefully. In a catch statement, you generally try to log the error, and maybe roll back changes if you need to.
bool finished = false;
while(finished == false)
{
try
{
//your code here
finished = true
}
catch(exception ex)
{
log.error("there was an error, ex");
}
}
Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory
From the start the error message tell you that class is not found : NoClassDefFoundError
that mean the PATH to junit is the problem.
Press right click to project folder and choose Properties OR select project folder and press combination cmd + i.
select from list "Java Build Path".
- select "Libraries" tab
- If JUnit 5(or JUnit 4) is added to "Modulepath", select the "JUnit 5" and press Remove.
- select "Classpath", press "Add Library...".
- from opened "Add Library" window, select JUnit, press next.
- Select JUnit library version that you need and press Finish.
That is all. Try to run test again.
Split a large dataframe into a list of data frames based on common value in column
Stumbled across this answer and I actually wanted BOTH groups (data containing that one user and data containing everything but that one user). Not necessary for the specifics of this post, but I thought I would add in case someone was googling the same issue as me.
df <- data.frame(
ran_data1=rnorm(125),
ran_data2=rnorm(125),
g=rep(factor(LETTERS[1:5]), 25)
)
test_x = split(df,df$g)[['A']]
test_y = split(df,df$g!='A')[['TRUE']]
Here's what it looks like:
head(test_x)
x y g
1 1.1362198 1.2969541 A
6 0.5510307 -0.2512449 A
11 0.0321679 0.2358821 A
16 0.4734277 -1.2889081 A
21 -1.2686151 0.2524744 A
> head(test_y)
x y g
2 -2.23477293 1.1514810 B
3 -0.46958938 -1.7434205 C
4 0.07365603 0.1111419 D
5 -1.08758355 0.4727281 E
7 0.28448637 -1.5124336 B
8 1.24117504 0.4928257 C
How to install XNA game studio on Visual Studio 2012?
There seems to be some confusion over how to get this set up for the Express version specifically. Using the Windows Desktop (WD) version of VS Express 2012, I followed the instructions in Steve B's and Rick Martin's answers with the modifications below.
- In step 2 rather than copying to
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"
, copy to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WDExpressExtensions\Microsoft\XNA Game Studio 4.0"
- In step 4, after making the changes also add the line
<Edition>WDExpress</Edition>
(you should be able to see where it makes sense)
- In step 5, replace
devenv.exe
with WDExpress.exe
- In Rick Martin's step, replace
"%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions"
with "%LocalAppData%\Microsoft\WDExpress\11.0\Extensions"
I haven't done a lot of work since then, but I did manage to create a new game project and it seems fine so far.
Check if a PHP cookie exists and if not set its value
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Source
Programmatically shut down Spring Boot application
Closing a SpringApplication
basically means closing the underlying ApplicationContext
. The SpringApplication#run(String...)
method gives you that ApplicationContext
as a ConfigurableApplicationContext
. You can then close()
it yourself.
For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to shut down...
ctx.close();
}
}
Alternatively, you can use the static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
helper method to do it for you. For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to stop...
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
@Override
public int getExitCode() {
// no errors
return 0;
}
});
// or shortened to
// int exitCode = SpringApplication.exit(ctx, () -> 0);
System.exit(exitCode);
}
}
jQuery get textarea text
Methinks the word "console" is causing the confusion.
If you want to emulate an old-style full/half duplex console, you'd use something like this:
$('console').keyup(function(event){
$.get("url", { keyCode: event.which }, ... );
return true;
});
event.which has the key that was pressed. For backspace handling, event.which === 8.
Best way to remove items from a collection
There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:
shortname => SPRoleAssignment
If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.
Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.
Get a timestamp in C in microseconds?
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
pythonw.exe or python.exe?
If you're going to call a python script from some other process (say, from the command line), use pythonw.exe
. Otherwise, your user will continuously see a cmd
window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an email; python.exe
will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe
avoids this, but still sends the email.
How to generate a random integer number from within a range
Here is a slight simpler algorithm than Ryan Reich's solution:
/// Begin and end are *inclusive*; => [begin, end]
uint32_t getRandInterval(uint32_t begin, uint32_t end) {
uint32_t range = (end - begin) + 1;
uint32_t limit = ((uint64_t)RAND_MAX + 1) - (((uint64_t)RAND_MAX + 1) % range);
/* Imagine range-sized buckets all in a row, then fire randomly towards
* the buckets until you land in one of them. All buckets are equally
* likely. If you land off the end of the line of buckets, try again. */
uint32_t randVal = rand();
while (randVal >= limit) randVal = rand();
/// Return the position you hit in the bucket + begin as random number
return (randVal % range) + begin;
}
Example (RAND_MAX := 16, begin := 2, end := 7)
=> range := 6 (1 + end - begin)
=> limit := 12 (RAND_MAX + 1) - ((RAND_MAX + 1) % range)
The limit is always a multiple of the range,
so we can split it into range-sized buckets:
Possible-rand-output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Buckets: [0, 1, 2, 3, 4, 5][0, 1, 2, 3, 4, 5][X, X, X, X, X]
Buckets + begin: [2, 3, 4, 5, 6, 7][2, 3, 4, 5, 6, 7][X, X, X, X, X]
1st call to rand() => 13
? 13 is not in the bucket-range anymore (>= limit), while-condition is true
? retry...
2nd call to rand() => 7
? 7 is in the bucket-range (< limit), while-condition is false
? Get the corresponding bucket-value 1 (randVal % range) and add begin
=> 3
Running a command in a new Mac OS X Terminal window
In case anyone cares, here's an equivalent for iTerm:
#!/bin/sh
osascript <<END
tell application "iTerm"
tell the first terminal
launch session "Default Session"
tell the last session
write text "cd \"`pwd`\";$1;exit"
end tell
end tell
end tell
END
How to assign from a function which returns more than one value?
(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...]
like this:
library(gsubfn) # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()
If you only need the first or second component these all work too:
list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()
(Of course, if you only needed one value then functionReturningTwoValues()[[1]]
or functionReturningTwoValues()[[2]]
would be sufficient.)
See the cited r-help thread for more examples.
(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with
:
myfun <- function() list(a = 1, b = 2)
list[a, b] <- myfun()
a + b
# same
with(myfun(), a + b)
(3) attach Another alternative is attach:
attach(myfun())
a + b
ADDED: with
and attach
Confused by python file mode "w+"
Actually, there's something wrong about all the other answers about r+
mode.
test.in
file's content:
hello1
ok2
byebye3
And the py script's :
with open("test.in", 'r+')as f:
f.readline()
f.write("addition")
Execute it and the test.in
's content will be changed to :
hello1
ok2
byebye3
addition
However, when we modify the script to :
with open("test.in", 'r+')as f:
f.write("addition")
the test.in
also do the respond:
additionk2
byebye3
So, the r+
mode will allow us to cover the content from the beginning if we did't do the read operation. And if we do some read operation, f.write()
will just append to the file.
By the way, if we f.seek(0,0)
before f.write(write_content)
, the write_content will cover them from the positon(0,0).
What's the proper value for a checked attribute of an HTML checkbox?
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#attr-input-checked :
The disabled content attribute is a boolean attribute.
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />
The following are invalid:
<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
The absence of the attribute is the only valid syntax for false:
<input />
Recommendation
If you care about writing valid XHTML, use checked="checked"
, since <input checked>
is invalid XHTML (but valid HTML) and other alternatives are less readable. Else, just use <input checked>
as it is shorter.
Pass a javascript variable value into input type hidden value
You could give your hidden field an id:
<input type="hidden" id="myField" value="" />
and then when you want to assign its value:
document.getElementById('myField').value = product(2, 3);
Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load
event.
Why Would I Ever Need to Use C# Nested Classes
Nested classes are very useful for implementing internal details that should not be exposed. If you use Reflector to check classes like Dictionary<Tkey,TValue> or Hashtable you'll find some examples.
Decode JSON with unknown structure
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a
Slice instead of Map. So I also added methods to return a Slice from Map, and
Map from Slice. I didnt do one for Slice to Slice, but you could easily add that
if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
Twitter Bootstrap Datepicker within modal window
can you change in your css file bootstrap-timepicker/css/bootstrap-timepicker.css
from
.bootstrap-timepicker-widget.dropdown-menu.open {
display: inline-block;
}
to
.bootstrap-timepicker-widget.dropdown-menu.open {
display: inline-block;
z-index:1151;
}
Delete all rows in table
You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.
See the MySQL 5.1 Reference Manual for the [RENAME TABLE
][1] and [CREATE TABLE
][2] commands.
RENAME TABLE tbl TO tbl_old;
CREATE TABLE tbl LIKE tbl_old;
DROP TABLE tbl_old; -- at your leisure
This approach can help minimize application downtime.
How to map calculated properties with JPA and Hibernate
You have three options:
- either you are calculating the attribute using a
@Transient
method
- you can also use
@PostLoad
entity listener
- or you can use the Hibernate specific
@Formula
annotation
While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:
@Column(name = "price")
private Double price;
@Column(name = "tax_percentage")
private Double taxes;
@Transient
private Double priceWithTaxes;
@PostLoad
private void onLoad() {
this.priceWithTaxes = price * taxes;
}
So, you can use the Hibernate @Formula
like this:
@Formula("""
round(
(interestRate::numeric / 100) *
cents *
date_part('month', age(now(), createdOn)
)
/ 12)
/ 100::numeric
""")
private double interestDollars;
How do you make websites with Java?
Read the tutorial on Java Web applications.
Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.
All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).
Here is a Tomcat tutorial.
Get Multiple Values in SQL Server Cursor
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Cropping an UIImage
(UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
double ratio;
double delta;
CGPoint offset;
//make a new square size, that is the resized imaged width
CGSize sz = CGSizeMake(newSize.width, newSize.width);
//figure out if the picture is landscape or portrait, then
//calculate scale factor and offset
if (image.size.width > image.size.height) {
ratio = newSize.width / image.size.width;
delta = (ratio*image.size.width - ratio*image.size.height);
offset = CGPointMake(delta/2, 0);
} else {
ratio = newSize.width / image.size.height;
delta = (ratio*image.size.height - ratio*image.size.width);
offset = CGPointMake(0, delta/2);
}
//make the final clipping rect based on the calculated values
CGRect clipRect = CGRectMake(-offset.x, -offset.y,
(ratio * image.size.width) + delta,
(ratio * image.size.height) + delta);
//start a new context, with scale factor 0.0 so retina displays get
//high quality image
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
} else {
UIGraphicsBeginImageContext(sz);
}
UIRectClip(clipRect);
[image drawInRect:clipRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
CSS - How to Style a Selected Radio Buttons Label?
You can add a span to your html and css .
Here's an example from my code ...
HTML ( JSX ):
<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>
<label for="radiostyle1"><span></span> am </label>
<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm </label>
CSS to make standard radio button vanish on screen and superimpose custom button image:
input[type="radio"] {
opacity:0;
}
input[type="radio"] + label {
font-size:1em;
text-transform: uppercase;
color: white ;
cursor: pointer;
margin:auto 15px auto auto;
}
input[type="radio"] + label span {
display:inline-block;
width:30px;
height:10px;
margin:1px 0px 0 -30px;
cursor:pointer;
border-radius: 20%;
}
input[type="radio"] + label span {
background-color: #FFFFFF
}
input[type="radio"]:checked + label span{
background-color: #660006;
}
What are .iml files in Android Studio?
Those files are created and used by Android Studio editor.
You don't need to check in those files to version control.
Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.
Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.
How do I replace a character in a string in Java?
//I think this will work, you don't have to replace on the even, it's just an example.
public void emphasize(String phrase, char ch)
{
char phraseArray[] = phrase.toCharArray();
for(int i=0; i< phrase.length(); i++)
{
if(i%2==0)// even number
{
String value = Character.toString(phraseArray[i]);
value = value.replace(value,"*");
phraseArray[i] = value.charAt(0);
}
}
}
Center fixed div with dynamic width (CSS)
You can center a fixed
or absolute
positioned element setting right
and left
to 0
, and then margin-left
& margin-right
to auto
as if you were centering a static
positioned element.
#example {
position: fixed;
/* center the element */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
/* give it dimensions */
min-height: 10em;
width: 90%;
}
Windows equivalent of the 'tail' command
This is a total hack but if it's a huge file that you want to just examine the format, header, etc. and you're looking for a solution you can always just redirect the 'more' output to a new file and CTRL-C quickly. The output rows can't be controlled precisely and you will most likely kill it in the middle of a line of output but it's a cheap way of grabbing a small bit of an otherwise unusable file.
Ex.
C:\more test.csv > test.txt
^C
C:\more test.txt
line 1
line 2
etc......
C:\
Generating a PNG with matplotlib when DISPLAY is undefined
I found this snippet to work well when switching between X and no-X environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
How do I break out of nested loops in Java?
Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position.
Example 1:
loop1:
for(int i= 0; i<6; i++){
for(int j=0; j<5; j++){
if(i==3)
break loop1;
}
}
suppose there are 3 loops and you want to terminate the loop3:
Example 2:
loop3:
for(int i= 0; i<6; i++){
loop2:
for(int k= 0; k<6; k++){
loop1:
for(int j=0; j<5; j++){
if(i==3)
break loop3;
}
}
}
Checking if float is an integer
I'm not 100% sure but when you cast f to an int, and subtract it from f, I believe it is getting cast back to a float. This probably won't matter in this case, but it could present problems down the line if you are expecting that to be an int for some reason.
I don't know if it's a better solution per se, but you could use modulus math instead, for example:
float f = 4.5886;
bool isInt;
isInt = (f % 1.0 != 0) ? false : true;
depending on your compiler you may or not need the .0 after the 1, again the whole implicit casts thing comes into play. In this code, the bool isInt should be true if the right of the decimal point is all zeroes, and false otherwise.
Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine
I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:
- Ensure SQL Express is configured for SQL Authentication as well as Windows Authentication (the default). You do this via SQL Server Management Studio (SSMS) Server Properties/Security
- In SSMS create a new login called "sqlUser", say, with a suitable password, "sql", say. Ensure this new login is set for SQL Authentication, not Windows Authentication. SSMS Server Security/Logins/Properties/General. Also ensure "Enforce password policy" is unchecked
- Under Properties/Server Roles ensure this new user has the "sysadmin" role
- In SQL Server Configuration Manager SSCM (search for SQLServerManagerxx.msc file in Windows\SysWOW64 if you can't find SSCM) under SQL Server Network Configuration/Protocols for SQLExpress make sure TCP/IP is enabled. You can disable Named Pipes if you want
- Right-click protocol TCP/IP and on the IPAddresses tab, ensure every one of the IP addresses is set to Enabled Yes, and TCP Port 1433 (this is the default port for SQL Server)
- In Windows Firewall (WF.msc) create two new Inbound Rules - one for SQL Server and another for SQL Browser Service. For SQL Server you need to open TCP Port 1433 (if you are using the default port for SQL Server) and very importantly for the SQL Browser Service you need to open UDP Port 1434. Name these two rules suitably in your firewall
- Stop and restart the SQL Server Service using either SSCM or the Services.msc snap-in
- In the Services.msc snap-in make sure SQL Browser Service Startup Type is Automatic and then start this service
At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection
How to Convert datetime value to yyyymmddhhmmss in SQL server?
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '')
Insert line at middle of file with Python?
location_of_line = 0
with open(filename, 'r') as file_you_want_to_read:
#readlines in file and put in a list
contents = file_you_want_to_read.readlines()
#find location of what line you want to insert after
for index, line in enumerate(contents):
if line.startswith('whatever you are looking for')
location_of_line = index
#now you have a list of every line in that file
context.insert(location_of_line, "whatever you want to append to middle of file")
with open(filename, 'w') as file_to_write_to:
file_to_write_to.writelines(contents)
That is how I ended up getting whatever data I want to insert to the middle of the file.
this is just pseudo code, as I was having a hard time finding clear understanding of what is going on.
essentially you read in the file to its entirety and add it into a list, then you insert your lines that you want to that list, and then re-write to the same file.
i am sure there are better ways to do this, may not be efficient, but it makes more sense to me at least, I hope it makes sense to someone else.
'namespace' but is used like a 'type'
I had this problem as I created a class "Response.cs" inside a folder named "Response". So VS was catching the new Response ()
as Folder/namespace.
So I changed the class name to StatusResponse.cs and called new StatusResponse()
.This solved the issue.
How to cache data in a MVC application
You can also try and use the caching built into ASP MVC:
Add the following attribute to the controller method you'd like to cache:
[OutputCache(Duration=10)]
In this case the ActionResult of this will be cached for 10 seconds.
More on this here
Looping through dictionary object
You can do it like this.
Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
Console.Write(item.Key);
Console.Write(item.Value.name);
Console.Write(item.Value.age);
}
The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
You should be able to access it from the function inside your controller.
Edit: Adding functional example of the full TestModels
implementation.
Your TestModels
class should look something like this.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You probably want to read up on the dynamic keyword as well.
jQuery slide left and show
And if you want to vary the speed and include callbacks simply add them like this :
jQuery.fn.extend({
slideRightShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, speed, callback);
});
},
slideRightHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, speed, callback);
});
}
});
Installing Git on Eclipse
I made an installation guide for Egit on Eclipse so I thought I would share it.
INSTALL EGIT plugin in eclispe which is pretty easy. If EGit is missing in your Eclipse installation, you can install it via the Eclipse Update Manager via: Help ? Install new Software. EGit can be installed from the following URL: http://download.eclipse.org/egit/updates
Under Eclipse Git Team Provider, tick ONLY "Eclipse EGit" and then download the plugin.
CONNECT TO YOUR LOCAL REPOSITORY. I right clicked on the project, selected "team > share project" and then ticked "use or create repository"
GIT IGNORE. Mark the "bin" folder as "ignored by Git", either by right-clicking on it and selecting Team > Ignore or by creating a .gitignore file. My file was generated for me, I just had to make it visible. Here's how in eclipse: In your package explorer, pull down the menu and select "Filters ...". You can adjust what types of files are shown/hidden there.
IDENTIFY YOURSELF. Click Preferences > Team > Git > Configuration and make sure your name & email are there so we know which user committed/pushed what.
NOW YOU ARE READY TO ADD/COMMIT/PUSH/PULL files with the plugin!
Adding a collaborator to my free GitHub account?
It is pretty easy to add a collaborator to a free plan.
- Navigate to the repository on Github you wish to share with your collaborator.
- Click on the "Settings" tab on the right side of the menu at the top of the screen.
- On the new page, click the "Collaborators" menu item on the left side of the page.
- Start typing the new collaborator's GitHub username into the text box.
- Select the GitHub user from the list that appears below the text box.
- Click the "Add" button.
The added user should now be able to push to your repository on GitHub.
When to use the JavaScript MIME type application/javascript instead of text/javascript?
In theory, according to RFC 4329, application/javascript
.
The reason it is supposed to be application
is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset
parameter. A subtype of text
should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:
a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);
b. browsers use other information—the including page's encoding and in some browsers the script charset
attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)
Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application
type and not technically character-based text
.
For the same reason, application/xml
is officially preferred over text/xml
: XML has its own in-band charset signalling mechanisms. And everyone ignores application
for XML, too.
text/javascript
and text/xml
may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.
Load image from resources
You can do this using the ResourceManager
:
public bool info(string channel)
{
object o = Properties.Resources.ResourceManager.GetObject(channel);
if (o is Image)
{
channelPic.Image = o as Image;
return true;
}
return false;
}
ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()
I think you will understand it through these examples below.
Source code structure:
/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp
Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp
Forward to RELATIVE path:
Using servletRequest.getRequestDispatcher("sample.jsp")
:
http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp
Using servletContext.getRequestDispatcher("sample.jsp")
:
http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
Forward to ABSOLUTE path:
Using servletRequest.getRequestDispatcher("/sample.jsp")
:
http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp
Using servletContext.getRequestDispatcher("/sample.jsp")
:
http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp
Start redis-server with config file
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
Please add a @Pipe/@Directive/@Component annotation. Error
I faced the same error when I used another class instead of component down the component decorator.
Component class must come just after the component decorator
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
export class SmsgtreconComponent implements OnInit {
After moving TodoItemNode to the top of component decorator it worked
Solution
// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
export class TodoItemNode {
children: TodoItemNode[];
item: string;
}
@Component({
selector: 'app-smsgtrecon',
templateUrl: './smsgtrecon.component.html',
styleUrls: ['./smsgtrecon.component.css'],
providers: [ChecklistDatabase]
})
export class SmsgtreconComponent implements OnInit {
What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?
Difference between Spring, Struts and Hibernate are following:
- Spring is an Application Framework but Struts and hibernate is not.
- Spring and Hibernate are Light weighted but Struts 2 is not.
- Spring and Hibernate has layered architecture but Struts 2 doesn't.
- Spring and Hibernate support loose coupling but Struts 2 doesn't.
- Struts 2 and Hibernate have tag library but Spring doesn't.
- Spring and Hibernate have easy integration with ORM technologies but Struts doesn't.
- Struts 2 has easy integration with client-side technologies but Spring and Hibernate don't have.
Get button click inside UITableViewCell
Instead of playing with tags, I took different approach. Made delegate for my subclass of UITableViewCell(OptionButtonsCell) and added an indexPath var. From my button in storyboard I connected @IBAction to the OptionButtonsCell and there I send delegate method with the right indexPath to anyone interested. In cell for index path I set current indexPath and it works :)
Let the code speak for itself:
Swift 3 Xcode 8
OptionButtonsTableViewCell.swift
import UIKit
protocol OptionButtonsDelegate{
func closeFriendsTapped(at index:IndexPath)
}
class OptionButtonsTableViewCell: UITableViewCell {
var delegate:OptionButtonsDelegate!
@IBOutlet weak var closeFriendsBtn: UIButton!
var indexPath:IndexPath!
@IBAction func closeFriendsAction(_ sender: UIButton) {
self.delegate?.closeFriendsTapped(at: indexPath)
}
}
MyTableViewController.swift
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, OptionButtonsDelegate {...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell") as! OptionButtonsTableViewCell
cell.delegate = self
cell.indexPath = indexPath
return cell
}
func closeFriendsTapped(at index: IndexPath) {
print("button tapped at index:\(index)")
}
How to call a JavaScript function, declared in <head>, in the body when I want to call it
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
How can I mock requests and the response?
This is how you can do it (you can run this file as-is):
import requests
import unittest
from unittest import mock
# This is the class we want to test
class MyGreatClass:
def fetch_json(self, url):
response = requests.get(url)
return response.json()
# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
if args[0] == 'http://someurl.com/test.json':
return MockResponse({"key1": "value1"}, 200)
elif args[0] == 'http://someotherurl.com/anothertest.json':
return MockResponse({"key2": "value2"}, 200)
return MockResponse(None, 404)
# Our test case class
class MyGreatClassTestCase(unittest.TestCase):
# We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
# Assert requests.get calls
mgc = MyGreatClass()
json_data = mgc.fetch_json('http://someurl.com/test.json')
self.assertEqual(json_data, {"key1": "value1"})
json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
self.assertEqual(json_data, {"key2": "value2"})
json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
self.assertIsNone(json_data)
# We can even assert that our mocked method was called with the right parameters
self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)
self.assertEqual(len(mock_get.call_args_list), 3)
if __name__ == '__main__':
unittest.main()
Important Note: If your MyGreatClass
class lives in a different package, say my.great.package
, you have to mock my.great.package.requests.get
instead of just 'request.get'. In that case your test case would look like this:
import unittest
from unittest import mock
from my.great.package import MyGreatClass
# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
# Same as above
class MyGreatClassTestCase(unittest.TestCase):
# Now we must patch 'my.great.package.requests.get'
@mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
# Same as above
if __name__ == '__main__':
unittest.main()
Enjoy!
How can I render Partial views in asp.net mvc 3?
Create your partial view something like:
@model YourModelType
<div>
<!-- HTML to render your object -->
</div>
Then in your view use:
@Html.Partial("YourPartialViewName", Model)
If you do not want a strongly typed partial view remove the @model YourModelType
from the top of the partial view and it will default to a dynamic
type.
Update
The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/
in the path below.
@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
Raise an event whenever a property's value changed?
public event EventHandler ImageFullPath1Changed;
public string ImageFullPath1
{
get
{
// insert getter logic
}
set
{
// insert setter logic
// EDIT -- this example is not thread safe -- do not use in production code
if (ImageFullPath1Changed != null && value != _backingField)
ImageFullPath1Changed(this, new EventArgs(/*whatever*/);
}
}
That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.
Rendering partial view on button click in ASP.NET MVC
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
What is the most appropriate way to store user settings in Android application
I agree with Reto and fiXedd. Objectively speaking it doesn't make a lot of sense investing significant time and effort into encrypting passwords in SharedPreferences since any attacker that has access to your preferences file is fairly likely to also have access to your application's binary, and therefore the keys to unencrypt the password.
However, that being said, there does seem to be a publicity initiative going on identifying mobile applications that store their passwords in cleartext in SharedPreferences and shining unfavorable light on those applications. See http://blogs.wsj.com/digits/2011/06/08/some-top-apps-put-data-at-risk/ and http://viaforensics.com/appwatchdog for some examples.
While we need more attention paid to security in general, I would argue that this sort of attention on this one particular issue doesn't actually significantly increase our overall security. However, perceptions being as they are, here's a solution to encrypt the data you place in SharedPreferences.
Simply wrap your own SharedPreferences object in this one, and any data you read/write will be automatically encrypted and decrypted. eg.
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
// eg.
prefs.edit().putString("foo","bar").commit();
prefs.getString("foo", null);
Here's the code for the class:
/**
* Warning, this gives a false sense of security. If an attacker has enough access to
* acquire your password store, then he almost certainly has enough access to acquire your
* source binary and figure out your encryption key. However, it will prevent casual
* investigators from acquiring passwords, and thereby may prevent undesired negative
* publicity.
*/
public class ObscuredSharedPreferences implements SharedPreferences {
protected static final String UTF8 = "utf-8";
private static final char[] SEKRIT = ... ; // INSERT A RANDOM PASSWORD HERE.
// Don't use anything you wouldn't want to
// get out there if someone decompiled
// your app.
protected SharedPreferences delegate;
protected Context context;
public ObscuredSharedPreferences(Context context, SharedPreferences delegate) {
this.delegate = delegate;
this.context = context;
}
public class Editor implements SharedPreferences.Editor {
protected SharedPreferences.Editor delegate;
public Editor() {
this.delegate = ObscuredSharedPreferences.this.delegate.edit();
}
@Override
public Editor putBoolean(String key, boolean value) {
delegate.putString(key, encrypt(Boolean.toString(value)));
return this;
}
@Override
public Editor putFloat(String key, float value) {
delegate.putString(key, encrypt(Float.toString(value)));
return this;
}
@Override
public Editor putInt(String key, int value) {
delegate.putString(key, encrypt(Integer.toString(value)));
return this;
}
@Override
public Editor putLong(String key, long value) {
delegate.putString(key, encrypt(Long.toString(value)));
return this;
}
@Override
public Editor putString(String key, String value) {
delegate.putString(key, encrypt(value));
return this;
}
@Override
public void apply() {
delegate.apply();
}
@Override
public Editor clear() {
delegate.clear();
return this;
}
@Override
public boolean commit() {
return delegate.commit();
}
@Override
public Editor remove(String s) {
delegate.remove(s);
return this;
}
}
public Editor edit() {
return new Editor();
}
@Override
public Map<String, ?> getAll() {
throw new UnsupportedOperationException(); // left as an exercise to the reader
}
@Override
public boolean getBoolean(String key, boolean defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Boolean.parseBoolean(decrypt(v)) : defValue;
}
@Override
public float getFloat(String key, float defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Float.parseFloat(decrypt(v)) : defValue;
}
@Override
public int getInt(String key, int defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Integer.parseInt(decrypt(v)) : defValue;
}
@Override
public long getLong(String key, long defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Long.parseLong(decrypt(v)) : defValue;
}
@Override
public String getString(String key, String defValue) {
final String v = delegate.getString(key, null);
return v != null ? decrypt(v) : defValue;
}
@Override
public boolean contains(String s) {
return delegate.contains(s);
}
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
protected String encrypt( String value ) {
try {
final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);
} catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected String decrypt(String value){
try {
final byte[] bytes = value!=null ? Base64.decode(value,Base64.DEFAULT) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(pbeCipher.doFinal(bytes),UTF8);
} catch( Exception e) {
throw new RuntimeException(e);
}
}
}
issue ORA-00001: unique constraint violated coming in INSERT/UPDATE
The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
Once you know what column(s) are affected, you can compare the data you're trying to INSERT
or UPDATE
against the data already in the table to determine why the constraint is being violated.
Resize height with Highcharts
Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.
This always works:
- Set up a timed and pipelined resize event listener. Example with
500ms on jsFiddle
- use
chart.setSize(width, height, doAnimation =
true);
in your actual resize function to set the height and width
dynamically
- Set
reflow: false
in the highcharts-options and of course set height
and width
explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.
The following artifacts could not be resolved: javax.jms:jms:jar:1.1
Log4 version 1.2.17 automatically resolves the issue as it has depency on geronimo-jms. I got the same issue with log4j- 1.2.15 version.
Added with more around the issue
using 1.2.17 resolved the issue during the compile time but the server(Karaf) was using 1.2.15 version thus creating conflict at run time. Thus I had to switch back to 1.2.15.
The JMS and JMX api were available for me at the runtime thus i did not import the J2ee api.
what i did was I used the compile time dependency on 1.2.17 but removed it at the runtime.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
....
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Import-Package>!org.apache.log4j.*,*</Import-Package>
.....
Adding Table rows Dynamically in Android
Create an init() function and point the table layout.
Then create the needed rows and columns.
public void init() {
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Sl.No ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Product ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Unit Price ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(" Stock Remaining ");
tv3.setTextColor(Color.WHITE);
tbrow0.addView(tv3);
stk.addView(tbrow0);
for (int i = 0; i < 25; i++) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText("" + i);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("Product " + i);
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText("Rs." + i);
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
TextView t4v = new TextView(this);
t4v.setText("" + i * 15 / 32 * 10);
t4v.setTextColor(Color.WHITE);
t4v.setGravity(Gravity.CENTER);
tbrow.addView(t4v);
stk.addView(tbrow);
}
}
Call init function in your onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
}
Layout file like:
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >
<HorizontalScrollView
android:id="@+id/hscrll1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/table_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Will look like:
Python strip() multiple characters?
Because that's not what strip()
does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.
You could do:
name= name.replace('(', '').replace(')', '').replace ...
or:
name= ''.join(c for c in name if c not in '(){}<>')
or maybe use a regex:
import re
name= re.sub('[(){}<>]', '', name)
How to get the query string by javascript?
You can use this Javascript :
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
OR
You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.
Usage is very simple and cool:
$.url().param("itemID")
via James&Alfa
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
How to get single value of List<object>
You can access the fields by indexing the object array:
foreach (object[] item in selectedValues)
{
idTextBox.Text = item[0];
titleTextBox.Text = item[1];
contentTextBox.Text = item[2];
}
That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:
public class MyObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Then you can do:
foreach (MyObject item in selectedValues)
{
idTextBox.Text = item.Id;
titleTextBox.Text = item.Title;
contentTextBox.Text = item.Content;
}
Play a Sound with Python
After the play() command add a delay of say 10 secs or so, it'll work
import pygame
import time
pygame.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
time.sleep(10)
This also plays .mp3 files.
Control cannot fall through from one case label
You missed break statements. Don't forget to use break
-statements even in the default
case.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
default:
Console.WriteLine("Default case handling");
break;
}
How can I get name of element with jQuery?
Play around with this jsFiddle example:
HTML:
<p id="foo" name="bar">Hello, world!</p>
jQuery:
$(function() {
var name = $('#foo').attr('name');
alert(name);
console.log(name);
});
This uses jQuery's .attr() method to get value for the first element in the matched set.
While not specifically jQuery, the result is shown as an alert prompt and written to the browser's console.
Spring: How to inject a value to static field?
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
"java.lang.OutOfMemoryError : unable to create new native Thread"
I had this same issue and it turned out to be an improper usage of an java API. I was initializing a builder in a batch processing method that was that not supposed to be initiallized more than once.
Basically I was doing something like:
for (batch in batches) {
process_batch(batch)
}
def process_batch(batch) {
var client = TransportClient.builder().build()
client.processList(batch)
}
when I should have done this:
for (batch in batches) {
var client = TransportClient.builder().build()
process_batch(batch, client)
}
def process_batch(batch, client) {
client.processList(batch)
}
How to deal with SQL column names that look like SQL keywords?
If it had been in PostgreSQL, use double quotes around the name, like:
select "from" from "table";
Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.
How to list the contents of a package using YUM?
There are several good answers here, so let me provide a terrible one:
: you can type in anything below, doesnt have to match anything
yum whatprovides "me with a life"
: result of the above (some liberties taken with spacing):
Loaded plugins: fastestmirror
base | 3.6 kB 00:00
extras | 3.4 kB 00:00
updates | 3.4 kB 00:00
(1/4): extras/7/x86_64/primary_db | 166 kB 00:00
(2/4): base/7/x86_64/group_gz | 155 kB 00:00
(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04
(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05
Determining fastest mirrors
* base: mirrors.xmission.com
* extras: mirrors.xmission.com
* updates: mirrors.xmission.com
base/7/x86_64/filelists_db | 6.2 MB 00:02
extras/7/x86_64/filelists_db | 468 kB 00:00
updates/7/x86_64/filelists_db | 5.3 MB 00:01
No matches found
: the key result above is that "primary_db" files were downloaded
: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf
: note you can limit this to "primary_db.sqlite" if you really want
find /var/cache/yum -name '*.sqlite'
: if you download/install a new repo, run the exact same command again
: to get the databases for the new repo
: if you know sqlite you can stop reading here
: if not heres a sample command to dump the contents
echo 'SELECT packages.name, GROUP_CONCAT(files.name, ", ") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite
: remove "LIMIT 10" above for the whole list
: format chosen for proof-of-concept purposes, probably can be improved a lot
jQuery Refresh/Reload Page if Ajax Success after time
I prefer this way
Using ajaxStop
+ setInterval
,, this will refresh the page after any XHR[ajax] request in the same page
$(document).ajaxStop(function() {
setInterval(function() {
location.reload();
}, 3000);
});
Java: Converting String to and from ByteBuffer and associated problems
Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)
However, the method in question (in this discussion) is a variant of encode - encode(CharBuffer in). This is a convenience method that implements the entire encoding operation. (Please see java docs reference in P.S.)
As per the docs, This method should therefore not be invoked if an encoding operation is already in progress (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).
Personally, I like to use convenience methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers.
ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:
- Create a new encoder/decoder object when needed for each operation (not efficient as it could lead to a large number of objects). OR,
- Use a ThreadLocal to avoid creating new encoder/decoder for each operation. OR,
- Synchronize the entire encoding/decoding operation (this might not be preferred unless sacrificing some concurrency is ok for your program)
P.S.
java docs references:
- Encode (convenience) method: http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html#encode%28java.nio.CharBuffer%29
- General encode method: http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html#encode%28java.nio.CharBuffer,%20java.nio.ByteBuffer,%20boolean%29
Java - remove last known item from ArrayList
clients.get
will return a ClientThread
and not a String
, and it will bomb with an IndexOutOfBoundsException
if it would compile as Java is zero based for indexing.
Similarly I think you should call remove
on the clients
list.
ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
I would use the stack functions of a LinkedList
in this case though.
ClientThread hey = clients.removeLast()
HTML form submit to PHP script
Here is what I find works
- Set a
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
- Try to use HTML5 attributes now they are supported.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
javax.naming.NameNotFoundException
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class
/com/mypackage/MyEJBInterface.class
/com/mypackage/etc... etc... java classes
/META-INF/ejb-jar.xml
/META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
What is the difference between substr and substring?
substring
(MDN) takes parameters as (from, to)
.
substr
(MDN) takes parameters as (from, length)
.
Update: MDN considers substr
legacy.
alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"
You can remember substring
(with an i) takes indices, as does yet another string extraction method, slice (with an i).
When starting from 0 you can use either method.
Calling virtual functions inside constructors
During the object's constructor call the virtual function pointer table is not completely built. Doing this will usually not give you the behavior you expect. Calling a virtual function in this situation may work but is not guaranteed and should be avoided to be portable and follow the C++ standard.
Send POST request using NSURLSession
If you are using Swift, the Just library does this for you. Example from it's readme file:
// talk to registration end point
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
if (r.ok) { /* success! */ }
}