Export and Import all MySQL databases at one time
I wrote this comment already more than 4 years ago and decided now to make it to an answer.
The script from jruzafa can be a bit simplified:
#!/bin/bash
USER="zend"
PASSWORD=""
ExcludeDatabases="Database|information_schema|performance_schema|mysql"
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | egrep -v $ExcludeDatabases`
for db in $databases; do
echo "Dumping database: $db"
mysqldump -u $USER -p$PASSWORD --databases $db > `date +%Y%m%d`.$db.sql
# gzip $OUTPUT`date +%Y%m%d`.$db.sql
done
Note:
- The excluded databases - prevalently the system tables - are provided in the variable
ExcludeDatabases
- Please be aware that the password is provided in the command line. This is considered as insecure. Study this question.
How to import a bak file into SQL Server Express
To do this via TSQL (ssms query window or sqlcmd.exe) just run:
RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'
To do it via GUI - open SSMS, right click on Databases and follow the steps below
How to solve privileges issues when restore PostgreSQL Database
To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:
root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------------+-------------+-----------
<user-name> | Superuser | {}
: Create DB
postgres | Superuser | {}
: Create role
: Create DB
postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#
So connect to the database under a Superuser account sudo -u postgres psql
and execute a ALTER ROLE <user-name> Superuser;
statement.
Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.
How to get cookie's expire time
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
Error converting data types when importing from Excel to SQL Server 2008
Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:
- Paste from excel into Notepad and save as normal (.txt file).
- From within excel, open said .txt file.
- Select next as it is obviously tab delimited.
- Select "none" for text qualifier, then next again.
- Select the first row, hold shift, select the last row, and select the text radial button. Click Finish
It will open, check it to make sure it's accurate and then save as an excel file.
How do you upload a file to a document library in sharepoint?
As an alternative to the webservices, you can use the put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).
For a reference application that explains the use of Frontpage RPC, see the SharePad project on CodePlex.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Mapping over values in a python dictionary
You can do this in-place, rather than create a new dict, which may be preferable for large dictionaries (if you do not need a copy).
def mutate_dict(f,d):
for k, v in d.iteritems():
d[k] = f(v)
my_dictionary = {'a':1, 'b':2}
mutate_dict(lambda x: x+1, my_dictionary)
results in my_dictionary
containing:
{'a': 2, 'b': 3}
bootstrap multiselect get selected values
$('#multiselect1').on('change', function(){
var selected = $(this).find("option:selected");
var arrSelected = [];
selected.each(function(){
arrSelected.push($(this).val());
});
});
How to create a testflight invitation code?
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
Reactjs convert html string to jsx
There are now safer methods to accomplish this. The docs have been updated with these methods.
Other Methods
Easiest - Use Unicode, save the file as UTF-8 and set the charset
to UTF-8.
<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using dangerouslySetInnerHTML
.
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
How do I set a background-color for the width of text, not the width of the entire element, using CSS?
EDIT: the answer below would apply in most cases. OP however later mentioned that they could not edit anything other than the CSS file. But will leave this here so it may be of use to others.
The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.
You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.
In an example that I made, I targeted all <p>
elements with jQuery and wrapped it with a div with a class of "colored"
$( "p" ).wrap( "<div class='colored'></div>" );
Then in my CSS i targeted the <p>
and gave it the background color and changed to display: inline
.colored p {
display: inline;
background: green;
}
By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen
How can I set the color of a selected row in DataGrid
The above solution left blue border around each cell in my case.
This is the solution that worked for me. It is very simple, just add this to your DataGrid
. You can change it from a SolidColorBrush
to any other brush such as linear gradient.
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#FF0000"/>
</DataGrid.Resources>
React-router urls don't work when refreshing or writing manually
Solution for Preact with preact-router
Works with refresh and direct access
For those discovering this via Google, here's a demo of preact-router + hash history:
const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
<div>
<AddressBar />
<Router history={createHashHistory()}>
<div path="/">
<p>
all paths in preact-router are still /normal/urls.
using hash history rewrites them to /#/hash/urls
</p>
Example: <a href="/page2">page 2</a>
</div>
<div path="/page2">
<p>Page Two</p>
<a href="/">back to home</a><br/>
</div>
</Router>
</div>
);
jsfiddle
Undefined symbols for architecture i386
well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks
i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.
ENJOY
Play audio with Python
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
document .click function for touch device
touchstart or touchend are not good, because if you scroll the page, the device do stuff.
So, if I want close a window with tap or click outside the element, and scroll the window, I've done:
$(document).on('touchstart', function() {
documentClick = true;
});
$(document).on('touchmove', function() {
documentClick = false;
});
$(document).on('click touchend', function(event) {
if (event.type == "click") documentClick = true;
if (documentClick){
doStuff();
}
});
Add views in UIStackView programmatically
It is really not recommended to set a height constraint... If you can, never, never, never set a height! You need to check all the constraints of the views inside your UIStackView and be sure that there is constraints for bottom, top, leading and trailing. Someone said to me: it is like a guy pushing on walls. If he don't push on 4 sides, one of the wall will fall on him.
How to pass objects to functions in C++?
There are three methods of passing an object to a function as a parameter:
- Pass by reference
- pass by value
- adding constant in parameter
Go through the following example:
class Sample
{
public:
int *ptr;
int mVar;
Sample(int i)
{
mVar = 4;
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value of the pointer is " << *ptr << endl
<< "The value of the variable is " << mVar;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
char ch;
cin >> ch;
}
Output:
Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4
String concatenation: concat() vs "+" operator
I don't think so.
a.concat(b)
is implemented in String and I think the implementation didn't change much since early java machines. The +
operation implementation depends on Java version and compiler. Currently +
is implemented using StringBuffer
to make the operation as fast as possible. Maybe in the future, this will change. In earlier versions of java +
operation on Strings was much slower as it produced intermediate results.
I guess that +=
is implemented using +
and similarly optimized.
What is the difference between a "function" and a "procedure"?
Procedures:
1.Procedures are the collections of statements that defines parameterized computations.
2.Procedures cannot return values.
3.Procedures cannot be called from function.
Functions
1.Functions structurally resemble procedures but are semantically modeled on mathematical functions.
2.It can return values
3.Function can be called from procedures.
jQuery ajax call to REST service
I think there is no need to specify
'http://localhost:8080`"
in the URI part.. because. if you specify it, You'll have to change it manually for every environment.
Only
"/restws/json/product/get" also works
Can't use Swift classes inside Objective-C
Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h
header file and you will be able to import.
You can set module definition and module name in your project settings.
jQuery won't parse my JSON from AJAX query
This problem is usually because your request received the wrong mime type. When developing on your own computer, sometimes you are not receiving the proper mime type from the "server", which is your own computer. I ran into this problem once when developing by opening the locally stored file in the browser (e.g. the url was "c:/project/test.html").
Try using the beforeSend property to add a callback function that overrides the mime type. This will trick the code into dealing with json despite the wrong mime type being sent by the server and received by your calling code. Some example code is below.
The proper mime type is application/json according to this question, but I do know that application/j-son worked when I tried it (now several years ago). You should probably try application/json first.
var jsonMimeType = "application/json;charset=UTF-8";
$.ajax({
type: "GET",
url: myURL,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType: "json",
success: function(data){
// do stuff...
}
});
JavaScript function to add X months to a date
The following is an example of how to calculate a future date based on date input (membershipssignup_date) + added months (membershipsmonths) via form fields.
The membershipsmonths field has a default value of 0
Trigger link (can be an onchange event attached to membership term field):
<a href="#" onclick="calculateMshipExp()"; return false;">Calculate Expiry Date</a>
function calculateMshipExp() {
var calcval = null;
var start_date = document.getElementById("membershipssignup_date").value;
var term = document.getElementById("membershipsmonths").value; // Is text value
var set_start = start_date.split('/');
var day = set_start[0];
var month = (set_start[1] - 1); // January is 0 so August (8th month) is 7
var year = set_start[2];
var datetime = new Date(year, month, day);
var newmonth = (month + parseInt(term)); // Must convert term to integer
var newdate = datetime.setMonth(newmonth);
newdate = new Date(newdate);
//alert(newdate);
day = newdate.getDate();
month = newdate.getMonth() + 1;
year = newdate.getFullYear();
// This is British date format. See below for US.
calcval = (((day <= 9) ? "0" + day : day) + "/" + ((month <= 9) ? "0" + month : month) + "/" + year);
// mm/dd/yyyy
calcval = (((month <= 9) ? "0" + month : month) + "/" + ((day <= 9) ? "0" + day : day) + "/" + year);
// Displays the new date in a <span id="memexp">[Date]</span> // Note: Must contain a value to replace eg. [Date]
document.getElementById("memexp").firstChild.data = calcval;
// Stores the new date in a <input type="hidden" id="membershipsexpiry_date" value="" name="membershipsexpiry_date"> for submission to database table
document.getElementById("membershipsexpiry_date").value = calcval;
}
app-release-unsigned.apk is not signed
i also appear this problem,and my code below
storeFile file(properties.getProperty("filepath"))
storePassword properties.getProperty("keypassword")
keyAlias properties.getProperty("keyAlias")
keyPassword properties.getProperty("keypassword")
the reason is property name error,it should be keyPassword not keypassword
How to download the latest artifact from Artifactory repository?
If you want to download the latest jar between 2 repositores, you can use this solution. I actually use it within my Jenkins pipeline, it works perfectly. Let's say you have a plugins-release-local and plugins-snapshot-local and you want to download the latest jar between these. Your shell script should look like this
NOTE : I use jfrog cli and it's configured with my Artifactory server.
Use case : Shell script
# your repo, you can change it then or pass an argument to the script
# repo = $1 this get the first arg passed to the script
repo=plugins-snapshot-local
# change this by your artifact path, or pass an argument $2
artifact=kshuttle/ifrs16
path=$repo/$artifact
echo $path
~/jfrog rt download --flat $path/maven-metadata.xml version/
version=$(cat version/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
echo "VERSION $version"
~/jfrog rt download --flat $path/$version/maven-metadata.xml build/
build=$(cat build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
echo "BUILD $build"
# change this by your app name, or pass an argument $3
name=ifrs16
jar=$name-$build.jar
url=$path/$version/$jar
# Download
echo $url
~/jfrog rt download --flat $url
Use case : Jenkins Pipeline
def getLatestArtifact(repo, pkg, appName, configDir){
sh """
~/jfrog rt download --flat $repo/$pkg/maven-metadata.xml $configDir/version/
version=\$(cat $configDir/version/maven-metadata.xml | grep latest | sed "s/.*<latest>\\([^<]*\\)<\\/latest>.*/\\1/")
echo "VERSION \$version"
~/jfrog rt download --flat $repo/$pkg/\$version/maven-metadata.xml $configDir/build/
build=\$(cat $configDir/build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\\([^<]*\\)<\\/value>.*/\\1/")
echo "BUILD \$build"
jar=$appName-\$build.jar
url=$repo/$pkg/\$version/\$jar
# Download
echo \$url
~/jfrog rt download --flat \$url
"""
}
def clearDir(dir){
sh """
rm -rf $dir/*
"""
}
node('mynode'){
stage('mysstage'){
def repos = ["plugins-snapshot-local","plugins-release-local"]
for (String repo in repos) {
getLatestArtifact(repo,"kshuttle/ifrs16","ifrs16","myConfigDir/")
}
//optional
clearDir("myConfigDir/")
}
}
This helps alot when you want to get the latest package between 1 or more repos. Hope it helps u too!
For more Jenkins scripted pipelines info, visit Jenkins docs.
Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=
How can I decrypt MySQL passwords
With luck, if the original developer was any good, you will not be able to get the plain text out. I say "luck" otherwise you probably have an insecure system.
For the admin passwords, as you have the code, you should be able to create hashed passwords from a known plain text such that you can take control of the application. Follow the algorithm used by the original developer.
If they were not salted and hashed, then make sure you do apply this as 'best practice'
Using Python's ftplib to get a directory listing, portably
There's no standard for the layout of the LIST
response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls
and Windows Server DIR
formats. There's a lot of variety out there, though.
Fall back to the nlst
method (returning the result of the NLST
command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.
Programmatically switching between tabs within Swift
Just to update, following iOS 13, we now have SceneDelegates. So one might choose to put the desired tab selection in SceneDelegate.swift as follows:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
if let tabBarController = self.window!.rootViewController as? UITabBarController {
tabBarController.selectedIndex = 1
}
}
Console.log not working at all
Now in modern browsers, console.log()
can be used by pressing F12 key. The picture will be helpful to understand the concept clearly.
How do I get the domain originating the request in express.js?
Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host')
is deprecated, that's why giving Undefined
.
Use,
req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
POST Multipart Form Data using Retrofit 2.0 including image
Update Code for image file uploading in Retrofit2.0
public interface ApiInterface {
@Multipart
@POST("user/signup")
Call<UserModelResponse> updateProfilePhotoProcess(@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("profile_pic\"; filename=\"pp.png")
RequestBody file);
}
Change MediaType.parse("image/*")
to MediaType.parse("image/jpeg")
RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
file);
RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
"[email protected]");
RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
"123456789");
Call<UserModelResponse> call = apiService.updateProfilePhotoProcess(email,
password,
reqFile);
call.enqueue(new Callback<UserModelResponse>() {
@Override
public void onResponse(Call<UserModelResponse> call,
Response<UserModelResponse> response) {
String
TAG =
response.body()
.toString();
UserModelResponse userModelResponse = response.body();
UserModel userModel = userModelResponse.getUserModel();
Log.d("MainActivity",
"user image = " + userModel.getProfilePic());
}
@Override
public void onFailure(Call<UserModelResponse> call,
Throwable t) {
Toast.makeText(MainActivity.this,
"" + TAG,
Toast.LENGTH_LONG)
.show();
}
});
PHP - iterate on string characters
Expanded from @SeaBrightSystems answer, you could try this:
$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array
How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?
For your interest, to do the same with double
double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75
or just
double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n", doubleVal);
System.out.printf("bdTest1: %.2f%n", doubleVal2);
both print
bdTest: 1.75
bdTest1: 0.75
I prefer to keep code as simple as possible. ;)
As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335
are a little less than they appear.
How to pass 2D array (matrix) in a function in C?
2D array:
int sum(int array[][COLS], int rows)
{
}
3D array:
int sum(int array[][B][C], int A)
{
}
4D array:
int sum(int array[][B][C][D], int A)
{
}
and nD array:
int sum(int ar[][B][C][D][E][F].....[N], int A)
{
}
How to remove item from a python list in a loop?
hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).
glglgl's answer suffers from O(n²) complexity, because list.remove
is O(n).
Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del
keywork to remove by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
del x[index]
Now del x[i]
is also O(n) because you need to copy all elements after index i
(a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove
because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.
[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress
which was introduced in python 2.7:
from itertools import compress
selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:] # trim the end of the list
Convert blob to base64
There is a pure JavaSript way that is not depended on any stacks:
const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
For using this helper function you should set a callback, example:
blobToBase64(blobData).then(res => {
// do what you wanna do
console.log(res); // res is base64 now
});
I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:
fetch(imageAddressAsStringValue)
.then(res => res.blob())
.then(blobToBase64)
.then(finalResult => {
storeOnMyLocalDatabase(finalResult);
});
Async always WaitingForActivation
The reason is your result
assigned to the returning Task
which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:
var task = Task.Run(() =>
{
for (int i = 10; i < 432543543; i++)
{
// just for a long job
double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
}
return "Foo Completed.";
});
while (task.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);
}
Console.WriteLine("Result: {0}", task.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
The output
:
Consider this for better explanation: You have a Foo
method,let's say it Task A, and you have a Task
in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task
which is Task A, because Task B doesn't return a Task, it returns a string
. Consider this:
If you define your result like this:
Task result = Foo(5);
You won't get any error.But if you define it like this:
string result = Foo(5);
You will get:
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'
But if you add an await
keyword:
string result = await Foo(5);
Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:
private static async Task<string> Foo(int seconds)
{
await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
// in here don't return anything
});
return await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.
How to update specific key's value in an associative array in PHP?
This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value
foreach ($array as $key => $item) {
$item["your_field"] = "new_value";
$array[$key] = $item;
}
In your case new_value will be a date() function
Read specific columns from a csv file with csv module?
I think there is an easier way
import pandas as pd
dataset = pd.read_csv('table1.csv')
ftCol = dataset.iloc[:, 0].values
So in here iloc[:, 0]
, :
means all values, 0
means the position of the column.
in the example below ID
will be selected
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
How can I get the nth character of a string?
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str
is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str
which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
Sum rows in data.frame or matrix
I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind
function:
cbind(data, total = rowSums(data))
This method adds a total
column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).
Adding a new column to matrix error
Get the difference between two dates both In Months and days in sql
Find out Year - Month- Day between two Days in Orale Sql
select
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
from dual;
Linux command for extracting war file?
A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.
But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.
How to define and use function inside Jenkins Pipeline config?
Solved! The call build job: project, parameters: params
fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List
when params = [:]
. Replacing it with params = null
solved the issue.
Here the working code below.
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1')
}
}
Hibernate SessionFactory vs. JPA EntityManagerFactory
I prefer the JPA2 EntityManager
API over SessionFactory
, because it feels more modern. One simple example:
JPA:
@PersistenceContext
EntityManager entityManager;
public List<MyEntity> findSomeApples() {
return entityManager
.createQuery("from MyEntity where apples=7", MyEntity.class)
.getResultList();
}
SessionFactory:
@Autowired
SessionFactory sessionFactory;
public List<MyEntity> findSomeApples() {
Session session = sessionFactory.getCurrentSession();
List<?> result = session.createQuery("from MyEntity where apples=7")
.list();
@SuppressWarnings("unchecked")
List<MyEntity> resultCasted = (List<MyEntity>) result;
return resultCasted;
}
I think it's clear that the first one looks cleaner and is also easier to test because EntityManager can be easily mocked.
Get values from label using jQuery
You can use the attr
method. For example, if you have a jQuery object called label
, you could use this code:
console.log(label.attr("year")); // logs the year
console.log(label.attr("month")); // logs the month
How can I use Oracle SQL developer to run stored procedures?
I am not sure how to see the actual
rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
Tree data structure in C#
In case you need a rooted tree data structure implementation that uses less memory, you can write your Node class as follows (C++ implementation):
class Node {
Node* parent;
int item; // depending on your needs
Node* firstChild; //pointer to left most child of node
Node* nextSibling; //pointer to the sibling to the right
}
How to find if a given key exists in a C++ std::map
If you want to compare pair of map you can use this method:
typedef map<double, double> TestMap;
TestMap testMap;
pair<map<double,double>::iterator,bool> controlMapValues;
controlMapValues= testMap.insert(std::pair<double,double>(x,y));
if (controlMapValues.second == false )
{
TestMap::iterator it;
it = testMap.find(x);
if (it->second == y)
{
cout<<"Given value is already exist in Map"<<endl;
}
}
This is a useful technique.
Difference Between Cohesion and Coupling
Cohesion is an indication of how related and focused the responsibilities of an software element are.
Coupling refers to how strongly a software element is connected to other elements.
The software element could be class, package, component, subsystem or a system. And while designing the systems it is recommended to have software elements that have High cohesion and support Low coupling.
Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usablity. Similarly High Coupling results in classes that are tightly coupled and changes tend not be non-local, difficult to change and reduces the reuse.
We can take a hypothetical scenario where we are designing an typical monitor-able ConnectionPool
with the following requirements. Note that, it might look too much for a simple class like ConnectionPool
but the basic intent is just to demonstrate low coupling and high cohesion with some simple example and I think should help.
- support getting a connection
- release a connection
- get stats about connection vs usage count
- get stats about connection vs time
- Store the connection retrieval and release information to a database for reporting later.
With low cohesion we could design a ConnectionPool
class by forcefully stuffing all this functionality/responsibilities into a single class as below. We can see that this single class is responsible for connection management, interacting with database as well maintaining connection stats.
With high cohesion we can assign these responsibility across the classes and make it more maintainable and reusable.
To demonstrate Low coupling we will continue with the high cohesion ConnectionPool
diagram above. If we look at the above diagram although it supports high cohesion, the ConnectionPool
is tightly coupled with ConnectionStatistics
class and PersistentStore
it interacts with them directly. Instead to reduce the coupling we could introduce a ConnectionListener
interface and let these two classes implement the interface and let them register with ConnectionPool
class. And the ConnectionPool
will iterate through these listeners and notify them of connection get and release events and allows less coupling.
Note/Word or Caution: For this simple scenario it may look like an overkill but if we imagine a real-time scenario where our application needs to interact with multiple third party services to complete a transaction: Directly coupling our code with the third party services would mean that any changes in the third party service could result in changes to our code at multiple places, instead we could have Facade
that interacts with these multiple services internally and any changes to the services become local to the Facade
and enforce low coupling with the third party services.
How do I retrieve query parameters in Spring Boot?
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
- curl 'http://localhost:8080/user/books'
- curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'
clearing select using jquery
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
Multiple Inheritance in C#
Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.
Add centered text to the middle of a <hr/>-like line
Flexbox and SCSS
HTML
<div class="divider">divider</div>
SCSS
.divider {
display: flex;
align-items: center;
text-align: center;
color: #c2c2c2;
&::before,
&::after {
content: "";
flex: 1;
border-bottom: 1px solid #c2c2c2;
}
&::before {
margin-right: 0.25em;
}
&::after {
margin-left: 0.25em;
}
}
Are nested try/except blocks in Python a good programming practice?
I like to avoid raising a new exception while handling an old one. It makes the error messages confusing to read.
For example, in my code, I originally wrote
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
raise KeyError(key)
And I got this message.
>>> During handling of above exception, another exception occurred.
I wanted this:
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
pass
raise KeyError(key)
It doesn't affect how exceptions are handled. In either block of code, a KeyError would have been caught. This is merely an issue of getting style points.
Invoking Java main method with parameters from Eclipse
I'm not sure what your uses are, but I find it convenient that usually I use no more than several command line parameters, so each of those scenarios gets one run configuration, and I just pick the one I want from the Run History.
The feature you are suggesting seems a bit of an overkill, IMO.
With CSS, use "..." for overflowed block of multi-lines
Here's a recent css-tricks article which discusses this.
Some of the solutions in the above article (which are not mentioned here) are
1) -webkit-line-clamp
and 2) Place an absolutely positioned element to the bottom right with fade out
Both methods assume the following markup:
<div class="module"> /* Add line-clamp/fade class here*/
<p>Text here</p>
</div>
with css
.module {
width: 250px;
overflow: hidden;
}
1) -webkit-line-clamp
line-clamp FIDDLE (..for a maximum of 3 lines)
.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
max-height: 3.6em; /* I needed this to get it to work */
}
2) fade out
Let's say you set the line-height to 1.2em. If we want to expose
three lines of text, we can just make the height of the container
3.6em (1.2em × 3). The hidden overflow will hide the rest.
Fade out FIDDLE
p
{
margin:0;padding:0;
}
.module {
width: 250px;
overflow: hidden;
border: 1px solid green;
margin: 10px;
}
.fade {
position: relative;
height: 3.6em; /* exactly three lines */
}
.fade:after {
content: "";
text-align: right;
position: absolute;
bottom: 0;
right: 0;
width: 70%;
height: 1.2em;
background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
}
Solution #3 - A combination using @supports
We can use @supports to apply webkit's line-clamp on webkit browsers and apply fade out in other browsers.
@supports line-clamp with fade fallback fiddle
<div class="module line-clamp">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>
CSS
.module {
width: 250px;
overflow: hidden;
border: 1px solid green;
margin: 10px;
}
.line-clamp {
position: relative;
height: 3.6em; /* exactly three lines */
}
.line-clamp:after {
content: "";
text-align: right;
position: absolute;
bottom: 0;
right: 0;
width: 70%;
height: 1.2em;
background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
}
@supports (-webkit-line-clamp: 3) {
.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
max-height:3.6em; /* I needed this to get it to work */
height: auto;
}
.line-clamp:after {
display: none;
}
}
RE error: illegal byte sequence on Mac OS X
Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?
$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64
I got part of the way to answering the above just by using tr.
I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all
; ;
with
;;
Here goes:
$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence
I used od to shed some light: Note the 374 halfway down this od -c output
$ head -3 Auswertungen.csv | tail -1 | od -c
0000000 1 6 8 7 9 6 1 9 7 1 2 2 ; 5
0000020 4 6 8 8 7 X X X X X X 2 6
0000040 6 0 ; M Y N A M E I S X ; 1
0000060 4 . 0 2 . 2 0 1 9 ; 9 5 5 2 -
0000100 M i t a r b e i t e r r e s t
0000120 Z 374 r i c h
0000140 C H E ; R e s t a u r a n t s ,
0000160 B a r s ; 6 . 2 0 ; C H F ;
0000200 ; C H F ; 6 . 2 0 ; ; 1 5 . 0
0000220 2 . 2 0 1 9 \n
0000227
Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:
$ head -3 Auswertungen.csv | tail -1 | tr . . ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest Z
You can see tr bails at the 374 character.
Using perl seems to avoid this problem
$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest Z?rich CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019
Better way to convert file sizes in Python
Here my two cents, which permits casting up and down, and adds customizable precision:
def convertFloatToDecimal(f=0.0, precision=2):
'''
Convert a float to string of decimal.
precision: by default 2.
If no arg provided, return "0.00".
'''
return ("%." + str(precision) + "f") % f
def formatFileSize(size, sizeIn, sizeOut, precision=0):
'''
Convert file size to a string representing its value in B, KB, MB and GB.
The convention is based on sizeIn as original unit and sizeOut
as final unit.
'''
assert sizeIn.upper() in {"B", "KB", "MB", "GB"}, "sizeIn type error"
assert sizeOut.upper() in {"B", "KB", "MB", "GB"}, "sizeOut type error"
if sizeIn == "B":
if sizeOut == "KB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**3), precision)
elif sizeIn == "KB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeIn == "MB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeIn == "GB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**3), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size*1024.0), precision)
Add TB
, etc, as you wish.
How to add a line break within echo in PHP?
\n
is a line break. /n
is not.
use of \n
with
1. echo directly to page
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with <br />
or <br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
Output
kings
garden
Note Make sure you're echoing/printing \n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
2. write to text file
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
What does the 'export' command do?
In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions.
The export
command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.
100% width in React Native Flexbox
just remove the alignItems: 'center'
in the container styles and add textAlign: "center"
to the line1
style like given below.
It will work well
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 1,
}
line1: {
backgroundColor: '#FDD7E4',
textAlign:'center'
},
json_encode sparse PHP array as JSON array, not JSON object
Array
in JSON
are indexed array only, so the structure you're trying to get is not valid Json/Javascript.
PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.
If you want to get such structure you can do:
$indexedOnly = array();
foreach ($associative as $row) {
$indexedOnly[] = array_values($row);
}
json_encode($indexedOnly);
Will returns something like:
[
[0, "name1", "n1"],
[1, "name2", "n2"],
]
Creating files and directories via Python
import os
os.mkdir('directory name') #### this command for creating directory
os.mknod('file name') #### this for creating files
os.system('touch filename') ###this is another method for creating file by using unix commands in os modules
Remove NA values from a vector
The na.omit
function is what a lot of the regression routines use internally:
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
Trim specific character from a string
expanding on @leaf 's answer, here's one that can take multiple characters:
var trim = function (s, t) {
var tr, sr
tr = t.split('').map(e => `\\\\${e}`).join('')
sr = s.replace(new RegExp(`^[${tr}]+|[${tr}]+$`, 'g'), '')
return sr
}
How can I resolve "Your requirements could not be resolved to an installable set of packages" error?
Your software dependencies have an incompatible version conflict.
At the same time you want to install any Laravel 4.2.x version, and "zizaco/entrust" from its master branch. And that master branch requires at least Laravel 5.0 (roughly speaking).
The problem comes from the dependency on branches. It's likely that the package zizaco/entrust once was using Laravel 4.2 in its master branch, and that you were able to install your dependencies at that day. But the very moment this branch gets updated with an incompatible version requirement, you will never ever be able to run composer update
and get updated dependencies.
Always use tagged versions! Ideally you use a relaxed version requirement that allows for compatible updates. This should be expressed as a tilde-two-number version requirement: ~1.2
would install a version 1.2.0 and up (like 1.2.99 or 1.2.100), and also 1.3 and up. If you need a certain patch release: Caret-three-number version ^1.2.10
will install 1.2.10 or up, also 1.3 and up.
Using this version requirement instead of dev-master
will allow you to use released versions instead of the unstable state in the master branch, and allows you to address the most recent version that still works with Laravel 4.2. I guess that would be zizaco/entrust version 1.3.0, but version 1.2 would also qualify. Go with "zizaco/entrust": "~1.2"
.
Populating a database in a Laravel migration file
Another clean way to do it is to define a private method which create instance et persist concerned Model.
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('label', 256);
$table->timestamps();
$table->softDeletes();
});
$this->postCreate('admin', 'user');
}
private function postCreate(string ...$roles) {
foreach ($roles as $role) {
$model = new Role();
$model->setAttribute('label', $role);
$model->save();
}
}
With this solution, timestamps fields will be generated by Eloquent.
EDIT:
it's better to use seeder system to disctinct database structure generation and database population.
Should I use Java's String.format() if performance is important?
The answer to this depends very much on how your specific Java compiler optimizes the bytecode it generates. Strings are immutable and, theoretically, each "+" operation can create a new one. But, your compiler almost certainly optimizes away interim steps in building long strings. It's entirely possible that both lines of code above generate the exact same bytecode.
The only real way to know is to test the code iteratively in your current environment. Write a QD app that concatenates strings both ways iteratively and see how they time out against each other.
Is the sizeof(some pointer) always equal to four?
In general, sizeof(pretty much anything) will change when you compile on different platforms. On a 32 bit platform, pointers are always the same size. On other platforms (64 bit being the obvious example) this can change.
How to disable back swipe gesture in UINavigationController on iOS 7
For Swift 4 this works:
class MyViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.gesture.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.interactivePopGestureRecognizer?.gesture.isEnabled = false
}
}
Eliminating duplicate values based on only one column of the table
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
Running an executable in Mac Terminal
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
I get exception when using Thread.sleep(x) or wait()
As other users have said you should surround your call with a try{...} catch{...}
block. But since Java 1.5 was released, there is TimeUnit class which do the same as Thread.sleep(millis) but is more convenient.
You can pick time unit for sleep operation.
try {
TimeUnit.NANOSECONDS.sleep(100);
TimeUnit.MICROSECONDS.sleep(100);
TimeUnit.MILLISECONDS.sleep(100);
TimeUnit.SECONDS.sleep(100);
TimeUnit.MINUTES.sleep(100);
TimeUnit.HOURS.sleep(100);
TimeUnit.DAYS.sleep(100);
} catch (InterruptedException e) {
//Handle exception
}
Also it has additional methods:
TimeUnit Oracle Documentation
Bad Gateway 502 error with Apache mod_proxy and Tomcat
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that mod_proxy
considers a backend as failed only when the
transport layer connection to that backend fails. Unless failonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a balancer
here, so the timeout
parameter relates to
the balancer
(like the two others).
However for a balancer
, the timeout
parameter is not a connection
timeout (like the one used with BalancerMember
), but the maximum time
to wait for a free worker/member (e.g. when all the workers are busy
or in error state, the default being to not wait).
So, a proper configuration is done like this
- set
timeout
at the BalanceMember
level:
<Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
- set the
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
Using ng-if as a switch inside ng-repeat?
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
Migrating from VMWARE to VirtualBox
This error occurs because VMware has a bug that uses the absolute path of the disk file in certain situations.
If you look at the top of that small *.vmdk file you'll likely see an incorrect absolute path to the original VMDK file that needs to be corrected.
If statement with String comparison fails
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>
Javascript find json value
Just use the ES6 find()
function in a functional way:
_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_
or Lodash _.find:
_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_
In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?
Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);
Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);
System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map: {test2=2, test1=1}
// map2: {test2=2, test1=1}
You can use the forEach
method to do what you want.
What you're doing there is:
map.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String s, Integer integer) {
map2.put(s, integer);
}
});
Which we can simplify into a lambda:
map.forEach((s, integer) -> map2.put(s, integer));
And because we're just calling an existing method we can use a method reference, which gives us:
map.forEach(map2::put);
Python import csv to list
Here is the easiest way in Python 3.x to import a CSV to a multidimensional array, and its only 4 lines of code without importing anything!
#pull a CSV into a multidimensional array in 4 lines!
L=[] #Create an empty list for the main array
for line in open('log.txt'): #Open the file and read all the lines
x=line.rstrip() #Strip the \n from each line
L.append(x.split(',')) #Split each line into a list and add it to the
#Multidimensional array
print(L)
object==null or null==object?
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code
These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.
To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.
Prophylactic measures to prevent you getting the error again
The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR
package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.
Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.
Common syntactic mistakes that generate these errors
Mismatched parentheses, braces or brackets
If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.
{}}
## Error: unexpected '}' in "{}}"
{{}} # OK
Missing *
when doing multiplication
This is a common mistake by mathematicians.
5x
Error: unexpected symbol in "5x"
5*x # OK
Not wrapping if, for, or return values in parentheses
This is a common mistake by MATLAB users. In R, if
, for
, return
, etc., are functions, so you need to wrap their contents in parentheses.
if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK
Not using multiple lines for code
Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.
x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK
else
starting on a new line
In an if
-else
statement, the keyword else
must appear on the same line as the end of the if
block.
if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}
=
instead of ==
=
is used for assignment and giving values to function arguments. ==
tests two values for equality.
if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK
Missing commas between arguments
When calling a function, each argument must be separated by a comma.
c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK
Not quoting file paths
File paths are just strings. They need to be wrapped in double or single quotes.
path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK
Quotes inside strings
This is a common problem when trying to pass quoted values to the shell via system
, or creating quoted xPath
or sql
queries.
Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.
"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK
Using curly quotes
So-called "smart" quotes are not so smart for R programming.
path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK
Using non-standard variable names without backquotes
?make.names
describes what constitutes a valid variable name. If you create a non-valid variable name (using assign
, perhaps), then you need to access it with backquotes,
assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK
This also applies to column names in data frames created with check.names = FALSE
.
dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK
It also applies when passing operators and other special values to functions. For example, looking up help on %in%
.
?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK
Sourcing non-R code
The source
function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table
.
source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^
Corrupted RStudio desktop file
RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop
file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.
Using expression without paste in mathematical plot annotations
When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath
page. Otherwise the contents should be contained inside a call to paste.
plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK
How to change default text color using custom theme?
You can't use @android:style/TextAppearance
as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.
To change default text colour everywhere in your app using a custom theme, try something like this.
Works at least on Android 4.0+ (API level 14+).
res/values/themes.xml
:
<resources>
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<!-- Change default text colour from dark grey to black -->
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
Manifest:
<application
...
android:theme="@style/MyAppTheme">
Update
A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)
As I learned by asking this question, a better way is to define the colour using a drawable:
<item name="android:textColor">@drawable/default_text_color</item>
...with res/drawable/default_text_color.xml
specifying separate state_enabled="false"
colour:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/darker_gray"/>
<item android:color="@android:color/black"/>
</selector>
Separators for Navigation
You can add one li
element where you want to add divider
<ul>
<li> your content </li>
<li class="divider-vertical-second-menu"></li>
<li> NExt content </li>
<li class="divider-vertical-second-menu"></li>
<li> last item </li>
</ul>
In CSS you can Add following code.
.divider-vertical-second-menu{
height: 40px;
width: 1px;
margin: 0 5px;
overflow: hidden;
background-color: #DDD;
border-right: 2px solid #FFF;
}
This will increase you speed of execution as it will not load any image. just test it out.. :)
How to print something to the console in Xcode?
You can also use breakpoints. Assuming the value you want is defined within the scope of your breakpoint you have 3 options:
print it in console doing:
po some_paramter
Bare in mind in objective-c for properties you can't use self.
po _someProperty
po self.someProperty // would not work
po stands for print object.
Or can just use Xcode 'Variable Views' . See the image
I highly recommend seeing Debugging with Xcode from Apple
Or just hover over within your code. Like the image below.
How do I pass a datetime value as a URI parameter in asp.net mvc?
Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer
I would suggest sending the date value as a parameter rather than as part of the route:
mysite/Controller/Action?date=21-9-2009 10:20
If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:
encodeURIComponent(yourstring)
It is a method within Javascript.
On the Server Side:
public ActionResult ActionName(string date)
{
DateTime mydate;
DateTime.Tryparse(date, out mydate);
}
FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.
How to check if matching text is found in a string in Lua?
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
Example
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match(s, pattern, optional index)
Returns the capture groups found.
Example
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Check if table exists
/**
* Method that checks if all tables exist
* If a table doesnt exist it creates the table
*/
public void checkTables() {
try {
startConn();// method that connects with mysql database
String useDatabase = "USE " + getDatabase() + ";";
stmt.executeUpdate(useDatabase);
String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
DatabaseMetaData metadata = conn.getMetaData();
for(int i=0; i< tables.length; i++) {
ResultSet rs = metadata.getTables(null, null, tables[i], null);
if(!rs.next()) {
createTable(tables[i]);
System.out.println("Table " + tables[i] + " created");
}
}
} catch(SQLException e) {
System.out.println("checkTables() " + e.getMessage());
}
closeConn();// Close connection with mysql database
}
Defining a variable with or without export
export NAME=value
for settings and variables that have meaning to a subprocess.
NAME=value
for temporary or loop variables private to the current shell process.
In more detail, export
marks the variable name in the environment that copies to a subprocesses and their subprocesses upon creation. No name or value is ever copied back from the subprocess.
A common error is to place a space around the equal sign:
$ export FOO = "bar"
bash: export: `=': not a valid identifier
Only the exported variable (B
) is seen by the subprocess:
$ A="Alice"; export B="Bob"; echo "echo A is \$A. B is \$B" | bash
A is . B is Bob
Changes in the subprocess do not change the main shell:
$ export B="Bob"; echo 'B="Banana"' | bash; echo $B
Bob
Variables marked for export have values copied when the subprocess is created:
$ export B="Bob"; echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash &
[1] 3306
$ B="Banana"; echo '(sleep 30; echo "Subprocess 2 has B=$B")' | bash
Subprocess 1 has B=Bob
Subprocess 2 has B=Banana
[1]+ Done echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash
Only exported variables become part of the environment (man environ
):
$ ALICE="Alice"; export BOB="Bob"; env | grep "ALICE\|BOB"
BOB=Bob
So, now it should be as clear as is the summer's sun! Thanks to Brain Agnew, alexp, and William Prusell.
Heap vs Binary Search Tree (BST)
Summary
Type BST (*) Heap
Insert average log(n) 1
Insert worst log(n) log(n) or n (***)
Find any worst log(n) n
Find max worst 1 (**) 1
Create worst n log(n) n
Delete worst log(n) log(n)
All average times on this table are the same as their worst times except for Insert.
*
: everywhere in this answer, BST == Balanced BST, since unbalanced sucks asymptotically
**
: using a trivial modification explained in this answer
***
: log(n)
for pointer tree heap, n
for dynamic array heap
Advantages of binary heap over a BST
average time insertion into a binary heap is O(1)
, for BST is O(log(n))
. This is the killer feature of heaps.
There are also other heaps which reach O(1)
amortized (stronger) like the Fibonacci Heap, and even worst case, like the Brodal queue, although they may not be practical because of non-asymptotic performance: Are Fibonacci heaps or Brodal queues used in practice anywhere?
binary heaps can be efficiently implemented on top of either dynamic arrays or pointer-based trees, BST only pointer-based trees. So for the heap we can choose the more space efficient array implementation, if we can afford occasional resize latencies.
binary heap creation is O(n)
worst case, O(n log(n))
for BST.
Advantage of BST over binary heap
search for arbitrary elements is O(log(n))
. This is the killer feature of BSTs.
For heap, it is O(n)
in general, except for the largest element which is O(1)
.
"False" advantage of heap over BST
heap is O(1)
to find max, BST O(log(n))
.
This is a common misconception, because it is trivial to modify a BST to keep track of the largest element, and update it whenever that element could be changed: on insertion of a larger one swap, on removal find the second largest. Can we use binary search tree to simulate heap operation? (mentioned by Yeo).
Actually, this is a limitation of heaps compared to BSTs: the only efficient search is that for the largest element.
Average binary heap insert is O(1)
Sources:
Intuitive argument:
- bottom tree levels have exponentially more elements than top levels, so new elements are almost certain to go at the bottom
- heap insertion starts from the bottom, BST must start from the top
In a binary heap, increasing the value at a given index is also O(1)
for the same reason. But if you want to do that, it is likely that you will want to keep an extra index up-to-date on heap operations How to implement O(logn) decrease-key operation for min-heap based Priority Queue? e.g. for Dijkstra. Possible at no extra time cost.
GCC C++ standard library insert benchmark on real hardware
I benchmarked the C++ std::set
(Red-black tree BST) and std::priority_queue
(dynamic array heap) insert to see if I was right about the insert times, and this is what I got:
- benchmark code
- plot script
- plot data
- tested on Ubuntu 19.04, GCC 8.3.0 in a Lenovo ThinkPad P51 laptop with CPU: Intel Core i7-7820HQ CPU (4 cores / 8 threads, 2.90 GHz base, 8 MB cache), RAM: 2x Samsung M471A2K43BB1-CRC (2x 16GiB, 2400 Mbps), SSD: Samsung MZVLB512HAJQ-000L7 (512GB, 3,000 MB/s)
So clearly:
heap insert time is basically constant.
We can clearly see dynamic array resize points. Since we are averaging every 10k inserts to be able to see anything at all above system noise, those peaks are in fact about 10k times larger than shown!
The zoomed graph excludes essentially only the array resize points, and shows that almost all inserts fall under 25 nanoseconds.
BST is logarithmic. All inserts are much slower than the average heap insert.
BST vs hashmap detailed analysis at: What data structure is inside std::map in C++?
GCC C++ standard library insert benchmark on gem5
gem5 is a full system simulator, and therefore provides an infinitely accurate clock with with m5 dumpstats
. So I tried to use it to estimate timings for individual inserts.
Interpretation:
heap is still constant, but now we see in more detail that there are a few lines, and each higher line is more sparse.
This must correspond to memory access latencies are done for higher and higher inserts.
TODO I can't really interpret the BST fully one as it does not look so logarithmic and somewhat more constant.
With this greater detail however we can see can also see a few distinct lines, but I'm not sure what they represent: I would expect the bottom line to be thinner, since we insert top bottom?
Benchmarked with this Buildroot setup on an aarch64 HPI CPU.
BST cannot be efficiently implemented on an array
Heap operations only need to bubble up or down a single tree branch, so O(log(n))
worst case swaps, O(1)
average.
Keeping a BST balanced requires tree rotations, which can change the top element for another one, and would require moving the entire array around (O(n)
).
Heaps can be efficiently implemented on an array
Parent and children indexes can be computed from the current index as shown here.
There are no balancing operations like BST.
Delete min is the most worrying operation as it has to be top down. But it can always be done by "percolating down" a single branch of the heap as explained here. This leads to an O(log(n)) worst case, since the heap is always well balanced.
If you are inserting a single node for every one you remove, then you lose the advantage of the asymptotic O(1) average insert that heaps provide as the delete would dominate, and you might as well use a BST. Dijkstra however updates nodes several times for each removal, so we are fine.
Dynamic array heaps vs pointer tree heaps
Heaps can be efficiently implemented on top of pointer heaps: Is it possible to make efficient pointer-based binary heap implementations?
The dynamic array implementation is more space efficient. Suppose that each heap element contains just a pointer to a struct
:
the tree implementation must store three pointers for each element: parent, left child and right child. So the memory usage is always 4n
(3 tree pointers + 1 struct
pointer).
Tree BSTs would also need further balancing information, e.g. black-red-ness.
the dynamic array implementation can be of size 2n
just after a doubling. So on average it is going to be 1.5n
.
On the other hand, the tree heap has better worst case insert, because copying the backing dynamic array to double its size takes O(n)
worst case, while the tree heap just does new small allocations for each node.
Still, the backing array doubling is O(1)
amortized, so it comes down to a maximum latency consideration. Mentioned here.
Philosophy
BSTs maintain a global property between a parent and all descendants (left smaller, right bigger).
The top node of a BST is the middle element, which requires global knowledge to maintain (knowing how many smaller and larger elements are there).
This global property is more expensive to maintain (log n insert), but gives more powerful searches (log n search).
Heaps maintain a local property between parent and direct children (parent > children).
The top node of a heap is the big element, which only requires local knowledge to maintain (knowing your parent).
Comparing BST vs Heap vs Hashmap:
BST: can either be either a reasonable:
- unordered set (a structure that determines if an element was previously inserted or not). But hashmap tends to be better due to O(1) amortized insert.
- sorting machine. But heap is generally better at that, which is why heapsort is much more widely known than tree sort
heap: is just a sorting machine. Cannot be an efficient unordered set, because you can only check for the smallest/largest element fast.
hash map: can only be an unordered set, not an efficient sorting machine, because the hashing mixes up any ordering.
Doubly-linked list
A doubly linked list can be seen as subset of the heap where first item has greatest priority, so let's compare them here as well:
- insertion:
- position:
- doubly linked list: the inserted item must be either the first or last, as we only have pointers to those elements.
- binary heap: the inserted item can end up in any position. Less restrictive than linked list.
- time:
- doubly linked list:
O(1)
worst case since we have pointers to the items, and the update is really simple
- binary heap:
O(1)
average, thus worse than linked list. Tradeoff for having more general insertion position.
- search:
O(n)
for both
An use case for this is when the key of the heap is the current timestamp: in that case, new entries will always go to the beginning of the list. So we can even forget the exact timestamp altogether, and just keep the position in the list as the priority.
This can be used to implement an LRU cache. Just like for heap applications like Dijkstra, you will want to keep an additional hashmap from the key to the corresponding node of the list, to find which node to update quickly.
Comparison of different Balanced BST
Although the asymptotic insert and find times for all data structures that are commonly classified as "Balanced BSTs" that I've seen so far is the same, different BBSTs do have different trade-offs. I haven't fully studied this yet, but it would be good to summarize these trade-offs here:
- Red-black tree. Appears to be the most commonly used BBST as of 2019, e.g. it is the one used by the GCC 8.3.0 C++ implementation
- AVL tree. Appears to be a bit more balanced than BST, so it could be better for find latency, at the cost of slightly more expensive finds. Wiki summarizes: "AVL trees are often compared with red–black trees because both support the same set of operations and take [the same] time for the basic operations. For lookup-intensive applications, AVL trees are faster than red–black trees because they are more strictly balanced. Similar to red–black trees, AVL trees are height-balanced. Both are, in general, neither weight-balanced nor mu-balanced for any mu < 1/2; that is, sibling nodes can have hugely differing numbers of descendants."
- WAVL. The original paper mentions advantages of that version in terms of bounds on rebalancing and rotation operations.
See also
Similar question on CS: https://cs.stackexchange.com/questions/27860/whats-the-difference-between-a-binary-search-tree-and-a-binary-heap
How to get full width in body element
You should set body
and html
to position:fixed;
, and then set right:
, left:
, top:
, and bottom:
to 0;
. That way, even if content overflows it will not extend past the limits of the viewport.
For example:
<html>
<body>
<div id="wrapper"></div>
</body>
</html>
CSS:
html, body, {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
}
JS Fiddle Example
Caveat: Using this method, if the user makes their window smaller, content will be cut off.
Writing an mp4 video using python opencv
This worked for me.
self._name = name + '.mp4'
self._cap = VideoCapture(0)
self._fourcc = VideoWriter_fourcc(*'MP4V')
self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))
What is the difference between json.dump() and json.dumps() in python?
There isn't much else to add other than what the docs say. If you want to dump the JSON into a file/socket or whatever, then you should go with dump()
. If you only need it as a string (for printing, parsing or whatever) then use dumps()
(dump string)
As mentioned by Antti Haapala in this answer, there are some minor differences on the ensure_ascii
behaviour. This is mostly due to how the underlying write()
function works, being that it operates on chunks rather than the whole string. Check his answer for more details on that.
json.dump()
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object
If ensure_ascii is False, some chunks written to fp may be unicode instances
json.dumps()
Serialize obj to a JSON formatted str
If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance
Turn a string into a valid filename?
>>> import string
>>> safechars = bytearray(('_-.()' + string.digits + string.ascii_letters).encode())
>>> allchars = bytearray(range(0x100))
>>> deletechars = bytearray(set(allchars) - set(safechars))
>>> filename = u'#ab\xa0c.$%.txt'
>>> safe_filename = filename.encode('ascii', 'ignore').translate(None, deletechars).decode()
>>> safe_filename
'abc..txt'
It doesn't handle empty strings, special filenames ('nul', 'con', etc).
How to get week number in Python?
Generally to get the current week number (starts from Sunday):
from datetime import *
today = datetime.today()
print today.strftime("%U")
Prevent any form of page refresh using jQuery/Javascript
Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.
However, a better solution is to synchronize the two sessions if possible like in google docs.
Change form size at runtime in C#
You can change the height of a form by doing the following where you want to change the size (substitute '10' for your size):
this.Height = 10;
This can be done with the width as well:
this.Width = 10;
How to get video duration, dimension and size in PHP?
getID3 supports video formats. See: http://getid3.sourceforge.net/
Edit: So, in code format, that'd be like:
include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");
Note: You must include the getID3 classes before this will work! See the above link.
Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/
C# 'or' operator?
Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:
if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())
is fundamentally different from
if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())
In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.
WARNING in budgets, maximum exceeded for initial
What is Angular CLI Budgets?
Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size.
Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process.
Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget?
Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
- We might have experimented in our feature and didn’t clean up properly
- Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
- We might import stuff from lazy modules in inappropriate locations
- Our new feature is just really big and doesn’t fit into existing budgets
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app.
To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip?
If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped.
The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
- In your Angular app, run
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.json
- Finally, run
webpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.
ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
ref 2: Optimize Angular bundle size in 4 steps
How to parse JSON string in Typescript
If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.
Validation
I like to express my validation logic as a set of "transforms". I define a Descriptor
as a map of transforms:
type Descriptor<T> = {
[P in keyof T]: (v: any) => T[P];
};
Then I can make a function that will apply these transforms to arbitrary input:
function pick<T>(v: any, d: Descriptor<T>): T {
const ret: any = {};
for (let key in d) {
try {
const val = d[key](v[key]);
if (typeof val !== "undefined") {
ret[key] = val;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`could not pick ${key}: ${msg}`);
}
}
return ret;
}
Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".
In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.
Usage
In your example, I would use this as follows:
const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
name: String,
error: Boolean,
});
Now value
will be typed, since String
and Boolean
are both "transformers" in the sense they take input and return a typed output.
Furthermore, the value
will actually be that type. In other words, if name
were actually 123
, it will be transformed to "123"
so that you have a valid string. This is because we used String
at runtime, a built-in function that accepts arbitrary input and returns a string
.
You can see this working here. Try the following things to convince yourself:
- Hover over the
const value
definition to see that the pop-over shows the correct type.
- Try changing
"Bob"
to 123
and re-run the sample. In your console, you will see that the name has been properly converted to the string "123"
.
Date minus 1 year?
You can use strtotime
:
$date = strtotime('2010-01-01 -1 year');
The strtotime
function returns a unix timestamp, to get a formatted string you can use date
:
echo date('Y-m-d', $date); // echoes '2009-01-01'
phpMyAdmin + CentOS 6.0 - Forbidden
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
How to disable text selection using jQuery?
This can easily be done using JavaScript This is applicable to all Browsers
<script type="text/javascript">
/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
target.style.MozUserSelect="none"
else //All other route (For Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</script>
Call to this function
<script type="text/javascript">
disableSelection(document.body)
</script>
Spring: Why do we autowire the interface and not the implemented class?
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
How do I get the path of the current executed file in Python?
You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.
However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.
some_path/module_locator.py:
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
some_path/main.py:
import module_locator
my_path = module_locator.module_path()
If you have several main scripts in different directories, you may need more than one copy of module_locator.
Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.
Map vs Object in JavaScript
In addition to the other answers, I've found that Maps are more unwieldy and verbose to operate with than objects.
obj[key] += x
// vs.
map.set(map.get(key) + x)
This is important, because shorter code is faster to read, more directly expressive, and better kept in the programmer's head.
Another aspect: because set() returns the map, not the value, it's impossible to chain assignments.
foo = obj[key] = x; // Does what you expect
foo = map.set(key, x) // foo !== x; foo === map
Debugging maps is also more painful. Below, you can't actually see what keys are in the map. You'd have to write code to do that.
Objects can be evaluated by any IDE:
how to add <script>alert('test');</script> inside a text box?
. I usually do it element.value="<script>alert('test');</script>"
.
If sounds like you are generating an inline <script>
element, in which case the </script>
will end the HTML element and cause the script to terminate in the middle of the string.
Escape the /
so that it isn't treated as an end tag by the HTML parser:
element.value = "<script>alert('test');<\/script>"
How to debug JavaScript / jQuery event bindings with Firebug or similar tools?
Using DevTools in the latest Chrome (v29) I find these two tips very helpful for debugging events:
Listing jQuery events of the last selected DOM element
- Inspect an element on the page
- type the following in the console:
$._data($0, "events") //assuming jQuery 1.7+
- It will list all jQuery event objects associated with it, expand the interested event, right-click on the function of the "handler" property and choose "Show function definition". It will open the file containing the specified function.
Utilizing the monitorEvents() command
Fill an array with random numbers
I tried to make this as simple as possible in Java. This makes an integer array of 100 variables and fill it with integers between 0 and 10 using only three lines of code. You can easily change the bounds of the random number too!
int RandNumbers[]=new int[100];
for (int i=0;i<RandNumbers.length;i++)
RandNumbers[i]=ThreadLocalRandom.current().nextInt(0,10);
Space between Column's children in Flutter
you can use Wrap()
widget instead Column()
to add space between child widgets.And use spacing property to give equal spacing between children
Wrap(
spacing: 20, // to apply margin in the main axis of the wrap
runSpacing: 20, // to apply margin in the cross axis of the wrap
children: <Widget>[
Text('child 1'),
Text('child 2')
]
)
can't load package: package .: no buildable Go source files
I had this exact error code and after checking my repository discovered that there were no go files but actually just more directories. So it was more of a red herring than an error for me.
I would recommend doing
go env
and making sure that everything is as it should be, check your environment variables in your OS and check to make sure your shell (bash or w/e ) isn't compromising it via something like a .bash_profile or .bashrc file. good luck.
How to construct a relative path in Java from two absolute paths (or URLs)?
I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:
public static String getRelativePath(String fromPath, String toPath) {
// This weirdness is because a separator of '/' messes with String.split()
String regexCharacter = File.separator;
if (File.separatorChar == '\\') {
regexCharacter = "\\\\";
}
String[] fromSplit = fromPath.split(regexCharacter);
String[] toSplit = toPath.split(regexCharacter);
// Find the common path
int common = 0;
while (fromSplit[common].equals(toSplit[common])) {
common++;
}
StringBuffer result = new StringBuffer(".");
// Work your way up the FROM path to common ground
for (int i = common; i < fromSplit.length; i++) {
result.append(File.separatorChar).append("..");
}
// Work your way down the TO path
for (int i = common; i < toSplit.length; i++) {
result.append(File.separatorChar).append(toSplit[i]);
}
return result.toString();
}
check for null date in CASE statement, where have I gone wrong?
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
https://msdn.microsoft.com/en-GB/library/ms188048.aspx
How to find numbers from a string?
Alternative via Byte
Array
If you assign a string to a Byte
array you typically get the number equivalents of each character in pairs of the array elements. Use a loop for numeric check via the Like
operator and return the joined array as string:
Function Nums(s$)
Dim by() As Byte, i&, ii&
by = s: ReDim tmp(UBound(by)) ' assign string to byte array; prepare temp array
For i = 0 To UBound(by) - 1 Step 2 ' check num value in byte array (0, 2, 4 ... n-1)
If Chr(by(i)) Like "#" Then tmp(ii) = Chr(by(i)): ii = ii + 1
Next i
Nums = Trim(Join(tmp, vbNullString)) ' return string with numbers only
End Function
Example call
Sub testByteApproach()
Dim s$: s = "a12bx99y /\:3,14159" ' [1] define original string
Debug.Print s & " => " & Nums(s) ' [2] display original string and result
End Sub
would display the original string and the result string in the immediate window:
a12bx99y /\:3,14159 => 1299314159
how to kill the tty in unix
The simplest way is with the pkill
command.
In your case:
pkill -9 -t pts/6
pkill -9 -t pts/9
pkill -9 -t pts/10
Regarding tty sessions, the commands below are always useful:
w
- shows active terminal sessions
tty
- shows your current terminal session (so you won't close it by accident)
last | grep logged
- shows currently logged users
Sometimes we want to close all sessions of an idle user (ie. when connections are lost abruptly).
pkill -u username
- kills all sessions of 'username' user.
And sometimes when we want to kill all our own sessions except the current one, so I made a script for it. There are some cosmetics and some interactivity (to avoid accidental running on the script).
#!/bin/bash
MYUSER=`whoami`
MYSESSION=`tty | cut -d"/" -f3-`
OTHERSESSIONS=`w $MYUSER | grep "^$MYUSER" | grep -v "$MYSESSION" | cut -d" " -f2`
printf "\e[33mCurrent session\e[0m: $MYUSER[$MYSESSION]\n"
if [[ ! -z $OTHERSESSIONS ]]; then
printf "\e[33mOther sessions:\e[0m\n"
w $MYUSER | egrep "LOGIN@|^$MYUSER" | grep -v "$MYSESSION" | column -t
echo ----------
read -p "Do you want to force close all your other sessions? [Y]Yes/[N]No: " answer
answer=`echo $answer | tr A-Z a-z`
confirm=("y" "yes")
if [[ "${confirm[@]}" =~ "$answer" ]]; then
for SESSION in $OTHERSESSIONS
do
pkill -9 -t $SESSION
echo Session $SESSION closed.
done
fi
else
echo "There are no other sessions for the user '$MYUSER'".
fi
Calculate time difference in Windows batch file
Here is my attempt to measure time difference in batch.
It respects the regional format of %TIME% without taking any assumptions on type of characters for time and decimal separators.
The code is commented but I will also describe it here.
It is flexible so it can also be used to normalize non-standard time values as well
The main function :timediff
:: timediff
:: Input and output format is the same format as %TIME%
:: If EndTime is less than StartTime then:
:: EndTime will be treated as a time in the next day
:: in that case, function measures time difference between a maximum distance of 24 hours minus 1 centisecond
:: time elements can have values greater than their standard maximum value ex: 12:247:853.5214
:: provided than the total represented time does not exceed 24*360000 centiseconds
:: otherwise the result will not be meaningful.
:: If EndTime is greater than or equals to StartTime then:
:: No formal limitation applies to the value of elements,
:: except that total represented time can not exceed 2147483647 centiseconds.
:timediff <outDiff> <inStartTime> <inEndTime>
(
setlocal EnableDelayedExpansion
set "Input=!%~2! !%~3!"
for /F "tokens=1,3 delims=0123456789 " %%A in ("!Input!") do set "time.delims=%%A%%B "
)
for /F "tokens=1-8 delims=%time.delims%" %%a in ("%Input%") do (
for %%A in ("@h1=%%a" "@m1=%%b" "@s1=%%c" "@c1=%%d" "@h2=%%e" "@m2=%%f" "@s2=%%g" "@c2=%%h") do (
for /F "tokens=1,2 delims==" %%A in ("%%~A") do (
for /F "tokens=* delims=0" %%B in ("%%B") do set "%%A=%%B"
)
)
set /a "@d=(@h2-@h1)*360000+(@m2-@m1)*6000+(@s2-@s1)*100+(@c2-@c1), @sign=(@d>>31)&1, @d+=(@sign*24*360000), @h=(@d/360000), @d%%=360000, @m=@d/6000, @d%%=6000, @s=@d/100, @c=@d%%100"
)
(
if %@h% LEQ 9 set "@h=0%@h%"
if %@m% LEQ 9 set "@m=0%@m%"
if %@s% LEQ 9 set "@s=0%@s%"
if %@c% LEQ 9 set "@c=0%@c%"
)
(
endlocal
set "%~1=%@h%%time.delims:~0,1%%@m%%time.delims:~0,1%%@s%%time.delims:~1,1%%@c%"
exit /b
)
Example:
@echo off
setlocal EnableExtensions
set "TIME="
set "Start=%TIME%"
REM Do some stuff here...
set "End=%TIME%"
call :timediff Elapsed Start End
echo Elapsed Time: %Elapsed%
pause
exit /b
:: put the :timediff function here
Explanation of the :timediff function:
function prototype :timediff <outDiff> <inStartTime> <inEndTime>
Input and output format is the same format as %TIME%
It takes 3 parameters from left to right:
Param1: Name of the environment variable to save the result to.
Param2: Name of the environment variable to be passed to the function containing StartTime string
Param3: Name of the environment variable to be passed to the function containing EndTime string
If EndTime is less than StartTime then:
EndTime will be treated as a time in the next day
in that case, the function measures time difference between a maximum distance of 24 hours minus 1 centisecond
time elements can have values greater than their standard maximum value ex: 12:247:853.5214
provided than the total represented time does not exceed 24*360000 centiseconds or (24:00:00.00) otherwise the result will not be meaningful.
If EndTime is greater than or equals to StartTime then:
No formal limitation applies to the value of elements,
except that total represented time can not exceed 2147483647 centiseconds.
More examples with literal and non-standard time values
Literal example with EndTime less than StartTime:
@echo off
setlocal EnableExtensions
set "start=23:57:33,12"
set "end=00:02:19,41"
call :timediff dif start end
echo Start Time: %start%
echo End Time: %end%
echo,
echo Difference: %dif%
echo,
pause
exit /b
:: put the :timediff function here
Start Time: 23:57:33,12
End Time: 00:02:19,41
Difference: 00:04:46,29
Normalize non-standard time:
@echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=27:2457:433.85935"
call :timediff normalized start end
echo,
echo %end% is equivalent to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
27:2457:433.85935 is equivalent to 68:18:32.35
@echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=00:00:00.2147483647"
call :timediff normalized start end
echo,
echo 2147483647 centiseconds equals to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
2147483647 centiseconds equals to 5965:13:56.47
Python OpenCV2 (cv2) wrapper to get image size?
I'm afraid there is no "better" way to get this size, however it's not that much pain.
Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size
:
import numpy as np
import cv2
# ...
def cv_size(img):
return tuple(img.shape[1::-1])
If you're on a terminal / ipython, you can also express it with a lambda:
>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)
Writing functions with def
is not fun while working interactively.
Edit
Originally I thought that using [:2]
was OK, but the numpy shape is (height, width[, depth])
, and we need (width, height)
, as e.g. cv2.resize
expects, so - we must use [1::-1]
. Even less memorable than [:2]
. And who remembers reverse slicing anyway?
how to use jQuery ajax calls with node.js
Use something like the following on the server side:
http.createServer(function (request, response) {
if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
// handle async request
var u = url.parse(request.url, true); //not needed
response.writeHead(200, {'content-type':'text/json'})
response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
} else {
// handle sync request (by server index.html)
if (request.url == '/') {
response.writeHead(200, {'content-type': 'text/html'})
util.pump(fs.createReadStream('index.html'), response)
}
else
{
// 404 error
}
}
}).listen(31337)
How to run two jQuery animations simultaneously?
While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.
To insure the animations are indeed running at the same time use:
$(function() {
$('#first').animate({..., queue: 'my-animation'});
$('#second').animate({..., queue: 'my-animation'}).dequeue('my-animation');
});
Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.
Cheers,
Anthony
Disable Input fields in reactive form
I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).
In my case I had to reset my form before reloading:
this.form = undefined;
this.router.navigate([path]);
Stopping Docker containers by image name - Ubuntu
This code will stop all containers with the image centos:6. I couldn't find an easier solution for that.
docker ps | grep centos:6 | awk '{print $1}' | xargs docker stop
Or even shorter:
docker stop $(docker ps -a | grep centos:6 | awk '{print $1}')
How do I go about adding an image into a java project with eclipse?
If you still have problems with Eclipse finding your files, you might try the following:
- Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
Getting reference to child component in parent component
You may actually go with ViewChild API
...
parent.ts
<button (click)="clicked()">click</button>
export class App {
@ViewChild(Child) vc:Child;
constructor() {
this.name = 'Angular2'
}
func(e) {
console.log(e)
}
clicked(){
this.vc.getName();
}
}
child.ts
export class Child implements OnInit{
onInitialized = new EventEmitter<Child>();
...
...
getName()
{
console.log('called by vc')
console.log(this.name);
}
}
Comparing two branches in Git?
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
Convert Enumeration to a Set/List
There is a simple example of convert enumeration to list. for this i used Collections.list(enum)
method.
public class EnumerationToList {
public static void main(String[] args) {
Vector<String> vt = new Vector<String>();
vt.add("java");
vt.add("php");
vt.add("array");
vt.add("string");
vt.add("c");
Enumeration<String> enm = vt.elements();
List<String> ll = Collections.list(enm);
System.out.println("List elements: " + ll);
}
}
Reference : How to convert enumeration to list
Fastest way to count number of occurrences in a Python list
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
Error: «Could not load type MvcApplication»
In my case issue was I renamed class Global to MvcApplication. When renaming it has to be changed on all places, otherwise app is looking for Global class in given namespace.
NoClassDefFoundError on Maven dependency
By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.
You could manually specify the libraries on the classpath with the -cp
parameter, but that quickly becomes tiresome.
A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package
.
To simply bundle all required libraries, add the following to your POM:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
Once this is done, you can rerun the commands you used above:
$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App
If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.
how to get the attribute value of an xml node using java
I'm happy that this snippet works fine:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("config.xml"));
NodeList nodeList = document.getElementsByTagName("source");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());
}
Android: I lost my android key store, what should I do?
If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.
If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:
/Applications/eclipse/Eclipse.app/Contents/MacOS/
then your keystore file without any extension. You need root privilege to access this path (file).
How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?
As an alternative to writing to a file, how about writing to a table? Instead of calling DBMS_OUTPUT.PUT_LINE you could call your own DEBUG.OUTPUT procedure something like:
procedure output (p_text varchar2) is
pragma autonomous_transaction;
begin
if g_debugging then
insert into debug_messages (username, datetime, text)
values (user, sysdate, p_text);
commit;
end if;
end;
The use of an autonomous transaction allows you to retain debug messages produced from transactions that get rolled back (e.g. after an exception is raised), as would happen if you were using a file.
The g_debugging boolean variable is a package variable that can be defaulted to false and set to true when debug output is required.
Of course, you need to manage that table so that it doesn't grow forever! One way would be a job that runs nightly/weekly and deletes any debug messages that are "old".
Javascript date.getYear() returns 111 in 2011?
From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear()
is the way to go. If you're really wanting to use getYear()
add 1900 to it.
var now = new Date(),
year = now.getYear() + 1900;
JS regex: replace all digits in string
The /g
modifier is used to perform a global match (find all matches rather than stopping after the first)
You can use \d
for digit, as it is shorter than [0-9]
.
JavaScript:
var s = "04.07.2012";
echo(s.replace(/\d/g, "X"));
Output:
XX.XX.XXXX