IOPub data rate exceeded in Jupyter notebook (when viewing image)
Some additional advice for Windows(10) users:
- If you are using Anaconda Prompt/PowerShell for the first time, type "Anaconda" in the search field of your Windows task bar and you will see the suggested software.
- Make sure to open the Anaconda prompt as administrator.
- Always navigate to your user directory or the directory with your Jupyter Notebook files first before running the command. Otherwise you might end up somewhere in your system files and be confused by an unfamiliar file tree.
The correct way to open Jupyter notebook with new data limit from the Anaconda Prompt on my own Windows 10 PC is:
(base) C:\Users\mobarget\Google Drive\Jupyter Notebook>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
Reportviewer tool missing in visual studio 2017 RC
Update: this answer works with both ,Visual Sudio 2017 and 2019
For me it worked by the following three steps:
- Updating Visual Studio to the latest build.
- Adding Report / Report Wizard to the Add/New Item menu by:
- Going to Visual Studio menu Tools/Extensions and Updates
- Choose Online from the left panel.
- Search for Microsoft Rdlc Report Designer for Visual Studio
- Download and install it.
Adding Report viewer control by:
For WebForms applications:
- The same.
- The same.
Adding Report viewer control by:
That's all!
Get only specific attributes with from Laravel Collection
You can do this using a combination of existing Collection
methods. It may be a little hard to follow at first, but it should be easy enough to break down.
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
return collect($user->toArray())
->only(['id', 'name', 'email'])
->all();
});
Explanation
First, the map()
method basically just iterates through the Collection
, and passes each item in the Collection
to the passed in callback. The value returned from each call of the callback builds the new Collection
generated by the map()
method.
collect($user->toArray())
is just building a new, temporary Collection
out of the Users
attributes.
->only(['id', 'name', 'email'])
reduces the temporary Collection
down to only those attributes specified.
->all()
turns the temporary Collection
back into a plain array.
Put it all together and you get "For each user in the users collection, return an array of just the id, name, and email attributes."
Laravel 5.5 update
Laravel 5.5 added an only
method on the Model, which basically does the same thing as the collect($user->toArray())->only([...])->all()
, so this can be slightly simplified in 5.5+ to:
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
return $user->only(['id', 'name', 'email']);
});
If you combine this with the "higher order messaging" for collections introduced in Laravel 5.4, it can be simplified even further:
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map->only(['id', 'name', 'email']);
Route.get() requires callback functions but got a "object Undefined"
I had the same error. The problem was in the export and import of the modules.
Example of my solution:
Controller (File: posts.js)
exports.getPosts = (req, res) => {
res.json({
posts: [
{ tittle: 'First posts' },
{ tittle: 'Second posts' },
]
});
};
Router (File: posts.js)
const express = require('express');
const { getPosts } = require('../controllers/posts');
const routerPosts = express.Router();
routerPosts.get('/', getPosts);
exports.routerPosts = routerPosts;
Main (File: app.js)
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { routerPosts } = require('./routes/posts');
const app = express();
const port = process.env.PORT || 3000;
dotenv.config();
// Middleware
app.use(morgan('dev'));
app.use('/', routerPosts);
app.listen(port, () => {
console.log(`A NodeJS API is listining on port: ${port}`);
});
Running the application (chrome output)
// 20200409002022
// http://localhost:3000/
{
"posts": [
{
"tittle": "First posts"
},
{
"tittle": "Second posts"
}
]
}
Console Log
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev
> [email protected] dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 304 5.093 ms - -
GET / 304 0.714 ms - -
GET / 304 0.653 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 200 4.427 ms - 62
GET / 304 0.783 ms - -
GET / 304 0.642 ms - -
Node Version
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ node -v
v13.12.0
NPM Version
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ npm -v
6.14.4
CodeIgniter: 404 Page Not Found on Live Server
I have solved this problem, please just make few changes
1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages
so it should be Pages not pages
2- save the controller class Pages as Pages.php
not pages.php
so first letter must be capital
same for model, model class first letter should be capital and also save model class as Pages_model.php
not page_model.php
hope this will solve ur problem
Xcode 6 Storyboard the wrong size?
Do the following steps to resolve the issue
In Storyboard, select any view, then go to the File inspector. Uncheck the "Use Size Classes", you will ask to keep size class data for: iPhone/iPad. And then Click the "Disable Size Classes" button.
Doing this will make the storyboard's view size with selected device.
Test credit card numbers for use with PayPal sandbox
If a credit card is already added to a PayPal account then it won't let you use that card to process directly with Payments Advanced. The system expects buyers to login to PayPal and just choose that credit card as their funding source if they want to pay with it.
As for testing on the sandbox, I've always used old, expired credit cards I have laying around and they seem to work fine for me.
You could always try the ones starting on page 87 of the PayFlow documentation, too. They should work.
HTML embedded PDF iframe
Try this out.
_x000D_
_x000D_
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
_x000D_
_x000D_
Send text to specific contact programmatically (whatsapp)
I think the answer is a mix of your question and this answer here: https://stackoverflow.com/a/15931345/734687
So I would try the following code:
- change ACTION_VIEW to ACTION_SENDTO
- set the Uri as you did
- set the package to whatsapp
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp"); // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);
I looked into the Whatsapp manifest and saw that ACTION_SEND is registered to the activity ContactPicker
, so that will not help you. However ACTION_SENDTO is registered to the activity com.whatsapp.Conversation
which sounds more adequate for your problem.
Whatsapp can work as a replacement for sending SMS, so it should work like SMS. When you do not specify the desired application (via setPackage
) Android displays the application picker. Thererfor you should just look at the code for sending SMS via intent and then provide the additional package information.
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);
i.setPackage("com.whatsapp");
startActivity(i);
First try just to replace the intent ACTION_SEND
to ACTION_SENDTO
. If this does not work than provide the additional extra sms_body
. If this does not work than try to change the uri.
Update
I tried to solve this myself and was not able to find a solution. Whatsapp is opening the chat history, but doesn't take the text and send it. It seems that this functionality is just not implemented.
How to change navbar/container width? Bootstrap 3
just simple:
.navbar{
width:65% !important;
margin:0px auto;
left:0;
right:0;
padding:0;
}
or,
.navbar.navbar-fixed-top{
width:65% !important;
margin:0px auto;
left:0;
right:0;
padding:0;
}
Hope it works (at least, for future searchers)
relative path to CSS file
You have to move the css
folder into your web
folder. It seems that your web
folder on the hard drive equals the /ServletApp
folder as seen from the www. Other content than inside your web
folder cannot be accessed from the browsers.
The url of the CSS link is then
<link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?
Because your update
uses PUT method, {entryId: $scope.entryId}
is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'}
when you define your update
, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '@entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
Viewing localhost website from mobile device
Know your host ip address on your lan
Open cmd and type ipconfig and the if xampp the default listen port would be 80
Then for instance if 10.0.0.5 is your host ip address
Type 10.0.0.5:80 from your mobile's web browser
Make sure that both are connected to the same LAN
However the default port that webaddress tries is 80.
Very Simple Image Slider/Slideshow with left and right button. No autoplay
After reading your comment on my previous answer I thought I might put this as a separate answer.
Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.
That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with
WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/
This is the jQuery
$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
}
else{
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
}
else{
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
});
So now the explanation.
Stage 1
1) Load the script on document ready.
2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.
3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;
Stage 2
Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.
2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.
3) We remove the class oldActive because it's no longer needed.
4) fadeOut all of the slides
5) fade In the active slides
Step 3
Same as in step two but using some reverse logic for traversing through the elements backwards.
It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
Pandas: Setting no. of max rows
Set display.max_rows
:
pd.set_option('display.max_rows', 500)
For older versions of pandas (<=0.11.0) you need to change both display.height
and display.max_rows
.
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
See also pd.describe_option('display')
.
You can set an option only temporarily for this one time like this:
from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
display(df) #need display to show the dataframe when using with in jupyter
#some pandas stuff
You can also reset an option back to its default value like this:
pd.reset_option('display.max_rows')
And reset all of them back:
pd.reset_option('all')
Javascript, viewing [object HTMLInputElement]
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}
Removing certain characters from a string in R
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits.
If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
How to compress an image via Javascript in the browser?
I find that there's simpler solution compared to the accepted answer.
Read the files using the HTML5 FileReader API with .readAsArrayBuffer
- Create a Blob with the file data and get its url with
window.URL.createObjectURL(blob)
- Create new Image element and set it's src to the file blob url
- Send the image to the canvas. The canvas size is set to desired output size
- Get the scaled-down data back from canvas
via canvas.toDataURL("image/jpeg",0.7)
(set your own output format and quality)
- Attach new hidden inputs to the original form
and transfer the dataURI images basically as normal text
On backend, read the dataURI, decode from Base64, and save it
As per your question:
Is there a way to compress an image (mostly jpeg, png and gif)
directly browser-side, before uploading it
My solution:
Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0])
.
Same as accepted answer.
Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width
and img.height
to set canvas.width
and canvas.height
. Not img.clientWidth
.
Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5)
. Setting 'image/jpg'
has no effect. image/png
is also supported. Make a new File
object inside the callbackfunction
body with let compressedImageBlob = new File([blob])
.
Add new hidden inputs or send via javascript . Server doesn't have to decode anything.
Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.
Code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" multiple>
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
This code looks far less scary than the other answers..
Update:
One has to put everything inside img.onload
. Otherwise canvas
will not be able to get the image's width and height correctly as the time canvas
is assigned.
function upload(){
var f = fileToUpload.files[0];
var fileName = f.name.split('.')[0];
var img = new Image();
img.src = URL.createObjectURL(f);
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(blob){
console.info(blob.size);
var f2 = new File([blob], fileName + ".jpeg");
var xhr = new XMLHttpRequest();
var form = new FormData();
form.append("fileToUpload", f2);
xhr.open("POST", "upload.php");
xhr.send(form);
}, 'image/jpeg', 0.5);
}
}
3.4MB
.png
file compression test with image/jpeg
argument set.
|0.9| 777KB |
|0.8| 383KB |
|0.7| 301KB |
|0.6| 251KB |
|0.5| 219kB |
HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set
I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
Iterator Loop vs index loop
By writing your client code in terms of iterators you abstract away the container completely.
Consider this code:
class ExpressionParser // some generic arbitrary expression parser
{
public:
template<typename It>
void parse(It begin, const It end)
{
using namespace std;
using namespace std::placeholders;
for_each(begin, end,
bind(&ExpressionParser::process_next, this, _1);
}
// process next char in a stream (defined elsewhere)
void process_next(char c);
};
client code:
ExpressionParser p;
std::string expression("SUM(A) FOR A in [1, 2, 3, 4]");
p.parse(expression.begin(), expression.end());
std::istringstream file("expression.txt");
p.parse(std::istringstream<char>(file), std::istringstream<char>());
char expr[] = "[12a^2 + 13a - 5] with a=108";
p.parse(std::begin(expr), std::end(expr));
Edit: Consider your original code example, implemented with :
using namespace std;
vector<int> myIntVector;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);
copy(myIntVector.begin(), myIntVector.end(),
std::ostream_iterator<int>(cout, " "));
How can I open the interactive matplotlib window in IPython notebook?
A better solution for your problem might be the Charts library. It enables you to use the excellent Highcharts javascript library to make beautiful and interactive plots. Highcharts uses the HTML svg
tag so all your charts are actually vector images.
Some features:
- Vector plots which you can download in .png, .jpg and .svg formats so you will never run into resolution problems
- Interactive charts (zoom, slide, hover over points, ...)
- Usable in an IPython notebook
- Explore hundreds of data structures at the same time using the asynchronous plotting capabilities.
Disclaimer: I'm the developer of the library
git undo all uncommitted or unsaved changes
This will unstage all files you might have staged with git add
:
git reset
This will revert all local uncommitted changes (should be executed in repo root):
git checkout .
You can also revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):
git reset --hard HEAD
This will remove all local untracked files, so only git tracked files remain:
git clean -fdx
WARNING: -x
will also remove all ignored files, including ones specified by .gitignore
! You may want to use -n
for preview of files to be deleted.
To sum it up: executing commands below is basically equivalent to fresh git clone
from original source (but it does not re-download anything, so is much faster):
git reset
git checkout .
git clean -fdx
Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.
Commit history on remote repository
git
isn't a centralized scm like svn
so you have two options:
It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.
An example with fetching into a temporary directory:
git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline
Alternatively:
git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master
Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.
An example with GitHub:
GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3
An example with GitLab:
GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3
Both are really fast but have different interfaces (like every platform).
Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement
add onclick function to a submit button
html:
<form method="post" name="form1" id="form1">
<input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>
Javascript:
to submit the form using javascript
function eatFood() {
document.getElementById('form1').submit();
}
to show onclick message
function eatFood() {
alert('Form has been submitted');
}
Viewing root access files/folders of android on windows
You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.
EDIT:
If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.
Throw HttpResponseException or return Request.CreateErrorResponse?
The approach I have taken is to just throw exceptions from the api controller actions and have an exception filter registered that processes the exception and sets an appropriate response on the action execution context.
The filter exposes a fluent interface that provides a means of registering handlers for specific types of exceptions prior to registering the filter with global configuration.
The use of this filter enables centralized exception handling instead of spreading it across the controller actions. There are however cases where I will catch exceptions within the controller action and return a specific response if it does not make sense to centralize the handling of that particular exception.
Example registration of filter:
GlobalConfiguration.Configuration.Filters.Add(
new UnhandledExceptionFilterAttribute()
.Register<KeyNotFoundException>(HttpStatusCode.NotFound)
.Register<SecurityException>(HttpStatusCode.Forbidden)
.Register<SqlException>(
(exception, request) =>
{
var sqlException = exception as SqlException;
if (sqlException.Number > 50000)
{
var response = request.CreateResponse(HttpStatusCode.BadRequest);
response.ReasonPhrase = sqlException.Message.Replace(Environment.NewLine, String.Empty);
return response;
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
)
);
UnhandledExceptionFilterAttribute class:
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;
namespace Sample
{
/// <summary>
/// Represents the an attribute that provides a filter for unhandled exceptions.
/// </summary>
public class UnhandledExceptionFilterAttribute : ExceptionFilterAttribute
{
#region UnhandledExceptionFilterAttribute()
/// <summary>
/// Initializes a new instance of the <see cref="UnhandledExceptionFilterAttribute"/> class.
/// </summary>
public UnhandledExceptionFilterAttribute() : base()
{
}
#endregion
#region DefaultHandler
/// <summary>
/// Gets a delegate method that returns an <see cref="HttpResponseMessage"/>
/// that describes the supplied exception.
/// </summary>
/// <value>
/// A <see cref="Func{Exception, HttpRequestMessage, HttpResponseMessage}"/> delegate method that returns
/// an <see cref="HttpResponseMessage"/> that describes the supplied exception.
/// </value>
private static Func<Exception, HttpRequestMessage, HttpResponseMessage> DefaultHandler = (exception, request) =>
{
if(exception == null)
{
return null;
}
var response = request.CreateResponse<string>(
HttpStatusCode.InternalServerError, GetContentOf(exception)
);
response.ReasonPhrase = exception.Message.Replace(Environment.NewLine, String.Empty);
return response;
};
#endregion
#region GetContentOf
/// <summary>
/// Gets a delegate method that extracts information from the specified exception.
/// </summary>
/// <value>
/// A <see cref="Func{Exception, String}"/> delegate method that extracts information
/// from the specified exception.
/// </value>
private static Func<Exception, string> GetContentOf = (exception) =>
{
if (exception == null)
{
return String.Empty;
}
var result = new StringBuilder();
result.AppendLine(exception.Message);
result.AppendLine();
Exception innerException = exception.InnerException;
while (innerException != null)
{
result.AppendLine(innerException.Message);
result.AppendLine();
innerException = innerException.InnerException;
}
#if DEBUG
result.AppendLine(exception.StackTrace);
#endif
return result.ToString();
};
#endregion
#region Handlers
/// <summary>
/// Gets the exception handlers registered with this filter.
/// </summary>
/// <value>
/// A <see cref="ConcurrentDictionary{Type, Tuple}"/> collection that contains
/// the exception handlers registered with this filter.
/// </value>
protected ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> Handlers
{
get
{
return _filterHandlers;
}
}
private readonly ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> _filterHandlers = new ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>>();
#endregion
#region OnException(HttpActionExecutedContext actionExecutedContext)
/// <summary>
/// Raises the exception event.
/// </summary>
/// <param name="actionExecutedContext">The context for the action.</param>
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if(actionExecutedContext == null || actionExecutedContext.Exception == null)
{
return;
}
var type = actionExecutedContext.Exception.GetType();
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;
if (this.Handlers.TryGetValue(type, out registration))
{
var statusCode = registration.Item1;
var handler = registration.Item2;
var response = handler(
actionExecutedContext.Exception.GetBaseException(),
actionExecutedContext.Request
);
// Use registered status code if available
if (statusCode.HasValue)
{
response.StatusCode = statusCode.Value;
}
actionExecutedContext.Response = response;
}
else
{
// If no exception handler registered for the exception type, fallback to default handler
actionExecutedContext.Response = DefaultHandler(
actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
);
}
}
#endregion
#region Register<TException>(HttpStatusCode statusCode)
/// <summary>
/// Registers an exception handler that returns the specified status code for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to register a handler for.</typeparam>
/// <param name="statusCode">The HTTP status code to return for exceptions of type <typeparamref name="TException"/>.</param>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler has been added.
/// </returns>
public UnhandledExceptionFilterAttribute Register<TException>(HttpStatusCode statusCode)
where TException : Exception
{
var type = typeof(TException);
var item = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
statusCode, DefaultHandler
);
if (!this.Handlers.TryAdd(type, item))
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;
if (this.Handlers.TryRemove(type, out oldItem))
{
this.Handlers.TryAdd(type, item);
}
}
return this;
}
#endregion
#region Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
/// <summary>
/// Registers the specified exception <paramref name="handler"/> for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to register the <paramref name="handler"/> for.</typeparam>
/// <param name="handler">The exception handler responsible for exceptions of type <typeparamref name="TException"/>.</param>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception <paramref name="handler"/>
/// has been added.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <see langword="null"/>.</exception>
public UnhandledExceptionFilterAttribute Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
where TException : Exception
{
if(handler == null)
{
throw new ArgumentNullException("handler");
}
var type = typeof(TException);
var item = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
null, handler
);
if (!this.Handlers.TryAdd(type, item))
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;
if (this.Handlers.TryRemove(type, out oldItem))
{
this.Handlers.TryAdd(type, item);
}
}
return this;
}
#endregion
#region Unregister<TException>()
/// <summary>
/// Unregisters the exception handler for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to unregister handlers for.</typeparam>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler
/// for exceptions of type <typeparamref name="TException"/> has been removed.
/// </returns>
public UnhandledExceptionFilterAttribute Unregister<TException>()
where TException : Exception
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> item = null;
this.Handlers.TryRemove(typeof(TException), out item);
return this;
}
#endregion
}
}
Source code can also be found here.
How do you view ALL text from an ntext or nvarchar(max) in SSMS?
PowerShell Alternative
This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.
Start by installing the SqlServer
module from an administrative PowerShell.
Install-Module -Name SqlServer
Use Invoke-Sqlcmd
to run your query:
$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
-As DataRows -MaxCharLength 1000000 -ConnectionString $ConnectionString
This will return an array of rows that you can output to the console as follows:
$Rows[0].BigColumn
Or output to a file as follows:
$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8
The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.
EDIT: It turns out that there was an answer by @dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.
How to solve the “failed to lazily initialize a collection of role” Hibernate exception
The problem is caused because the code is accessing a lazy JPA relation when the "connection" to the database is closed (persistence context is the correct name in terms of Hibernate/JPA).
A simple way of solving it in Spring Boot is by defining a service layer and using the @Transactional
annotation. This annotation in a method creates a transaction that propagates into the repository layer and keeps open the persistence context until the method finish. If you access the collection inside the transactional method Hibernate/JPA will fetch the data from the database.
In your case, you just need to annotate with @Transactional
the method findTopicByID(id)
in your TopicService
and force the fetch of the collection in that method (for instance, by asking its size):
@Transactional(readOnly = true)
public Topic findTopicById(Long id) {
Topic topic = TopicRepository.findById(id).orElse(null);
topic.getComments().size();
return topic;
}
Using Chrome's Element Inspector in Print Preview Mode?
With shortcuts available, the quickest way is to
Open the Developer Tools
- Windows: F12 or Ctrl+Shift+I
- Mac: Cmd+Opt+I
Open the Command Menu
- Windows: Ctrl+Shift+P
- Mac: Cmd+Shift+P
Type print
and select Emulate CSS print media type from the context menu
Looking at the excellent and currently most-upvoted answer by lmeurs, I think this solution might also remain stable over time.
Viewing local storage contents on IE
In IE11, you can see local storage in console on dev tools:
- Show dev tools (press F12)
- Click "Console" or press Ctrl+2
- Type
localStorage
and press Enter
Also, if you need to clear the localStorage, type localStorage.clear()
on console.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Calling a Javascript Function from Console
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
}
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
}
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
how to automatically scroll down a html page?
You can use .scrollIntoView()
for this. It will bring a specific element into the viewport.
Example:
document.getElementById( 'bottom' ).scrollIntoView();
Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/
Script:
function top() {
document.getElementById( 'top' ).scrollIntoView();
};
function bottom() {
document.getElementById( 'bottom' ).scrollIntoView();
window.setTimeout( function () { top(); }, 2000 );
};
bottom();
HTML:
<div id="top">top</div>
<div id="bottom">bottom</div>
CSS:
#top {
border: 1px solid black;
height: 3000px;
}
#bottom {
border: 1px solid red;
}
How to get the cursor to change to the hand when hovering a <button> tag
see:
https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
so you need to add: cursor:pointer;
In your case use:
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use
<input type="button" id="more" />
If you want to apply this to more than one button then you have more than one possibility:
using CLASS
.more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />
or apply to a html context:
input[type=button] {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" value="first" />
<input type="button" value="second" />
htaccess <Directory> deny from all
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
View content of H2 or HSQLDB in-memory database
For HSQLDB, The following worked for me:
DatabaseManager.threadedDBM();
And this brought up the GUI with my tables and data once I pointed it to the right named in-mem database.
It is basically the equivalent of newing up a DatabaseManager
(the non Swing variety), which prompts for connection details, and is set to --noexit
)
I also tried the Swing version, but it only had a main
, and I was unsure of the arguments to pass. If anyone knows, please post here.
Just because I searched for hours for the right database name: The name of the database is the name of your datasource. So try with URL jdbc:hsqldb:mem:dataSource if you have a data source bean with id=dataSource. If this does not work, try testdb which is the default.
Overcoming "Display forbidden by X-Frame-Options"
i had this problem, and resolved it editing httd.conf
<IfModule headers_module>
<IfVersion >= 2.4.7 >
Header always setifempty X-Frame-Options GOFORIT
</IfVersion>
<IfVersion < 2.4.7 >
Header always merge X-Frame-Options GOFORIT
</IfVersion>
</IfModule>
i changed SAMEORIGIN to GOFORIT
and restarted server
How to declare a local variable in Razor?
If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)
@{
// implicit type
var something1 = "something";
// explicit type
string something2 = "something";
}
<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@
Can I run HTML files directly from GitHub, instead of just viewing their source?
This solution only for chrome browser. I am not sure about other browser.
- Add "Modify Content-Type Options" extension in chrome browser.
- Open "chrome-extension://jnfofbopfpaoeojgieggflbpcblhfhka/options.html" url in browser.
- Add the rule for raw file url.
For example:
- URL Filter: https:///raw/master//fileName.html
- Original Type: text/plain
- Replacement Type: text/html
- Open the file browser which you added url in rule (in step 3).
TCP vs UDP on video stream
If the bandwidth is far higher than the bitrate, I would recommend TCP for unicast live video streaming.
Case 1: Consecutive packets are lost for a duration of several seconds. => live video will stop on the client side whatever the transport layer is (TCP or UDP). When the network recovers:
- if TCP is used, client video player can choose to restart the stream at the first packet lost (timeshift) OR to drop all late packets and to restart the video stream with no timeshift.
- if UDP is used, there is no choice on the client side, video restart live without any timeshift.
=> TCP equal or better.
Case 2: some packets are randomly and often lost on the network.
- if TCP is used, these packets will be immediately retransmitted and with a correct jitter buffer, there will be no impact on the video stream quality/latency.
- if UDP is used, video quality will be poor.
=> TCP much better
iOS UIImagePickerController result image orientation after upload
This what I have found for fixing orientation issue
UIImage *initialImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *data = UIImagePNGRepresentation(self.initialImage);
UIImage *tempImage = [UIImage imageWithData:data];
UIImage *fixedOrientationImage = [UIImage imageWithCGImage:tempImage.CGImage
scale:initialImage.scale
orientation:self.initialImage.imageOrientation];
initialImage = fixedOrientationImage;
EDIT:
UIImage *initialImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *data = UIImagePNGRepresentation(self.initialImage);
initialImage = [UIImage imageWithCGImage:[UIImage imageWithData:data].CGImage
scale:initialImage.scale
orientation:self.initialImage.imageOrientation];
Viewing full version tree in git
There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":
[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"
Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - orientationchange
Also, after some googling, check out window.orientation
(which is I believe measured in degrees...)
EDIT: On mobile devices, if you open a keyboard then the above may fail, so can use screen.availHeight
and screen.availWidth
, which gives proper height and width even after the keyboard is opened.
if(screen.availHeight > screen.availWidth){
alert("Please use Landscape!");
}
Java Try Catch Finally blocks without Catch
Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!
Viewing PDF in Windows forms using C#
you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:
System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");
[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation,
string lpFile, string lpParameters,
string lpDirectory, long nShowCmd);
Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:
ThewebBrowserControl.Navigate(@"c:\the_file.pdf");
How to output git log with the first line only?
if you want to always use git log
in such way you could add git alias by
git config --global alias.log log --oneline
after that git log
will print what normally would be printed by git log --oneline
Compare 2 JSON objects
Simply parsing the JSON and comparing the two objects is not enough because
it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
WebView and HTML5 <video>
I answer this topic just in case someone read it and is interested on the result.
It is possible to view a video element (video html5 tag) within a WebView, but I must say I had to deal with it for few days. These are the steps I had to follow so far:
-Find a properly encoded video
-When initializing the WebView, set the JavaScript, Plug-ins the WebViewClient and the WebChromeClient.
url = new String("http://broken-links.com/tests/video/");
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(chromeClient);
mWebView.setWebViewClient(wvClient);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl(url);
-Handle the onShowCustomView in the WebChromeClient object.
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout){
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView){
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
a.setContentView(video);
video.setOnCompletionListener(this);
video.setOnErrorListener(this);
video.start();
}
}
}
-Handle the onCompletion and the onError events for the video, in order to get back to the web view.
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Video completo");
a.setContentView(R.layout.main);
WebView wb = (WebView) a.findViewById(R.id.webview);
a.initWebView();
}
But now I should say there are still an important issue. I can play it only once. The second time I click on the video dispatcher (either the poster or some play button), it does nothing.
I would also like the video to play inside the WebView frame, instead of opening the Media Player window, but this is for me a secondary issue.
I hope it helps somebody, and I would also thank any comment or suggestion.
Saludos, terrícolas.
Viewing all `git diffs` with vimdiff
For people who want to use another diff tool not listed in git, say with nvim
. here is what I ended up using:
git config --global alias.d difftool -x <tool name>
In my case, I set <tool name>
to nvim -d
and invoke the diff command with
git d <file>
JavaScript/jQuery to download file via POST with JSON data
I've been playing around with another option that uses blobs. I've managed to get it to download text documents, and I've downloaded PDF's (However they are corrupted).
Using the blob API you will be able to do the following:
$.post(/*...*/,function (result)
{
var blob=new Blob([result]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.txt";
link.click();
});
This is IE 10+, Chrome 8+, FF 4+. See https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL
It will only download the file in Chrome, Firefox and Opera. This uses a download attribute on the anchor tag to force the browser to download it.
iPad browser WIDTH & HEIGHT standard
There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.
That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.
More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.
On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.
Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.
List Git commits not pushed to the origin yet
git log origin/master..master
or, more generally:
git log <since>..<until>
You can use this with grep to check for a specific, known commit:
git log <since>..<until> | grep <commit-hash>
Or you can also use git-rev-list to search for a specific commit:
git rev-list origin/master | grep <commit-hash>
XML Carriage return encoding
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
Viewing full output of PS command
It is likely that you're using a pager such as less
or most
since the output of ps aux
is longer than a screenful. If so, the following options will cause (or force) long lines to wrap instead of being truncated.
ps aux | less -+S
ps aux | most -w
If you use either of the following commands, lines won't be wrapped but you can use your arrow keys or other movement keys to scroll left and right.
ps aux | less -S # use arrow keys, or Esc-( and Esc-), or Alt-( and Alt-)
ps aux | most # use arrow keys, or < and > (Tab can also be used to scroll right)
Lines are always wrapped for more
and pg
.
When ps aux
is used in a pipe, the w
option is unnecessary since ps
only uses screen width when output is to the terminal.
Viewing unpushed Git commits
one way of doing things is to list commits that are available on one branch but not another.
git log ^origin/master master
ANTLR: Is there a simple example?
For Antlr 4 the java code generation process is below:-
java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g
Update your jar name in classpath accordingly.
HTML encoding issues - "Â" character showing up instead of " "
Somewhere in that mess, the non-breaking spaces from the HTML template (the s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character
That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as "Â "
. That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.
What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your
strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.
Well anyway, for now you can add one of the following to your document's <head>
and see if that makes it look right in the browser:
- for HTML4:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
- for HTML5:
<meta charset="utf-8">
If you've done that, then any remaining problem is ActivePDF's fault.
Auto detect mobile browser (via user-agent?)
You haven't said what language you're using. If it's Perl then it's trivial:
use CGI::Info;
my $info = CGI::Info->new();
if($info->is_mobile()) {
# Add mobile stuff
}
unless($info->is_mobile()) {
# Don't do some things on a mobile
}
Colorized grep -- viewing the entire file with highlighted matches
Use colout
program: http://nojhan.github.io/colout/
It is designed to add color highlights to a text stream. Given a regex and a color (e.g. "red"), it reproduces a text stream with matches highlighted. e.g:
# cat logfile but highlight instances of 'ERROR' in red
colout ERROR red <logfile
You can chain multiple invocations to add multiple different color highlights:
tail -f /var/log/nginx/access.log | \
colout ' 5\d\d ' red | \
colout ' 4\d\d ' yellow | \
colout ' 3\d\d ' cyan | \
colout ' 2\d\d ' green
Or you can achieve the same thing by using a regex with N groups (parenthesised parts of the regex), followed by a comma separated list of N colors.
vagrant status | \
colout \
'\''(^.+ running)|(^.+suspended)|(^.+not running)'\'' \
green,yellow,red
How to best display in Terminal a MySQL SELECT returning too many fields?
If you are using MySQL interactively, you can set your pager to use sed
like this:
$ mysql -u <user> p<password>
mysql> pager sed 's/,/\n/g'
PAGER set to 'sed 's/,/\n/g''
mysql> SELECT blah FROM blah WHERE blah = blah
.
.
.
"blah":"blah"
"blah":"blah"
"blah":"blah"
If you don't use sed
as the pager, the output is like this:
"blah":"blah","blah":"blah","blah":"blah"
Attach to a processes output for viewing
I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc
path. So if you have a program running, whose ID is 1199, cd
into it:
$ cd /proc/1199
Then look for the fd
directory underneath
$ cd fd
This fd
directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f
the one you need - in this case, stdout):
$ tail -f 1
Viewing all defined variables
keep in mind dir() will return all current imports, AND variables.
if you just want your variables, I would suggest a naming scheme that is easy to extract from dir, such as varScore, varNames, etc.
that way, you can simply do this:
for vars in dir():
if vars.startswith("var"):
print vars
Edit
if you want to list all variables, but exclude imported modules and variables such as:
__builtins__
you can use something like so:
import os
import re
x = 11
imports = "os","re"
for vars in dir():
if vars.startswith("__") == 0 and vars not in imports:
print vars
as you can see, it will show the variable "imports" though, because it is a variable (well, a tuple). A quick workaround is to add the word "imports" into the imports tuple itself!
Logging best practices
I have to join the chorus recommending log4net, in my case coming from a platform flexibility (desktop .Net/Compact Framework, 32/64-bit) point of view.
However, wrapping it in a private-label API is a major anti-pattern. log4net.ILogger
is the .Net counterpart of the Commons Logging wrapper API already, so coupling is already minimized for you, and since it is also an Apache library, that's usually not even a concern because you're not giving up any control: fork it if you must.
Most house wrapper libraries I've seen also commit one or more of a litany of faults:
- Using a global singleton logger (or equivalently a static entry point) which loses the fine resolution of the recommended logger-per-class pattern for no other selectivity gain.
- Failing to expose the optional
Exception
argument, leading to multiple problems:
- It makes an exception logging policy even more difficult to maintain, so nothing is done consistently with exceptions.
- Even with a consistent policy, formatting the exception away into a string loses data prematurely. I've written a custom
ILayout
decorator that performs detailed drill-down on an exception to determine the chain of events.
- Failing to expose the
IsLevelEnabled
properties, which discards the ability to skip formatting code when areas or levels of logging are turned off.
Comprehensive methods of viewing memory usage on Solaris
# echo ::memstat | mdb -k
Page Summary Pages MB %Tot
------------ ---------------- ---------------- ----
Kernel 7308 57 23%
Anon 9055 70 29%
Exec and libs 1968 15 6%
Page cache 2224 17 7%
Free (cachelist) 6470 50 20%
Free (freelist) 4641 36 15%
Total 31666 247
Physical 31256 244
Table and Index size in SQL Server
There is an extended stored procedure sp_spaceused
that gets this information out. It's fairly convoluted to do it from the data dictionary, but This link fans out to a script that does it. This stackoverflow question has some fan-out to information on the underlying data structures that you can use to construct estimates of table and index sizes for capcity planning.
What's the best visual merge tool for Git?
You can try P4Merge.
Visualize the differences between file versions with P4Merge. Resolve conflicts that result from parallel or concurrent development via color coding.
The features includes:
- Highlight and edit text file differences
- Choose to include or ignore line endings or white spaces
- Recognize line-ending conventions for Windows (CRLF), Mac (CR), and Unix (LF)
- Use command-line parameters and launch from non-Perforce applications
- Display line numbers when comparing and merging files
- Exclude files that are modified, unique, or unchanged
- Filter files by name or extension
- Organize modified assets in familiar file/folder hierarchy
- Compare JPEG, GIF, TIFF, BMP, and other file formats
- Extend using the Qt API
- Overlay images or display side-by-side
- Highlight differences on overlaid images
Force Internet Explorer to use a specific Java Runtime Environment install?
First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.
Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.
To get your old version of Java back you need to reverse these steps.
Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).
The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.
How do I get the current location of an iframe?
Ok, so in this application, there is an iframe in which the user is supplied with links or some capacity that allows that iframe to browse to some external site. You are then looking to capture the URL to which the user has browsed.
Something to keep in mind. Since the URL is to an external source, you will be limited in how much you can interact with this iframe via javascript (or an client side access for that matter), this is known as browser cross-domain security, as apparently you have discovered. There are clever work arounds, as presented here Cross-domain, cross-frame Javascript, although I do not think this work around applies in this case.
About all you can access is the location, as you need.
I would suggest making the code presented more resilitant and less error prone. Try browsing the web sometime with IE or FF configured to show javascript errors. You will be surprised just how many javascript errors are thrown, largely because there is a lot of error prone javascript out there, which just continues to proliferate.
This solution assumes that the iframe in question is the same "window" context where you are running the javascript. (Meaning, it is not embedded within another frame or iframe, in which case, the javascript code gets more involved, and you likely need to recursively search through the window hierarchy.)
<iframe name='frmExternal' id='frmExternal' src='http://www.stackoverflow.com'></frame>
<input type='text' id='txtUrl' />
<input type='button' id='btnGetUrl' value='Get URL' onclick='GetIFrameUrl();' />
<script language='javascript' type='text/javascript'>
function GetIFrameUrl()
{
if (!document.getElementById)
{
return;
}
var frm = document.getElementById("frmExternal");
var txt = document.getElementById("txtUrl");
if (frm == null || txt == null)
{
// not great user feedback but slightly better than obnoxious script errors
alert("There was a problem with this page, please refresh.");
return;
}
txt.value = frm.src;
}
</script>
Hope this helps.
How can I clear the terminal in Visual Studio Code?
2019 Update (Read in Full)
Shortcut
Mac: cmd + k
Windows: ctrl + k
TroubleShooting
If the shortcuts do not work for you, the most likely scenario is that either you or an extension you installed has added an open ended ctrl + k / cmd + k chord to another shortcut.
Open ended meaning, the shortcut does not have an explicit when
clause that excludes terminal focus. There are two possible solutions here.
Solution 1:
If you added the shortcut, simply go to your keybindings.json file and add a when
clause that does not include terminal focus. Example:
{
"key": "cmd+k cmd+c",
"command": "someCommandHere",
"when": "editorTextFocus",
}
Solution 2:
Alternatively, you can add the workbench.action.terminal.clear
command to the very bottom of keybindings.json
, ensuring it takes precedence over other shortcuts. It'd be wise to add a comment so you don't forget and later place new chords below it. Example:
// Keep this keybinding at very bottom of file to ensure terminal clearing.
{
"key": "cmd+k",
"command": "workbench.action.terminal.clear",
"when": "terminalFocus",
}
For additional information, check out this GitHub issue.
How to mock private method for testing using PowerMock?
With no argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");
With String
argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
.withArguments(anyString()).thenReturn("mocked result");
How do I UPDATE from a SELECT in SQL Server?
declare @tblStudent table (id int,name varchar(300))
declare @tblMarks table (std_id int,std_name varchar(300),subject varchar(50),marks int)
insert into @tblStudent Values (1,'Abdul')
insert into @tblStudent Values(2,'Rahim')
insert into @tblMarks Values(1,'','Math',50)
insert into @tblMarks Values(1,'','History',40)
insert into @tblMarks Values(2,'','Math',30)
insert into @tblMarks Values(2,'','history',80)
select * from @tblMarks
update m
set m.std_name=s.name
from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id
select * from @tblMarks
How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?
For VS2015... here's a VB example for switching from a WebSite project to a Web Application Project that worked for me. None of the other solutions worked for me, which is why I'm sharing this. It's not elegant, but works.
Step 0: Replace all " CodeFile=" with " CodeBehind=" in your project
Step 1: Close the Solution.
Step 2: Run a home-grown Windows app with the following code (below steps).
Step 3: Re-open the solution.
Step 4: In Solution Explorer, make sure you are Showing All Files, and search for designer.vb (or designer.cs for C#)
Step 5: Select all the missing files, and include them in your project.
Step 6: For each file, view the main page / control and save it.
private void button1_Click(object sender, EventArgs e)
{
ProcessDirectory(new DirectoryInfo(textBox1.Text));
}
private void ProcessDirectory(DirectoryInfo directory)
{
ProcessMask(directory, ".ascx", ".vb");
ProcessMask(directory, ".aspx", ".vb");
foreach (DirectoryInfo directoryInfo in directory.GetDirectories())
ProcessDirectory(directoryInfo);
}
private void ProcessMask(DirectoryInfo directory, string maskStart, string maskEnd)
{
FileStream fs;
foreach (FileInfo file in directory.GetFiles(string.Format("*{0}{1}", maskStart, maskEnd)))
{
string designerFileName = file.Name.Replace(string.Format("{0}{1}", maskStart, maskEnd), string.Format("{0}.designer{1}", maskStart, maskEnd));
if (directory.GetFiles(designerFileName).Length == 0)
{
using (fs = File.Create(Path.Combine(directory.FullName, designerFileName)))
{
fs.Close();
}
}
}
}
Show popup after page load
<script type="text/javascript">
jQuery(document).ready(function(){
setTimeout(PopUp(),5000); // invoke Popup function after 5 seconds
});
</script>
Add a reference column migration in Rails 4
Rails 4.x
When you already have users
and uploads
tables and wish to add a new relationship between them.
All you need to do is: just generate a migration using the following command:
rails g migration AddUserToUploads user:references
Which will create a migration file as:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
end
end
Then, run the migration using rake db:migrate
.
This migration will take care of adding a new column named user_id
to uploads
table (referencing id
column in users
table), PLUS it will also add an index on the new column.
UPDATE [For Rails 4.2]
Rails can’t be trusted to maintain referential integrity; relational databases come to our rescue here. What that means is that we can add foreign key constraints at the database level itself and ensure that database would reject any operation that violates this set referential integrity. As @infoget commented, Rails 4.2 ships with native support for foreign keys(referential integrity). It's not required but you might want to add foreign key(as it's very useful) to the reference that we created above.
To add foreign key to an existing reference, create a new migration to add a foreign key:
class AddForeignKeyToUploads < ActiveRecord::Migration
def change
add_foreign_key :uploads, :users
end
end
To create a completely brand new reference with a foreign key(in Rails 4.2), generate a migration using the following command:
rails g migration AddUserToUploads user:references
which will create a migration file as:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
add_foreign_key :uploads, :users
end
end
This will add a new foreign key to the user_id
column of the uploads
table. The key references the id
column in users
table.
NOTE: This is in addition to adding a reference so you still need to create a reference first then foreign key (you can choose to create a foreign key in the same migration or a separate migration file). Active Record only supports single column foreign keys and currently only mysql
, mysql2
and PostgreSQL
adapters are supported. Don't try this with other adapters like sqlite3
, etc. Refer to Rails Guides: Foreign Keys for your reference.
Case insensitive searching in Oracle
From Oracle 12c R2 you could use COLLATE operator
:
The COLLATE operator determines the collation for an expression. This operator enables you to override the collation that the database would have derived for the expression using standard collation derivation rules.
The COLLATE operator takes one argument, collation_name, for which you can specify a named collation or pseudo-collation. If the collation name contains a space, then you must enclose the name in double quotation marks.
Demo:
CREATE TABLE tab1(i INT PRIMARY KEY, name VARCHAR2(100));
INSERT INTO tab1(i, name) VALUES (1, 'John');
INSERT INTO tab1(i, name) VALUES (2, 'Joe');
INSERT INTO tab1(i, name) VALUES (3, 'Billy');
--========================================================================--
SELECT /*csv*/ *
FROM tab1
WHERE name = 'jOHN' ;
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI = 'jOHN' ;
/*
"I","NAME"
1,"John"
*/
SELECT /*csv*/ *
FROM tab1
WHERE name LIKE 'j%';
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI LIKE 'j%';
/*
"I","NAME"
1,"John"
2,"Joe"
*/
db<>fiddle demo
What's the fastest way in Python to calculate cosine similarity given sparse matrix data?
You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:
from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse
A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)
similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))
#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))
Results:
pairwise dense output:
[[ 1. 0.40824829 0.40824829]
[ 0.40824829 1. 0.33333333]
[ 0.40824829 0.33333333 1. ]]
pairwise sparse output:
(0, 1) 0.408248290464
(0, 2) 0.408248290464
(0, 0) 1.0
(1, 0) 0.408248290464
(1, 2) 0.333333333333
(1, 1) 1.0
(2, 1) 0.333333333333
(2, 0) 0.408248290464
(2, 2) 1.0
If you want column-wise cosine similarities simply transpose your input matrix beforehand:
A_sparse.transpose()
How can I generate random alphanumeric strings?
Try to combine two parts: unique (sequence, counter or date ) and random
public class RandomStringGenerator
{
public static string Gen()
{
return ConvertToBase(DateTime.UtcNow.ToFileTimeUtc()) + GenRandomStrings(5); //keep length fixed at least of one part
}
private static string GenRandomStrings(int strLen)
{
var result = string.Empty;
using (var gen = new RNGCryptoServiceProvider())
{
var data = new byte[1];
while (result.Length < strLen)
{
gen.GetNonZeroBytes(data);
int code = data[0];
if (code > 48 && code < 57 || // 0-9
code > 65 && code < 90 || // A-Z
code > 97 && code < 122 // a-z
)
{
result += Convert.ToChar(code);
}
}
return result;
}
}
private static string ConvertToBase(long num, int nbase = 36)
{
const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //if you wish to make the algorithm more secure - change order of letter here
// check if we can convert to another base
if (nbase < 2 || nbase > chars.Length)
return null;
int r;
var newNumber = string.Empty;
// in r we have the offset of the char that was converted to the new base
while (num >= nbase)
{
r = (int)(num % nbase);
newNumber = chars[r] + newNumber;
num = num / nbase;
}
// the last number to convert
newNumber = chars[(int)num] + newNumber;
return newNumber;
}
}
Tests:
[Test]
public void Generator_Should_BeUnigue1()
{
//Given
var loop = Enumerable.Range(0, 1000);
//When
var str = loop.Select(x=> RandomStringGenerator.Gen());
//Then
var distinct = str.Distinct();
Assert.AreEqual(loop.Count(),distinct.Count()); // Or Assert.IsTrue(distinct.Count() < 0.95 * loop.Count())
}
C# LINQ select from list
In likeness of how I found this question using Google, I wanted to take it one step further.
Lets say I have a string[] states
and a db Entity
of StateCounties
and I just want the states from the list returned and not all of the StateCounties
.
I would write:
db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();
I found this within the sample of CheckBoxList
for nu-get.
What are the default color values for the Holo theme on Android 4.0?
If you want the default colors of Android ICS, you just have to go to your Android SDK and look for this path: platforms\android-15\data\res\values\colors.xml
.
Here you go:
<!-- For holo theme -->
<drawable name="screen_background_holo_light">#fff3f3f3</drawable>
<drawable name="screen_background_holo_dark">#ff000000</drawable>
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
<color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
<color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
<color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
<color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
<color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
<color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
<color name="dim_foreground_holo_dark">#bebebe</color>
<color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
<color name="dim_foreground_inverse_holo_dark">#323232</color>
<color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
<color name="hint_foreground_holo_dark">#808080</color>
<color name="dim_foreground_holo_light">#323232</color>
<color name="dim_foreground_disabled_holo_light">#80323232</color>
<color name="dim_foreground_inverse_holo_light">#bebebe</color>
<color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
<color name="hint_foreground_holo_light">#808080</color>
<color name="highlighted_text_holo_dark">#6633b5e5</color>
<color name="highlighted_text_holo_light">#6633b5e5</color>
<color name="link_text_holo_dark">#5c5cff</color>
<color name="link_text_holo_light">#0000ee</color>
This for the Background:
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
You won't get the same colors if you look this up in Photoshop etc. because they are set up with Alpha values.
Update for API Level 19:
<resources>
<drawable name="screen_background_light">#ffffffff</drawable>
<drawable name="screen_background_dark">#ff000000</drawable>
<drawable name="status_bar_closed_default_background">#ff000000</drawable>
<drawable name="status_bar_opened_default_background">#ff000000</drawable>
<drawable name="notification_item_background_color">#ff111111</drawable>
<drawable name="notification_item_background_color_pressed">#ff454545</drawable>
<drawable name="search_bar_default_color">#ff000000</drawable>
<drawable name="safe_mode_background">#60000000</drawable>
<!-- Background drawable that can be used for a transparent activity to
be able to display a dark UI: this darkens its background to make
a dark (default theme) UI more visible. -->
<drawable name="screen_background_dark_transparent">#80000000</drawable>
<!-- Background drawable that can be used for a transparent activity to
be able to display a light UI: this lightens its background to make
a light UI more visible. -->
<drawable name="screen_background_light_transparent">#80ffffff</drawable>
<color name="safe_mode_text">#80ffffff</color>
<color name="white">#ffffffff</color>
<color name="black">#ff000000</color>
<color name="transparent">#00000000</color>
<color name="background_dark">#ff000000</color>
<color name="background_light">#ffffffff</color>
<color name="bright_foreground_dark">@android:color/background_light</color>
<color name="bright_foreground_light">@android:color/background_dark</color>
<color name="bright_foreground_dark_disabled">#80ffffff</color>
<color name="bright_foreground_light_disabled">#80000000</color>
<color name="bright_foreground_dark_inverse">@android:color/bright_foreground_light</color>
<color name="bright_foreground_light_inverse">@android:color/bright_foreground_dark</color>
<color name="dim_foreground_dark">#bebebe</color>
<color name="dim_foreground_dark_disabled">#80bebebe</color>
<color name="dim_foreground_dark_inverse">#323232</color>
<color name="dim_foreground_dark_inverse_disabled">#80323232</color>
<color name="hint_foreground_dark">#808080</color>
<color name="dim_foreground_light">#323232</color>
<color name="dim_foreground_light_disabled">#80323232</color>
<color name="dim_foreground_light_inverse">#bebebe</color>
<color name="dim_foreground_light_inverse_disabled">#80bebebe</color>
<color name="hint_foreground_light">#808080</color>
<color name="highlighted_text_dark">#9983CC39</color>
<color name="highlighted_text_light">#9983CC39</color>
<color name="link_text_dark">#5c5cff</color>
<color name="link_text_light">#0000ee</color>
<color name="suggestion_highlight_text">#177bbd</color>
<drawable name="stat_notify_sync_noanim">@drawable/stat_notify_sync_anim0</drawable>
<drawable name="stat_sys_download_done">@drawable/stat_sys_download_done_static</drawable>
<drawable name="stat_sys_upload_done">@drawable/stat_sys_upload_anim0</drawable>
<drawable name="dialog_frame">@drawable/panel_background</drawable>
<drawable name="alert_dark_frame">@drawable/popup_full_dark</drawable>
<drawable name="alert_light_frame">@drawable/popup_full_bright</drawable>
<drawable name="menu_frame">@drawable/menu_background</drawable>
<drawable name="menu_full_frame">@drawable/menu_background_fill_parent_width</drawable>
<drawable name="editbox_dropdown_dark_frame">@drawable/editbox_dropdown_background_dark</drawable>
<drawable name="editbox_dropdown_light_frame">@drawable/editbox_dropdown_background</drawable>
<drawable name="dialog_holo_dark_frame">@drawable/dialog_full_holo_dark</drawable>
<drawable name="dialog_holo_light_frame">@drawable/dialog_full_holo_light</drawable>
<drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
<drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
<color name="input_method_navigation_guard">#ff000000</color>
<!-- For date picker widget -->
<drawable name="selected_day_background">#ff0092f4</drawable>
<!-- For settings framework -->
<color name="lighter_gray">#ddd</color>
<color name="darker_gray">#aaa</color>
<!-- For security permissions -->
<color name="perms_dangerous_grp_color">#33b5e5</color>
<color name="perms_dangerous_perm_color">#33b5e5</color>
<color name="shadow">#cc222222</color>
<color name="perms_costs_money">#ffffbb33</color>
<!-- For search-related UIs -->
<color name="search_url_text_normal">#7fa87f</color>
<color name="search_url_text_selected">@android:color/black</color>
<color name="search_url_text_pressed">@android:color/black</color>
<color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>
<!-- SlidingTab -->
<color name="sliding_tab_text_color_active">@android:color/black</color>
<color name="sliding_tab_text_color_shadow">@android:color/black</color>
<!-- keyguard tab -->
<color name="keyguard_text_color_normal">#ffffff</color>
<color name="keyguard_text_color_unlock">#a7d84c</color>
<color name="keyguard_text_color_soundoff">#ffffff</color>
<color name="keyguard_text_color_soundon">#e69310</color>
<color name="keyguard_text_color_decline">#fe0a5a</color>
<!-- keyguard clock -->
<color name="lockscreen_clock_background">#ffffffff</color>
<color name="lockscreen_clock_foreground">#ffffffff</color>
<color name="lockscreen_clock_am_pm">#ffffffff</color>
<color name="lockscreen_owner_info">#ff9a9a9a</color>
<!-- keyguard overscroll widget pager -->
<color name="kg_multi_user_text_active">#ffffffff</color>
<color name="kg_multi_user_text_inactive">#ff808080</color>
<color name="kg_widget_pager_gradient">#ffffffff</color>
<!-- FaceLock -->
<color name="facelock_spotlight_mask">#CC000000</color>
<!-- For holo theme -->
<drawable name="screen_background_holo_light">#fff3f3f3</drawable>
<drawable name="screen_background_holo_dark">#ff000000</drawable>
<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>
<color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
<color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
<color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
<color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
<color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
<color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
<color name="dim_foreground_holo_dark">#bebebe</color>
<color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
<color name="dim_foreground_inverse_holo_dark">#323232</color>
<color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
<color name="hint_foreground_holo_dark">#808080</color>
<color name="dim_foreground_holo_light">#323232</color>
<color name="dim_foreground_disabled_holo_light">#80323232</color>
<color name="dim_foreground_inverse_holo_light">#bebebe</color>
<color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
<color name="hint_foreground_holo_light">#808080</color>
<color name="highlighted_text_holo_dark">#6633b5e5</color>
<color name="highlighted_text_holo_light">#6633b5e5</color>
<color name="link_text_holo_dark">#5c5cff</color>
<color name="link_text_holo_light">#0000ee</color>
<!-- Group buttons -->
<eat-comment />
<color name="group_button_dialog_pressed_holo_dark">#46c5c1ff</color>
<color name="group_button_dialog_focused_holo_dark">#2699cc00</color>
<color name="group_button_dialog_pressed_holo_light">#ffffffff</color>
<color name="group_button_dialog_focused_holo_light">#4699cc00</color>
<!-- Highlight colors for the legacy themes -->
<eat-comment />
<color name="legacy_pressed_highlight">#fffeaa0c</color>
<color name="legacy_selected_highlight">#fff17a0a</color>
<color name="legacy_long_pressed_highlight">#ffffffff</color>
<!-- General purpose colors for Holo-themed elements -->
<eat-comment />
<!-- A light Holo shade of blue -->
<color name="holo_blue_light">#ff33b5e5</color>
<!-- A light Holo shade of gray -->
<color name="holo_gray_light">#33999999</color>
<!-- A light Holo shade of green -->
<color name="holo_green_light">#ff99cc00</color>
<!-- A light Holo shade of red -->
<color name="holo_red_light">#ffff4444</color>
<!-- A dark Holo shade of blue -->
<color name="holo_blue_dark">#ff0099cc</color>
<!-- A dark Holo shade of green -->
<color name="holo_green_dark">#ff669900</color>
<!-- A dark Holo shade of red -->
<color name="holo_red_dark">#ffcc0000</color>
<!-- A Holo shade of purple -->
<color name="holo_purple">#ffaa66cc</color>
<!-- A light Holo shade of orange -->
<color name="holo_orange_light">#ffffbb33</color>
<!-- A dark Holo shade of orange -->
<color name="holo_orange_dark">#ffff8800</color>
<!-- A really bright Holo shade of blue -->
<color name="holo_blue_bright">#ff00ddff</color>
<!-- A really bright Holo shade of gray -->
<color name="holo_gray_bright">#33CCCCCC</color>
<drawable name="notification_template_icon_bg">#3333B5E5</drawable>
<drawable name="notification_template_icon_low_bg">#0cffffff</drawable>
<!-- Keyguard colors -->
<color name="keyguard_avatar_frame_color">#ffffffff</color>
<color name="keyguard_avatar_frame_shadow_color">#80000000</color>
<color name="keyguard_avatar_nick_color">#ffffffff</color>
<color name="keyguard_avatar_frame_pressed_color">#ff35b5e5</color>
<color name="accessibility_focus_highlight">#80ffff00</color>
</resources>
Task continuation on UI thread
I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:
Task.Factory.StartNew(() =>
{
DoLongRunningWork();
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{ txt.Text = "Complete"; }));
});
How to find the number of days between two dates
If you are using MySQL there is the DATEDIFF function which calculate the days between two dates:
SELECT dtCreated
, bActive
, dtLastPaymentAttempt
, dtLastUpdated
, dtLastVisit
, DATEDIFF(dtLastUpdated, dtCreated) as Difference
FROM Customers
WHERE (bActive = 'true')
AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
How to make RatingBar to show five stars
The actual thing over here is to use wrap_content
instead of match_parent
. If you will use match_parent
the layout will be filled with the stars even if it is more than the numStars variable.
How to change menu item text dynamically in Android
You can do it like this, and no need to dedicate variable:
Toolbar toolbar = findViewById(R.id.toolbar);
Menu menu = toolbar.getMenu();
MenuItem menuItem = menu.findItem(R.id.some_action);
menuItem.setTitle("New title");
Or a little simplified:
MenuItem menuItem = ((Toolbar)findViewById(R.id.toolbar)).getMenu().findItem(R.id.some_action);
menuItem.setTitle("New title");
It works only - after the menu created.
How to position two divs horizontally within another div
This should do what you are looking for:
<html>
<head>
<style type="text/css">
#header {
text-align: center;
}
#wrapper {
margin:0 auto;
width:600px;
}
#submain {
margin:0 auto;
width:600px;
}
#sub-left {
float:left;
width:300px;
}
#sub-right {
float:right;
width:240px;
text-align: right;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header"><h1>Head</h1></div>
<div id="sub-main">
<div id="sub-left">
Right
</div>
<div id="sub-right">
Left
</div>
</div>
</div>
</body>
</html>
And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.
Make Https call using HttpClient
Just specifying HTTPS in the URI should do the trick.
httpClient.BaseAddress = new Uri("https://foobar.com/");
If the request works with HTTP but fails with HTTPS then this is most certainly a certificate issue. Make sure the caller trusts the certificate issuer and that the certificate is not expired. A quick and easy way to check that is to try making the query in a browser.
You also may want to check on the server (if it's yours and / or if you can) that it is set to serve HTTPS requests properly.
findViewById in Fragment
Note :
From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.
So now you can simply do,
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
Perl read line by line
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'.
In perl $foo
is the name of the variable.
How to avoid 'undefined index' errors?
A variation on SquareRootOf2's answer, but this should be placed before the first use of the $output variable:
$keys = array('key1', 'key2', 'etc');
$output = array_fill_keys($keys, '');
What is the backslash character (\\)?
Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \"
to represent quotation marks. Then you have a second problem: how to represent \
? Again, out of convention you decide to use \\
instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n
).
Save modifications in place with awk
@sudo_O has the right answer.
This can't work:
someprocess < file > file
The shell performs the redirections before handing control over to someprocess (redirections). The >
redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.
matplotlib has no attribute 'pyplot'
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
Alternate table row color using CSS?
You have the :nth-child()
pseudo-class:
table tr:nth-child(odd) td{
...
}
table tr:nth-child(even) td{
...
}
In the early days of :nth-child()
its browser support was kind of poor. That's why setting class="odd"
became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.
script to map network drive
use the net use
command:
net use Z: \\10.0.1.1\DRIVENAME
Edit 1: Also, I believe the password should be simply appended:
net use Z: \\10.0.1.1\DRIVENAME PASSWORD
You can find out more about this command and its arguments via:
net use ?
Edit 2: As Tomalak mentioned in comments, you can later un-map it via
net use Z: \delete
PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
Java array assignment (multiple values)
Java does not provide a construct that will assign of multiple values to an existing array's elements. The initializer syntaxes can ONLY be used when creation a new array object. This can be at the point of declaration, or later on. But either way, the initializer is initializing a new array object, not updating an existing one.
Bootstrap Navbar toggle button not working
Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.
As soon as I added this, the toggle started working fine.
<meta name="viewport" content="width=device-width, initial-scale=1">
Python regex for integer?
I prefer ^[-+]?([1-9]\d*|0)$
because ^[-+]?[0-9]+$
allows the string starting with 0
.
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
class TestRE(unittest.TestCase):
def test_int(self):
self.assertFalse(RE_INT.match('+'))
self.assertFalse(RE_INT.match('-'))
self.assertTrue(RE_INT.match('1'))
self.assertTrue(RE_INT.match('+1'))
self.assertTrue(RE_INT.match('-1'))
self.assertTrue(RE_INT.match('0'))
self.assertTrue(RE_INT.match('+0'))
self.assertTrue(RE_INT.match('-0'))
self.assertTrue(RE_INT.match('11'))
self.assertFalse(RE_INT.match('00'))
self.assertFalse(RE_INT.match('01'))
self.assertTrue(RE_INT.match('+11'))
self.assertFalse(RE_INT.match('+00'))
self.assertFalse(RE_INT.match('+01'))
self.assertTrue(RE_INT.match('-11'))
self.assertFalse(RE_INT.match('-00'))
self.assertFalse(RE_INT.match('-01'))
self.assertTrue(RE_INT.match('1234567890'))
self.assertTrue(RE_INT.match('+1234567890'))
self.assertTrue(RE_INT.match('-1234567890'))
error: function returns address of local variable
All the answer explain the problem really good.
However, I would like to add another information.
I faced the same problem at the moment I wanted the output of a
function to be a vector.
In this situation, the common solution is to declare the output as an argument of the function itself. This way, the alloc
of the variable and the physical space necessary to store the information are managed outside the function. Pseudocode to explain the classical solution is:
void function(int input, int* output){
//...
output[0] = something;
output[1] = somethig_else;
//...
return;
}
In this case, the example code within the question should be changed in:
void foo(int x, char* a){
if(x < 0){
char b = "blah";
//...
strcpy(a, b);
//..
return;
}
//..
}
Convert string with comma to integer
You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.
Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.
BSTR to std::string (std::wstring) and vice versa
There is a c++ class called _bstr_t
. It has useful methods and a collection of overloaded operators.
For example, you can easily assign from a const wchar_t *
or a const char *
just doing _bstr_t bstr = L"My string";
Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();
. You can even convert it back to a regular char const char * c = bstr.operator char *();
You can then just use the const wchar_t *
or the const char *
to initialize a new std::wstring
oe std::string
.
How to emulate GPS location in the Android Emulator?
In eclipse:
You may have to drag the DDMS window down.
'Location Controls' is located under 'Telephony Actions' and may be hidden by a normally sized console view ( the bar with console, LogCat etc may be covering it!)
~
Reload nginx configuration
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
How to modify a specified commit?
Automated interactive rebase edit followed by commit revert ready for a do-over
I found myself fixing a past commit frequently enough that I wrote a script for it.
Here's the workflow:
git commit-edit <commit-hash>
This will drop you at the commit you want to edit.
Fix and stage the commit as you wish it had been in the first place.
(You may want to use git stash save
to keep any files you're not committing)
Redo the commit with --amend
, eg:
git commit --amend
Complete the rebase:
git rebase --continue
For the above to work, put the below script into an executable file called git-commit-edit
somewhere in your $PATH
:
#!/bin/bash
set -euo pipefail
script_name=${0##*/}
warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }
[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"
# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")
message=$(git log -1 --format='%h %s' "$commit")
if [[ $OSTYPE =~ ^darwin ]]; then
sed_inplace=(sed -Ei "")
else
sed_inplace=(sed -Ei)
fi
export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)" # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty # Commit an empty commit so that that cache diffs are un-reversed
echo
echo "Editing commit: $message" >&2
echo
How to update column value in laravel
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
How to put a link on a button with bootstrap?
You can call a function on click event of button.
<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">
<script>
function relocate_home()
{
location.href = "www.yoursite.com";
}
</script>
OR
Use this Code
<a href="#link" class="btn btn-info" role="button">Link Button</a>
When do I need to use a semicolon vs a slash in Oracle SQL?
I wanted to clarify some more use between the ;
and the /
In SQLPLUS:
;
means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
<newline>
after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;
), it means, store the statement to the buffer but do not run it.
/
after entering a statement into the buffer (with a blank <newline>
) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
RUN
or R
is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
/
during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
NOTE: Because ;
are used for PL/SQL to end a statement ;
cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:
END;
/
How to set UITextField height?
- Choose the border style as not rounded
- Set your height
in your viewWillAppear set the corners as round
yourUITextField.borderStyle = UITextBorderStyleRoundedRect;
- Enjoy your round and tall UITextField
What are the differences between numpy arrays and matrices? Which one should I use?
Scipy.org recommends that you use arrays:
*'array' or 'matrix'? Which should I use? - Short answer
Use arrays.
They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.
There is a clear distinction between element-wise operations and
linear algebra operations.
You can have standard vectors or row/column vectors if you like.
The only disadvantage of using the array type is that you will have to
use dot
instead of *
to multiply (reduce) two tensors (scalar product,
matrix vector multiplication etc.).
String, StringBuffer, and StringBuilder
Personally, I don't think there is any real world use for StringBuffer
. When would I ever want to communicate between multiple threads by manipulating a character sequence? That doesn't sound useful at all, but maybe I have yet to see the light :)
How to get overall CPU usage (e.g. 57%) on Linux
Try mpstat
from the sysstat
package
> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025) 02/10/2012 _x86_64_ (2 CPU)
03:33:26 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
03:33:26 PM all 2.39 0.04 0.19 0.34 0.00 0.01 0.00 0.00 97.03
Then some cut
or grep
to parse the info you need:
mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 - $ 12}'a
How to set up a PostgreSQL database in Django
Step by step that I use:
- sudo apt-get install python-dev
- sudo apt-get install postgresql-server-dev-9.1
- sudo apt-get install python-psycopg2 - Or sudo pip install psycopg2
You may want to install a graphic tool to manage your databases, for that you can do:
sudo apt-get install postgresql pgadmin3
After, you must change Postgre user password, then do:
- sudo su
- su postgres -c psql postgres
- ALTER USER postgres WITH PASSWORD 'YourPassWordHere';
- \q
On your settings.py file you do:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': '',
'PORT': '',
}
}
Extra:
If you want to create the db using the command line you can just do:
- sudo su
- su postgres -c psql postgres
- CREATE DATABASE dbname;
- CREATE USER djangouser WITH ENCRYPTED PASSWORD 'myPasswordHere';
- GRANT ALL PRIVILEGES ON DATABASE dbname TO djangouser;
On your settings.py file you do:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'djangouser',
'PASSWORD': 'myPasswordHere',
'HOST': '',
'PORT': '',
}
}
HTML -- two tables side by side
You can place your tables in a div and add style to your table "float: left"
<div>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
</div>
or simply use css:
div>table {
float: left
}
SSIS Text was truncated with status value 4
I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.
i applied the above solution and can convert my data to SQL.
Transform char array into String
If you have the char array null terminated, you can assign the char array to the string:
char[] chArray = "some characters";
String String(chArray);
As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.
Removing MySQL 5.7 Completely
First of all, do a backup of your needed databases with mysqldump
Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).
In total, do this:
sudo service mysql stop #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql
All above commands in single line (just copy and paste):
sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql
Execute PHP scripts within Node.js web server
You can run PHP as with any web-server, using the SPHP module for node.
It's compatible but not dependent on express.
It also supports websockets requests on the HTTP port.
Its biased for speed under small load, rather then saving resources.
To install in node:
npm install sphp
in you app:
var express = require('express');
var sphp = require('sphp');
var app = express();
var server = app.listen(8080);
app.use(sphp.express('public/'));
app.use(express.static('public/'));
For more information, look at https://github.com/paragi/sphp
I'm slightly biased too because I'm the author :)
HTML - how can I show tooltip ONLY when ellipsis is activated
Here's a Vanilla JavaScript solution:
_x000D_
_x000D_
(function init() {_x000D_
_x000D_
var cells = document.getElementsByClassName("cell");_x000D_
_x000D_
for(let index = 0; index < cells.length; ++index) {_x000D_
let cell = cells.item(index);_x000D_
cell.addEventListener('mouseenter', setTitleIfNecessary, false);_x000D_
}_x000D_
_x000D_
function setTitleIfNecessary() {_x000D_
if(this.offsetWidth < this.scrollWidth) {_x000D_
this.setAttribute('title', this.innerHTML);_x000D_
}_x000D_
}_x000D_
_x000D_
})();
_x000D_
.cell {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
border: 1px;_x000D_
border-style: solid;_x000D_
width: 120px; _x000D_
}
_x000D_
<div class="cell">hello world!</div>_x000D_
<div class="cell">hello mars! kind regards, world</div>
_x000D_
_x000D_
_x000D_
How to check if a file exists in Documents folder?
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
Call method when home button pressed
The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app).
The Home button is considered the user's "safe zone" and will always launch the user's configured home app.
The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
When pressing the home button, the current home app's activity's onNewIntent
will be called.
How can I access and process nested objects, arrays or JSON?
A pythonic, recursive and functional approach to unravel arbitrary JSON trees:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
where data is a python list (parsed from a JSON text string):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
How can I hide select options with JavaScript? (Cross browser)
Here's an option that:
- Works in all browsers
- Preserves current selection when filtering
- Preserves order of items when removing / restoring
- No dirty hacks / invalid HTML
`
$('select').each(function(){
var $select = $(this);
$select.data('options', $select.find('option'));
});
function filter($select, search) {
var $prev = null;
var $options = $select.data('options');
search = search.trim().toLowerCase();
$options.each(function(){
var $option = $(this);
var optionText = $option.text();
if(search == "" || optionText.indexOf(search) >= 0) {
if ($option.parent().length) {
$prev = $option;
return;
}
if (!$prev) $select.prepend($option);
else $prev.after($option);
$prev = $option;
}
else {
$option.remove();
}
});
}
`
JSFiddle: https://jsfiddle.net/derrh5tr/
Selenium wait until document is ready
If you have a slow page or network connection, chances are that none of the above will work. I have tried them all and the only thing that worked for me is to wait for the last visible element on that page. Take for example the Bing webpage. They have placed a CAMERA icon (search by image button) next to the main search button that is visible only after the complete page has loaded. If everyone did that, then all we have to do is use an explicit wait like in the examples above.
jQuery: Test if checkbox is NOT checked
An alternative way:
Here is a working example and here is the code, you should also use prop.
$('input[type="checkbox"]').mouseenter(function() {
if ($(this).is(':checked')) {
//$(this).prop('checked',false);
alert("is checked");
} else {
//$(this).prop('checked',true);
alert("not checked");
}
});?
I commented out the way to toggle the checked attribute.
Why is this HTTP request not working on AWS Lambda?
Simple Working Example of Http request using node.
const http = require('https')
exports.handler = async (event) => {
return httprequest().then((data) => {
const response = {
statusCode: 200,
body: JSON.stringify(data),
};
return response;
});
};
function httprequest() {
return new Promise((resolve, reject) => {
const options = {
host: 'jsonplaceholder.typicode.com',
path: '/todos',
port: 443,
method: 'GET'
};
const req = http.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var body = [];
res.on('data', function(chunk) {
body.push(chunk);
});
res.on('end', function() {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch(e) {
reject(e);
}
resolve(body);
});
});
req.on('error', (e) => {
reject(e.message);
});
// send the request
req.end();
});
}
How to convert C++ Code to C
While you can do OO in C (e.g. by adding a theType *this
first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).
I would suggest at least looking at a re-design to compare how this would work out.
Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?
Removing duplicate elements from an array in Swift
I think this the better way with knowing the logic itself
var arrayOfInts = [2, 2, 4, 4]
var mainArray = [Int]()
for value in arrayOfInts {
if mainArray.contains(value) != true {
mainArray.append(value)
print("mainArray:\(mainArray)")
}}
How does the JPA @SequenceGenerator annotation work
Even though this question is very old and I stumbled upon it for my own issues with JPA 2.0 and Oracle sequences.
Want to share my research on some of the things -
Relationship between @SequenceGenerator(allocationSize) of GenerationType.SEQUENCE and INCREMENT BY in database sequence definition
Make sure @SequenceGenerator(allocationSize) is set to same value as INCREMENT BY in Database sequence definition to avoid problems (the same applies to the initial value).
For example, if we define the sequence in database with a INCREMENT BY value of 20, set the allocationsize in SequenceGenerator also to 20. In this case the JPA will not make a call to database until it reaches the next 20 mark while it increments each value by 1 internally. This saves database calls to get the next sequence number each time.
The side effect of this is - Whenever the application is redeployed or the server is restarted in between, it'll call database to get the next batch and you'll see jumps in the sequence values. Also we need to make sure the database definition and the application setting to be in-sync which may not be possible all the time as both of them are managed by different groups and you can quickly lose control of. If database value is less than the allocationsize, you'll see PrimaryKey constraint errors due to duplicate values of Id. If the database value is higher than the allocationsize, you'll see jumps in the values of Id.
If the database sequence INCREMENT BY is set to 1 (which is what DBAs generally do), set the allocationSize as also 1 so that they are in-sync but the JPA calls database to get next sequence number each time.
If you don't want the call to database each time, use GenerationType.IDENTITY strategy and have the @Id value set by database trigger. With GenerationType.IDENTITY as soon as we call em.persist the object is saved to DB and a value to id is assigned to the returned object so we don't have to do a em.merge or em.flush. (This may be JPA provider specific..Not sure)
Another important thing -
JPA 2.0 automatically runs ALTER SEQUENCE command to sync the allocationSize and INCREMENT BY in database sequence. As mostly we use a different Schema name(Application user name) rather than the actual Schema where the sequence exists and the application user name will not have ALTER SEQUENCE privileges, you might see the below warning in the logs -
000004c1 Runtime W CWWJP9991W: openjpa.Runtime: Warn: Unable
to cache sequence values for sequence "RECORD_ID_SEQ". Your
application does not have permission to run an ALTER SEQUENCE command.
Ensure that it has the appropriate permission to run an ALTER SEQUENCE
command.
As the JPA could not alter the sequence, JPA calls database everytime to get next sequence number irrespective of the value of @SequenceGenerator.allocationSize. This might be a unwanted consequence which we need to be aware of.
To let JPA not to run this command, set this value - in persistence.xml. This ensures that JPA will not try to run ALTER SEQUENCE command. It writes a different warning though -
00000094 Runtime W CWWJP9991W: openjpa.Runtime: Warn: The
property "openjpa.jdbc.DBDictionary=disableAlterSeqenceIncrementBy" is
set to true. This means that the 'ALTER SEQUENCE...INCREMENT BY' SQL
statement will not be executed for sequence "RECORD_ID_SEQ". OpenJPA
executes this command to ensure that the sequence's INCREMENT BY value
defined in the database matches the allocationSize which is defined in
the entity's sequence. With this SQL statement disabled, it is the
responsibility of the user to ensure that the entity's sequence
definition matches the sequence defined in the database.
As noted in the warning, important here is we need to make sure @SequenceGenerator.allocationSize and INCREMENT BY in database sequence definition are in sync including the default value of @SequenceGenerator(allocationSize) which is 50. Otherwise it'll cause errors.
Android Use Done button on Keyboard to click button
Your Last Edittext .setOnEditorActionListener call this method automatic hit api
I was Call in LoginActivity in et_password
et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
Log.i(Check Internet," and Connect To Server");
}
return false;
}
});
Working Fine
Asynchronous shell exec in PHP
In Linux, you can start a process in a new independent thread by appending an ampersand at the end of the command
mycommand -someparam somevalue &
In Windows, you can use the "start" DOS command
start mycommand -someparam somevalue
How to pass multiple arguments in processStartInfo?
It is purely a string:
startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:
"... -ss \"My MyAdHocTestCert.cer\""
See MSDN for this.
Using ffmpeg to encode a high quality video
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
How to prevent a dialog from closing when a button is clicked
EDIT: This only works on API 8+ as noted by some of the comments.
This is a late answer, but you can add an onShowListener to the AlertDialog where you can then override the onClickListener of the button.
final AlertDialog dialog = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Do something
//Dismiss once everything is OK.
dialog.dismiss();
}
});
}
});
dialog.show();
Only detect click event on pseudo-element
Short Answer:
I did it.
I wrote a function for dynamic usage for all the little people out there...
Working example which displays on the page
Working example logging to the console
Long Answer:
...Still did it.
It took me awhile to do it, since a psuedo element is not really on the page. While some of the answers above work in SOME scenarios, they ALL fail to be both dynamic and work in a scenario in which an element is both unexpected in size and position(such as absolute positioned elements overlaying a portion of the parent element). Mine does not.
Usage:
//some element selector and a click event...plain js works here too
$("div").click(function() {
//returns an object {before: true/false, after: true/false}
psuedoClick(this);
//returns true/false
psuedoClick(this).before;
//returns true/false
psuedoClick(this).after;
});
How it works:
It grabs the height, width, top, and left positions(based on the position away from the edge of the window) of the parent element and grabs the height, width, top, and left positions(based on the edge of the parent container) and compares those values to determine where the psuedo element is on the screen.
It then compares where the mouse is. As long as the mouse is in the newly created variable range then it returns true.
Note:
It is wise to make the parent element RELATIVE positioned. If you have an absolute positioned psuedo element, this function will only work if it is positioned based on the parent's dimensions(so the parent has to be relative...maybe sticky or fixed would work too....I dont know).
Code:
function psuedoClick(parentElem) {
var beforeClicked,
afterClicked;
var parentLeft = parseInt(parentElem.getBoundingClientRect().left, 10),
parentTop = parseInt(parentElem.getBoundingClientRect().top, 10);
var parentWidth = parseInt(window.getComputedStyle(parentElem).width, 10),
parentHeight = parseInt(window.getComputedStyle(parentElem).height, 10);
var before = window.getComputedStyle(parentElem, ':before');
var beforeStart = parentLeft + (parseInt(before.getPropertyValue("left"), 10)),
beforeEnd = beforeStart + parseInt(before.width, 10);
var beforeYStart = parentTop + (parseInt(before.getPropertyValue("top"), 10)),
beforeYEnd = beforeYStart + parseInt(before.height, 10);
var after = window.getComputedStyle(parentElem, ':after');
var afterStart = parentLeft + (parseInt(after.getPropertyValue("left"), 10)),
afterEnd = afterStart + parseInt(after.width, 10);
var afterYStart = parentTop + (parseInt(after.getPropertyValue("top"), 10)),
afterYEnd = afterYStart + parseInt(after.height, 10);
var mouseX = event.clientX,
mouseY = event.clientY;
beforeClicked = (mouseX >= beforeStart && mouseX <= beforeEnd && mouseY >= beforeYStart && mouseY <= beforeYEnd ? true : false);
afterClicked = (mouseX >= afterStart && mouseX <= afterEnd && mouseY >= afterYStart && mouseY <= afterYEnd ? true : false);
return {
"before" : beforeClicked,
"after" : afterClicked
};
}
Support:
I dont know....it looks like ie is dumb and likes to return auto as a computed value sometimes. IT SEEMS TO WORK WELL IN ALL BROWSERS IF DIMENSIONS ARE SET IN CSS. So...set your height and width on your psuedo elements and only move them with top and left. I recommend using it on things that you are okay with it not working on. Like an animation or something. Chrome works...as usual.
How to multiply all integers inside list
#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.
print(results)
How to download a file via FTP with Python ftplib
Please note if you are downloading from the FTP to your local, you will need to use the following:
with open( filename, 'wb' ) as file :
ftp.retrbinary('RETR %s' % filename, file.write)
Otherwise, the script will at your local file storage rather than the FTP.
I spent a few hours making the mistake myself.
Script below:
import ftplib
# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')
filenames = ftp.nlst()
for filename in filenames:
with open( filename, 'wb' ) as file :
ftp.retrbinary('RETR %s' % filename, file.write)
file.close()
ftp.quit()
Simple two column html layout without using tables
<div id"content">
<div id"contentLeft"></div>
<div id"contentRight"></div>
</div>
#content {
clear: both;
width: 950px;
padding-bottom: 10px;
background:#fff;
overflow:hidden;
}
#contentLeft {
float: left;
display:inline;
width: 630px;
margin: 10px;
background:#fff;
}
#contentRight {
float: right;
width: 270px;
margin-top:25px;
margin-right:15px;
background:#d7e5f7;
}
Obviously you will need to adjust the size of the columns to suit your site as well as colours etc but that should do it. You also need to make sure that your ContentLeft and ContentRight widths do not exceed the Contents width (including margins).
Accessing session from TWIG template
{{app.session}}
refers to the Session
object and not the $_SESSION
array. I don't think the $_SESSION
array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.
Symfony2 is object-oriented, so you should use the Session
object to set session attributes and not rely on the array. The Session
object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.
So, set your attribute in the session and retrieve the value in your twig template by using the Session
object.
// In a controller
$session = $this->get('session');
$session->set('filter', array(
'accounts' => 'value',
));
// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}
Hope this helps.
Regards,
Matt
How to capitalize the first letter of word in a string using Java?
I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Java Code:
class Main {
public static void main(String[] args) {
System.out.println("Capitalize first letter ");
System.out.println("Normal check #1 : ["+ captializeFirstLetter("one thousand only")+"]");
System.out.println("Normal check #2 : ["+ captializeFirstLetter("two hundred")+"]");
System.out.println("Normal check #3 : ["+ captializeFirstLetter("twenty")+"]");
System.out.println("Normal check #4 : ["+ captializeFirstLetter("seven")+"]");
System.out.println("Single letter check : ["+captializeFirstLetter("a")+"]");
System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
System.out.println("Null Check : ["+ captializeFirstLetter(null)+"]");
}
static String captializeFirstLetter(String input){
if(input!=null && input.length() >0){
input = input.substring(0, 1).toUpperCase() + input.substring(1);
}
return input;
}
}
Output:
Normal check #1 : [One thousand only]
Normal check #2 : [Two hundred]
Normal check #3 : [Twenty]
Normal check #4 : [Seven]
Single letter check : [A]
IndexOutOfBound check : []
Null Check : [null]
PHP Fatal error when trying to access phpmyadmin mb_detect_encoding
I had the same trouble, this is what worked for me.
You can click at the wampserver icon, then at the PHP error log.
Check if it says this:
Unable to load dynamic library 'c:/wamp/bin/php/php5.5.12/ext/php_ldap.dll'
If yes, then you can reload your version of PHP, by clicking at the wampserver icon, then PHP, then version, and then you click at your version.
Wait for everything to be online again, then try to access phpmyadmin.
Job for mysqld.service failed See "systemctl status mysqld.service"
I met this problem today, and fix it with bellowed steps.
1, Check the log file /var/log/mysqld.log
tail -f /var/log/mysqld.log
2017-03-14T07:06:53.374603Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 2 - No such file or directory)
2017-03-14T07:06:53.374614Z 0 [ERROR] Can't start server: can't create PID file: No such file or directory
The log says that there isn't a file or directory /var/run/mysqld/mysqld.pid
2, Create the directory /var/run/mysqld
mkdir -p /var/run/mysqld/
3, Start the mysqld again service mysqld start
, but still fail, check the log again /var/log/mysqld.log
2017-03-14T07:14:22.967667Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 13 - Permission denied)
2017-03-14T07:14:22.967678Z 0 [ERROR] Can't start server: can't create PID file: Permission denied
It saids permission denied.
4, Grant the permission to mysql
chown mysql.mysql /var/run/mysqld/
5, Restart the mysqld
# service mysqld restart
Restarting mysqld (via systemctl): [ OK ]
Statically rotate font-awesome icons
In case someone else stumbles upon this question and wants it here is the SASS mixin I use.
@mixin rotate($deg: 90){
$sDeg: #{$deg}deg;
-webkit-transform: rotate($sDeg);
-moz-transform: rotate($sDeg);
-ms-transform: rotate($sDeg);
-o-transform: rotate($sDeg);
transform: rotate($sDeg);
}
How do I create an Android Spinner as a popup?
You can use an alert dialog
AlertDialog.Builder b = new Builder(this);
b.setTitle("Example");
String[] types = {"By Zip", "By Category"};
b.setItems(types, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
onZipRequested();
break;
case 1:
onCategoryRequested();
break;
}
}
});
b.show();
This will close the dialog when one of them is pressed like you are wanting. Hope this helps!
Http Basic Authentication in Java using HttpClient?
Ok so this one works. Just in case anybody wants it, here's the version that works for me :)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class HttpBasicAuth {
public static void main(String[] args) {
try {
URL url = new URL ("http://ip:port/login");
String encoding = Base64.getEncoder().encodeToString(("test1:test1").getBytes(?"UTF??-8"?));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
How to update/modify an XML file in python?
The quick and easy way, which you definitely should not do (see below), is to read the whole file into a list of strings using readlines()
. I write this in case the quick and easy solution is what you're looking for.
Just open the file using open()
, then call the readlines()
method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines()
.
An example might help:
my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)
The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parser. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand.
Tim's answer mentioned checking out xml.dom.minidom
for this purpose, which I think would be a great idea.
How does "cat << EOF" work in bash?
This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.
From man bash
:
Here Documents
This type of redirection instructs the shell to read input from
the current source until a line
containing only word (with no trailing
blanks) is seen.
All of the lines read up to that point are then used as the
standard input for a command.
The format of here-documents is:
<<[-]word
here-document
delimiter
No parameter expansion, command substitution, arithmetic expansion, or
pathname expansion is performed on
word. If any characters in word are
quoted, the
delimiter is the result of quote removal on word, and the lines
in the here-document are not expanded.
If word is unquoted, all lines of the
here-document are subjected to parameter expansion, command
substitution, and arithmetic
expansion. In the latter case, the
character sequence \<newline>
is
ignored, and \
must be used to quote the characters \
, $
, and `
.
If the redirection operator is <<-
, then all leading tab characters
are stripped from input lines and the
line containing delimiter. This
allows here-documents within shell scripts to be indented in a natural fashion.
Count distinct value pairs in multiple columns in SQL
Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:
SELECT count(DISTINCT concat(id, name, address)) FROM mytable;
How to get time in milliseconds since the unix epoch in Javascript?
Date.now() returns a unix timestamp in milliseconds.
_x000D_
_x000D_
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
_x000D_
_x000D_
Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
_x000D_
_x000D_
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
_x000D_
_x000D_
Group a list of objects by an attribute
You can use the following:
Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
String key = student.stud_location;
if (groupedStudents.get(key) == null) {
groupedStudents.put(key, new ArrayList<Student>());
}
groupedStudents.get(key).add(student);
}
//print
Set<String> groupedStudentsKeySet = groupedCustomer.keySet();
for (String location: groupedStudentsKeySet) {
List<Student> stdnts = groupedStudents.get(location);
for (Student student : stdnts) {
System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
}
}
selected value get from db into dropdown select box option using php mysql error
This may help you.
?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res))
{
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
// Assuming $list['options'] is a coma seperated options string
$arr=explode(",",$list['options']);
<?php foreach ($arr as $value) { ?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } >
</select>
<?php
}
?>
Jquery select change not firing
You can fire chnage event by these methods:
First
$('#selectid').change(function () {
alert('This works');
});
Second
$(document).on('change', '#selectid', function() {
alert('This Works');
});
Third
$(document.body).on('change','#selectid',function(){
alert('This Works');
});
If this methods not working, check your jQuery working or not:
$(document).ready(function($) {
alert('Jquery Working');
});
MySQL export into outfile : CSV escaping chars
Without actually seeing your output file for confirmation, my guess is that you've got to get rid of the FIELDS ESCAPED BY
value.
MySQL's FIELDS ESCAPED BY
is probably behaving in two ways that you were not counting on: (1) it is only meant to be one character, so in your case it is probably equal to just one quotation mark; (2) it is used to precede each character that MySQL thinks needs escaping, including the FIELDS TERMINATED BY
and LINES TERMINATED BY
values. This makes sense to most of the computing world, but it isn't the way Excel does escaping.
I think your double REPLACE
is working, and that you are successfully replacing literal newlines with spaces (two spaces in the case of Windows-style newlines). But if you have any commas in your data (literals, not field separators), these are being preceded by quotation marks, which Excel treats much differently than MySQL. If that's the case, then the erroneous newlines that are tripping up Excel are actually newlines that MySQL had intended as line terminators.
php create object without class
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
Sound effects in JavaScript / HTML5
Here's an idea. Load all of your audio for a certain class of sounds into a single individual audio element where the src data is all of your samples in a contiguous audio file (probably want some silence between so you can catch and cut the samples with a timeout with less risk of bleeding to the next sample). Then, seek to the sample and play it when needed.
If you need more than one of these to play you can create an additional audio element with the same src so that it is cached. Now, you effectively have multiple "tracks". You can utilize groups of tracks with your favorite resource allocation scheme like Round Robin etc.
You could also specify other options like queuing sounds into a track to play when that resource becomes available or cutting a currently playing sample.
Convert Variable Name to String?
I searched for this question because I wanted a Python program to print assignment statements for some of the variables in the program. For example, it might print "foo = 3, bar = 21, baz = 432". The print function would need the variable names in string form. I could have provided my code with the strings "foo","bar", and "baz", but that felt like repeating myself. After reading the previous answers, I developed the solution below.
The globals() function behaves like a dict with variable names (in the form of strings) as keys. I wanted to retrieve from globals() the key corresponding to the value of each variable. The method globals().items() returns a list of tuples; in each tuple the first item is the variable name (as a string) and the second is the variable value. My variablename() function searches through that list to find the variable name(s) that corresponds to the value of the variable whose name I need in string form.
The function itertools.ifilter() does the search by testing each tuple in the globals().items() list with the function lambda x: var is globals()[x[0]]
. In that function x is the tuple being tested; x[0] is the variable name (as a string) and x[1] is the value. The lambda function tests whether the value of the tested variable is the same as the value of the variable passed to variablename(). In fact, by using the is
operator, the lambda function tests whether the name of the tested variable is bound to the exact same object as the variable passed to variablename(). If so, the tuple passes the test and is returned by ifilter().
The itertools.ifilter() function actually returns an iterator which doesn't return any results until it is called properly. To get it called properly, I put it inside a list comprehension [tpl[0] for tpl ... globals().items())]
. The list comprehension saves only the variable name tpl[0]
, ignoring the variable value. The list that is created contains one or more names (as strings) that are bound to the value of the variable passed to variablename().
In the uses of variablename() shown below, the desired string is returned as an element in a list. In many cases, it will be the only item in the list. If another variable name is assigned the same value, however, the list will be longer.
>>> def variablename(var):
... import itertools
... return [tpl[0] for tpl in
... itertools.ifilter(lambda x: var is x[1], globals().items())]
...
>>> var = {}
>>> variablename(var)
['var']
>>> something_else = 3
>>> variablename(something_else)
['something_else']
>>> yet_another = 3
>>> variablename(something_else)
['yet_another', 'something_else']
Bad operand type for unary +: 'str'
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
Read file from resources folder in Spring Boot
After spending a lot of time trying to resolve this issue, finally found a solution that works. The solution makes use of Spring's ResourceUtils.
Should work for json files as well.
Thanks for the well written page by Lokesh Gupta : Blog
package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());
public static Properties fetchProperties(){
Properties properties = new Properties();
try {
File file = ResourceUtils.getFile("classpath:application.properties");
InputStream in = new FileInputStream(file);
properties.load(in);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return properties;
}
}
To answer a few concerns on the comments :
Pretty sure I had this running on Amazon EC2 using java -jar target/image-service-slave-1.0-SNAPSHOT.jar
Look at my github repo : https://github.com/johnsanthosh/image-service
to figure out the right way to run this from a JAR.
What is the best workaround for the WCF client `using` block issue?
Actually, although I blogged (see Luke's answer), I think this is better than my IDisposable wrapper. Typical code:
Service<IOrderService>.Use(orderService=>
{
orderService.PlaceOrder(request);
});
(edit per comments)
Since Use
returns void, the easiest way to handle return values is via a captured variable:
int newOrderId = 0; // need a value for definite assignment
Service<IOrderService>.Use(orderService=>
{
newOrderId = orderService.PlaceOrder(request);
});
Console.WriteLine(newOrderId); // should be updated
Select Last Row in the Table
For laravel 8:
Model::orderBy('id', 'desc')->withTrashed()->take(1)->first()->id
The resulting sql query:
Model::orderBy('id', 'desc')->withTrashed()->take(1)->toSql()
select * from "timetables" order by "id" desc limit 1
How can you get the Manifest Version number from the App's (Layout) XML variables?
There is not a way to directly get the version out, but there are two work-arounds that could be done.
The version could be stored in a resource string, and placed into the manifest by:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.somepackage"
android:versionName="@string/version" android:versionCode="20">
One could create a custom view, and place it into the XML. The view would use this to assign the name:
context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
Either of these solutions would allow for placing the version name in XML. Unfortunately there isn't a nice simple solution, like android.R.string.version
or something like that.
ASP.Net which user account running Web Service on IIS 7?
I had a ton of trouble with this and then found a great solution:
Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo 'php is running as user: ' . exec('whoami');
?>
How can I view a git log of just one user's commits?
This works for both git log
and gitk - the 2 most common ways of viewing history.
You don't need to use the whole name:
git log --author="Jon"
will match a commit made by "Jonathan Smith"
git log --author=Jon
and
git log --author=Smith
would also work. The quotes are optional if you don't need any spaces.
Add --all
if you intend to search all branches and not just the current commit's ancestors in your repo.
You can also easily match on multiple authors as regex is the underlying mechanism for this filter. So to list commits by Jonathan or Adam, you can do this:
git log --author="\(Adam\)\|\(Jon\)"
In order to exclude commits by a particular author or set of authors using regular expressions as noted in this question, you can use a negative lookahead in combination with the --perl-regexp
switch:
git log --author='^(?!Adam|Jon).*$' --perl-regexp
Alternatively, you can exclude commits authored by Adam by using bash
and piping:
git log --format='%H %an' |
grep -v Adam |
cut -d ' ' -f1 |
xargs -n1 git log -1
If you want to exclude commits commited (but not necessarily authored) by Adam, replace %an
with %cn
. More details about this are in my blog post here: http://dymitruk.com/blog/2012/07/18/filtering-by-author-name/
Iterator invalidation rules
It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator
, std::front_insert_iterator
, std::insert_iterator
) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.
For example, when you are performing a series of insertion operations into a std::vector
by using std::insert_iterator
it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.
This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.
For example, this code
std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);
for (unsigned n = 20; n > 0; --n)
*it_ins++ = rand();
is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it
will obviously become invalid, but it_ins
will continue to remain valid.
PHP Echo text Color
This is an old question, but no one responded to the question regarding centering text in a terminal.
/**
* Centers a string of text in a terminal window
*
* @param string $text The text to center
* @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
*
* @return string The padded result, ready to echo
*/
function center($text, $pad_string = ' ') {
$window_size = (int) `tput cols`;
return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}
echo center('foo');
echo center('bar baz', '=');
javascript windows alert with redirect function
Alert will block the program flow so you can just write the following.
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='http://someplace.com';
</script>");
Day Name from Date in JS
you can use an object
var days = {
'Mon': 'Monday',
'etc..': 'etc..',
'Fri': 'Friday'
}
var date = new Date().toString().split(' ')[0]; //get day abreviation first
console.log(days[date]);
How to vertical align an inline-block in a line of text?
_x000D_
_x000D_
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_
Tested and works in Safari 5 and IE6+.
Detect whether there is an Internet connection available on Android
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Which HTML elements can receive focus?
Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:
a[href]:not([tabindex='-1']),
area[href]:not([tabindex='-1']),
input:not([disabled]):not([tabindex='-1']),
select:not([disabled]):not([tabindex='-1']),
textarea:not([disabled]):not([tabindex='-1']),
button:not([disabled]):not([tabindex='-1']),
iframe:not([tabindex='-1']),
[tabindex]:not([tabindex='-1']),
[contentEditable=true]:not([tabindex='-1'])
{
/* your CSS for focusable elements goes here */
}
or a little more beautiful in SASS:
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
&:not([tabindex='-1'])
{
/* your SCSS for focusable elements goes here */
}
}
I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.
EDIT: There is one more selector, which is focusable:
[contentEditable=true]
However, this is used very rarely.
What is mapDispatchToProps?
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
Is it possible to clone html element objects in JavaScript / JQuery?
Using your code you can do something like this in plain JavaScript using the cloneNode() method:
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );
// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Or using jQuery clone() method (not the most efficient):
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
Best way to call a JSON WebService from a .NET Console
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
How do I hide a menu item in the actionbar?
Yes.
- You can set a flag/condition.
- Call
invalidateOptionsMenu()
when you want to hide the option. This will call onCreateOptionsMenu()
.
- In
onCreateOptionsMenu()
, check for the flag/condition and show or
hide it the following way:
MenuItem item = menu.findItem(R.id.menu_Done);
if (flag/condition)) {
item.setVisible(false);
} else { }
SQL Update Multiple Fields FROM via a SELECT Statement
I would write it this way
UPDATE s
SET OrgAddress1 = bd.OrgAddress1, OrgAddress2 = bd.OrgAddress2,
... DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc
FROM Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on bd.MyID =s.MyID2
WHERE bd.MyID = @MyId
This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.
How to install "ifconfig" command in my ubuntu docker image?
Please use the below command to get the IP address of the running container.
$ ip addr
Example-:
root@4c712d05922b:/# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
247: eth0@if248: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:06 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.6/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:6/64 scope link
valid_lft forever preferred_lft forever
Browser detection in JavaScript?
Here is how I do custom CSS for Internet Explorer:
In my JavaScript file:
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
jQuery(document).ready(function(){
if(var_isIE){
if(var_isIE == 10){
jQuery("html").addClass("ie10");
}
if(var_isIE == 8){
jQuery("html").addClass("ie8");
// you can also call here some function to disable things that
//are not supported in IE, or override browser default styles.
}
}
});
And then in my CSS file, y define each different style:
.ie10 .some-class span{
.......
}
.ie8 .some-class span{
.......
}
Is header('Content-Type:text/plain'); necessary at all?
It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser;
<?php
header('Content-Type:text/html');
?>
<p>Hello</p>
You will see:
hello
(note that you will get the same results if you miss off the header line in this case - text/html is php's default)
Change it to text/plain
<?php
header('Content-Type:text/plain');
?>
<p>Hello</p>
You will see:
<p>Hello</p>
Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request:
<?php
header('Content-Type:text/html');
print "Your name is " . $_GET['name']
Someone can put a link to a URL like http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe.
Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.
Jquery select this + class
What you are looking for is this:
$(".subclass", this).css("visibility","visible");
Add the this
after the class $(".subclass", this)
How to convert JSON string to array
Use json_decode($json_string, TRUE)
function to convert the JSON object to an array.
Example:
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$my_array_data = json_decode($json_string, TRUE);
NOTE: The second parameter will convert decoded JSON string into an associative array.
===========
Output:
var_dump($my_array_data);
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Split column at delimiter in data frame
@Taesung Shin is right, but then just some more magic to make it into a data.frame
.
I added a "x|y" line to avoid ambiguities:
df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
foo <- data.frame(do.call('rbind', strsplit(as.character(df$FOO),'|',fixed=TRUE)))
Or, if you want to replace the columns in the existing data.frame:
within(df, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))
Which produces:
ID FOO.X1 FOO.X2
1 11 a b
2 12 b c
3 13 x y
Creating a button in Android Toolbar
I was able to achieve that by wrapping Button
with ConstraintLayout
:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<androidx.appcompat.widget.Toolbar
android:id="@+id/top_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/white_color">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:layout_marginStart="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_publish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/publish"
android:background="@drawable/button_publish_rounded"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="10dp"
app:layout_constraintLeft_toRightOf="@id/cancel"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
You may create a drawable resourcebutton_publish_rounded
, define the button properties and assign this file to button's android:background
property:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/green" />
<corners android:radius="100dp" />
</shape>
Get current url in Angular
You can make use of location service available in @angular/common and via this below code you can get the location or current URL
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) {
router.events.subscribe((val) => {
if(location.path() != ''){
this.route = location.path();
} else {
this.route = 'Home'
}
});
}
ngOnInit() {
}
}
here is the reference link from where I have copied thing to get location for my project.
https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts
find . -type f -exec chmod 644 {} ;
I need this so often that I created a function in my ~/.bashrc
file:
chmodf() {
find $2 -type f -exec chmod $1 {} \;
}
chmodd() {
find $2 -type d -exec chmod $1 {} \;
}
Now I can use these shortcuts:
chmodd 0775 .
chmodf 0664 .
Setting action for back button in navigation controller
Use isMovingFromParentViewController
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
if self.isMovingFromParentViewController {
// current viewController is removed from parent
// do some work
}
}
Check empty string in Swift?
You can use this extension:
extension String {
static func isNilOrEmpty(string: String?) -> Bool {
guard let value = string else { return true }
return value.trimmingCharacters(in: .whitespaces).isEmpty
}
}
and then use it like this:
let isMyStringEmptyOrNil = String.isNilOrEmpty(string: myString)
What is the default maximum heap size for Sun's JVM from Java SE 6?
To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode.
You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:
http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html
Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.
Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.
Thanks to this SO post for guiding me:
Definition of server-class machine changed recently?
How do you check in python whether a string contains only numbers?
As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit()
method is not totally accurate for this use case, because it returns True for some digit-like characters:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")
Using android.support.v7.widget.CardView in my project (Eclipse)
I was able to work it out only after adding those two TOGETHER:
dependencies {
...
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
...
}
in my build.gradle (Module:app) file
and then press the sync now button
How to use multiple databases in Laravel
Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysqlOne' => [
'driver' => 'mysql',
'host' => env('DB_HOST_ONE', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_ONE', 'forge'),
'username' => env('DB_USERNAME_ONE', 'forge'),
'password' => env('DB_PASSWORD_ONE', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
];
Once you have this you can create two base model class for each connection and define the connection name in those models
//BaseModel.php
protected $connection = 'mysql';
//BaseModelOne.php
protected $connection = 'mysqlOne';
You can extend these models to create more models for tables in each DB.
SQL selecting rows by most recent date with two unique columns
You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth
SELECT
CHARGEID,
CHARGETYPE,
MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
What is Persistence Context?
In layman terms we can say that Persistence Context is an environment where entities are managed, i.e it syncs "Entity" with the database.
How to encode a URL in Swift
If it's possible that the value that you're adding to your URL can have reserved characters (as defined by section 2 of RFC 3986), you might have to refine your percent-escaping. Notably, while &
and +
are valid characters in a URL, they're not valid within a URL query parameter value (because &
is used as delimiter between query parameters which would prematurely terminate your value, and +
is translated to a space character). Unfortunately, the standard percent-escaping leaves those delimiters unescaped.
Thus, you might want to percent escape all characters that are not within RFC 3986's list of unreserved characters:
Characters that are allowed in a URI but do not have a reserved
purpose are called unreserved. These include uppercase and lowercase
letters, decimal digits, hyphen, period, underscore, and tilde.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
Later, in section 3.4, the RFC further contemplates adding ?
and /
to the list of allowed characters within a query:
The characters slash ("/") and question mark ("?") may represent data
within the query component. Beware that some older, erroneous
implementations may not handle such data correctly when it is used as
the base URI for relative references (Section 5.1), apparently
because they fail to distinguish query data from path data when
looking for hierarchical separators. However, as query components
are often used to carry identifying information in the form of
"key=value" pairs and one frequently used value is a reference to
another URI, it is sometimes better for usability to avoid percent-
encoding those characters.
Nowadays, you'd generally use URLComponents
to percent escape the query value:
var address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"
var components = URLComponents(string: "http://maps.googleapis.com/maps/api/geocode/json")!
components.queryItems = [URLQueryItem(name: "address", value: address)]
let url = components.url!
By the way, while it's not contemplated in the aforementioned RFC, section 5.2, URL-encoded form data, of the W3C HTML spec says that application/x-www-form-urlencoded
requests should also replace space characters with +
characters (and includes the asterisk in the characters that should not be escaped). And, unfortunately, URLComponents
won't properly percent escape this, so Apple advises that you manually percent escape it before retrieving the url
property of the URLComponents
object:
// configure `components` as shown above, and then:
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let url = components.url!
For Swift 2 rendition, where I manually do all of this percent escaping myself, see the previous revision of this answer.
How to make an authenticated web request in Powershell?
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
Finding what branch a Git commit came from
Update December 2013:
sschuberth comments
git-what-branch
(Perl script, see below) does not seem to be maintained anymore.
git-when-merged
is an alternative written in Python that's working very well for me.
It is based on "Find merge commit which include a specific commit".
git when-merged [OPTIONS] COMMIT [BRANCH...]
Find when a commit was merged into one or more branches.
Find the merge commit that brought COMMIT
into the specified BRANCH(es).
Specifically, look for the oldest commit on the first-parent history of BRANCH
that contains the COMMIT
as an ancestor.
Original answer September 2010:
Sebastien Douche just twitted (16 minutes before this SO answer):
git-what-branch: Discover what branch a commit is on, or how it got to a named branch
This is a Perl script from Seth Robertson that seems very interesting:
SYNOPSIS
git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...
OVERVIEW
Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch.
If a commit was made directly on a named branch, that obviously is the earliest path.
By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless --topo-order
is specified).
PERFORMANCE
If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular --reference-branch --reference tag
to examine will be hundreds of times faster (if you have hundreds of candidate branches).
EXAMPLES
# git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May 5 08:59:37 2005)
v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May 3 18:27:24 2005)
v2.6.12-rc3-461-g84e48b6 is on master
v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
[...]
This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.
Mean filter for smoothing images in Matlab
h = fspecial('average', n);
filter2(h, img);
See doc fspecial
:
h = fspecial('average', n)
returns an averaging filter. n
is a 1-by-2 vector specifying the number of rows and columns in h
.
String to Binary in C#
The following will give you the hex encoding for the low byte of each character, which looks like what you're asking for:
StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
uint i = (uint)c;
sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();
How to multi-line "Replace in files..." in Notepad++
Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.
To activate it just go to N++ menu:
Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.
Restart N++ and press ALT + SHIFT + F to multiline edit.
Open fancybox from function
The answers seems a bit over complicated. I hope I didn't misunderstand the question.
If you simply want to open a fancy box from a click to an "A" tag. Just set your html to
<a id="my_fancybox" href="#contentdiv">click me</a>
The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:
$('#my_fancybox').fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
});
This will show a fancybox containing "contentdiv" when your anchor tag is clicked.
Access props inside quotes in React JSX
Best practices are to add getter method for that :
getImageURI() {
return "images/" + this.props.image;
}
<img className="image" src={this.getImageURI()} />
Then , if you have more logic later on, you can maintain the code smoothly.
How to find text in a column and saving the row number where it is first found - Excel VBA
Dim FindRow as Range
Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
' column i.e. the first
LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
SearchOrder:=xlByRows, _ 'This look down the column row by row
'Larger Ranges with multiple columns can be set to
' look column by column then down
MatchCase:=False) ' this says that the search is not case sensitive
If Not FindRow Is Nothing Then ' if findrow is something (Prevents Errors)
FirstRow = FindRow.Row ' set FirstRow to the first time a match is found
End If
If you would like to get addition ones you can use:
Do Until FindRow Is Nothing
Set FindRow = Range("A:A").FindNext(after:=FindRow)
If FindRow.row = FirstRow Then
Exit Do
Else ' Do what you'd like with the additional rows here.
End If
Loop
How to display text in pygame?
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
What's onCreate(Bundle savedInstanceState)
onCreate(Bundle savedInstanceState)
you will get the Bundle
null when activity get starts first time and it will get in use when activity orientation get changed .......
http://www.gitshah.com/2011/03/how-to-handle-screen-orientation_28.html
Android provides another elegant way of achieving this. To achieve this, we have to override a method called onSaveInstanceState()
. Android platform allows the users to save any instance state. Instance state can be saved in the Bundle. Bundle is passed as argument to the onSaveInstanceState method.
we can load the saved instance state from the Bundle passed as argument to the onCreate
method. We can also load the saved instance state in onRestoreInstanceState
method. But I will leave that for the readers to figure out.
Difference between $(window).load() and $(document).ready() functions
document.ready
is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.
window.onload
fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.
How to manage exceptions thrown in filters in Spring?
This is my solution by overriding default Spring Boot /error handler
package com.mypackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* This controller is vital in order to handle exceptions thrown in Filters.
*/
@RestController
@RequestMapping("/error")
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
private final static Logger LOGGER = LoggerFactory.getLogger(ErrorController.class);
private final ErrorAttributes errorAttributes;
@Autowired
public ErrorController(ErrorAttributes errorAttributes) {
Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest aRequest, HttpServletResponse response) {
RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest);
Map<String, Object> result = this.errorAttributes.getErrorAttributes(requestAttributes, false);
Throwable error = this.errorAttributes.getError(requestAttributes);
ResponseStatus annotation = AnnotationUtils.getAnnotation(error.getClass(), ResponseStatus.class);
HttpStatus statusCode = annotation != null ? annotation.value() : HttpStatus.INTERNAL_SERVER_ERROR;
result.put("status", statusCode.value());
result.put("error", statusCode.getReasonPhrase());
LOGGER.error(result.toString());
return new ResponseEntity<>(result, statusCode) ;
}
}
Can I append an array to 'formdata' in javascript?
How about this?
formdata.append('tags', JSON.stringify(tags));
... and, correspondingly, using json_decode
on server to deparse it. See, the second value of FormData.append can be...
a Blob, File, or a string, if neither, the value is converted to a
string
The way I see it, your tags
array contains objects (@Musa is right, btw; making this_tag
an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with toString()
) won't be enough. JSON'ing should get the info through, though.
As a sidenote, I'd rewrite the property assigning block just into this:
tags.push({article: article, gender: gender, brand: brand});