How to get coordinates of an svg element?
The element.getBoundingClientRect()
method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.
See this question and answer.
While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.
Subtract minute from DateTime in SQL Server 2005
I spent a while trying to do the same thing, trying to subtract the hours:minutes
from datetime
- here's how I did it:
convert( varchar, cast((RouteMileage / @average_speed) as integer))+ ':' + convert( varchar, cast((((RouteMileage / @average_speed) - cast((RouteMileage / @average_speed) as integer)) * 60) as integer)) As TravelTime,
dateadd( n, -60 * CAST( (RouteMileage / @average_speed) AS DECIMAL(7,2)), @entry_date) As DepartureTime
OUTPUT:
DeliveryDate TravelTime DepartureTime
2012-06-02 12:00:00.000 25:49 2012-06-01 10:11:00.000
Is there a keyboard shortcut (hotkey) to open Terminal in macOS?
As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in MacOS 10.13.1 (High Sierra):
Option 1: Go to System Preferences | Keyboard | Shortcut | Services
.
Under Files and Folders
section, enable New Terminal at Folder
and/or New Terminal Tab at Folder
and assign a shortcut key to it.
Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop
Notes:
- If the shortcut doesn't work, it might be in conflict with another
key binding (and the OS wouldn't warn you), try something else, e.g.
if ??T doesn't work, try ??T.
- Don't spell-correct
MacOS
, that's not necessary.
ActionBarActivity cannot resolve a symbol
Follow the steps mentioned for using support ActionBar in Android Studio(0.4.2) :
Download the Android Support Repository from Android SDK Manager, SDK Manager icon will be available on Android Studio tool bar (or Tools -> Android -> SDK Manager
).
After download you will find your Support repository here
$SDK_DIR\extras\android\m2repository\com\android\support\appcompat-v7
Open your main module's build.gradle file and add following dependency for using action bar in lower API level
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Sync your project with gradle using the tiny Gradle icon available in toolbar (or Tools -> Android -> Sync Project With Gradle Files
).
There is some issue going on with Android Studio 0.4.2 so check this as well if you face any issue while importing classes in code.
Import Google Play Services library in Android Studio
If Required follow the steps as well :
- Exit Android Studio
- Delete all the .iml files and files inside .idea folder from your
project
- Relaunch Android Studio and wait till the project synced completely
with gradle. If it shows an error in Event Log with import option click on Import Project.
This is bug in Android Studio 0.4.2 and fixed for Android Studio 0.4.3 release.
open a url on click of ok button in android
You can use the below method, which will take your target URL as the only input (Don't forget http://)
void GoToURL(String url){
Uri uri = Uri.parse(url);
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
Getting time elapsed in Objective-C
For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.
Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476
In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime
!
I also benchmarked the mach_timebase_info
call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.
#include <mach/mach.h>
#include <mach/mach_time.h>
uint64_t getTickCount(void)
{
mach_timebase_info_data_t sTimebaseInfo;
uint64_t machTime = mach_absolute_time();
// Convert to milliseconds
mach_timebase_info(&sTimebaseInfo);
machTime *= sTimebaseInfo.numer;
machTime /= sTimebaseInfo.denom;
machTime /= 1000000; // convert from nanoseconds to milliseconds
return machTime;
}
Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3
.
The solution using CACurrentMediaTime()
is quite trivial:
uint64_t getTickCount(void)
{
double ret = CACurrentMediaTime();
return ret * 1000;
}
jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.
What I finally end up doing was replacing the single quote '
with it code '
using a regex after the stringify() method call the following way:
var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "'");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.
Removing specific rows from a dataframe
Here's a solution to your problem using dplyr's filter
function.
Although you can pass your data frame as the first argument to any dplyr function, I've used its %>%
operator, which pipes your data frame to one or more dplyr functions (just filter in this case).
Once you are somewhat familiar with dplyr, the cheat sheet is very handy.
> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
sub day
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 2 3
8 2 4
9 3 1
10 3 2
11 3 3
12 3 4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
sub day
1 1 1
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
What is the "Temporary ASP.NET Files" folder for?
These are what's known as Shadow Copy Folders.
Simplistically....and I really mean it:
When ASP.NET runs your app for the
first time, it copies any assemblies
found in the /bin folder, copies any
source code files (found for example
in the App_Code folder) and parses
your aspx, ascx files to c# source
files. ASP.NET then builds/compiles
all this code into a runnable
application.
One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.
ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.
Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.
This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation
How to format a numeric column as phone number in SQL
I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:
CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)
IF (LEN(@PhoneNo) <> 10)
SET @Formatted = @PhoneNo
ELSE
SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)
RETURN @Formatted
END
GO
Which you can then use like this:
SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable
It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.
EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)
Using margin:auto to vertically-align a div
I know the question is from 2012, but I found the easiest way ever, and I wanted to share.
HTML:
<div id="parent">
<div id="child">Content here</div>
</div>
and CSS:
#parent{
height: 100%;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
Batch file FOR /f tokens
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
Open file in a relative location in Python
I created an account just so I could clarify a discrepancy I think I found in Russ's original response.
For reference, his original answer was:
import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
This is a great answer because it is trying to dynamically creates an absolute system path to the desired file.
Cory Mawhorter noticed that __file__
is a relative path (it is as well on my system) and suggested using os.path.abspath(__file__)
. os.path.abspath
, however, returns the absolute path of your current script (i.e. /path/to/dir/foobar.py
)
To use this method (and how I eventually got it working) you have to remove the script name from the end of the path:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
The resulting abs_file_path (in this example) becomes: /path/to/dir/2091/data.txt
Preloading images with jQuery
$.fn.preload = function (callback) {
var length = this.length;
var iterator = 0;
return this.each(function () {
var self = this;
var tmp = new Image();
if (callback) tmp.onload = function () {
callback.call(self, 100 * ++iterator / length, iterator === length);
};
tmp.src = this.src;
});
};
The usage is quite simple:
$('img').preload(function(perc, done) {
console.log(this, perc, done);
});
http://jsfiddle.net/yckart/ACbTK/
Python Variable Declaration
There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic"
. Variables in Python can hold values of any type, and you can't restrict that.
Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__
method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.
So for example:
class Thing(object):
def __init__(self, magic):
self.magic = magic
Easy. Now instances of this class have a magic
attribute:
thingo = Thing("More magic")
# thingo.magic is now "More magic"
Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:
class Thing(object):
magic = "Magic"
def __init__(self):
pass
Now try:
thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1
Or:
class Thing(object):
magic = ["More", "magic"]
def __init__(self):
pass
thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]
This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.
The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__
method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.
strcpy() error in Visual studio 2012
I had to use strcpy_s and it worked.
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
struct student
{
char name[30];
int age;
};
int main()
{
struct student s1;
char myname[30] = "John";
strcpy_s (s1.name, strlen(myname) + 1 ,myname );
s1.age = 21;
cout << " Name: " << s1.name << " age: " << s1.age << endl;
return 0;
}
jQuery find parent form
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
java.lang.IllegalStateException: The specified child already has a parent
I had this problem and couldn't solve it in Java code. The problem was with my xml.
I was trying to add a textView to a container, but had wrapped the textView inside a LinearLayout.
This was the original xml file:
_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:orientation="vertical"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent">_x000D_
_x000D_
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>_x000D_
_x000D_
</LinearLayout>
_x000D_
_x000D_
_x000D_
Now with the LinearLayout removed:
_x000D_
_x000D_
<TextView xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
android:id="@android:id/text1"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceListItemSmall"_x000D_
android:gravity="center_vertical"_x000D_
android:paddingLeft="16dp"_x000D_
android:paddingRight="16dp"_x000D_
android:textColor="#fff"_x000D_
android:background="?android:attr/activatedBackgroundIndicator"_x000D_
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
_x000D_
_x000D_
_x000D_
This didn't seem like much to me but it did the trick, and I didn't change my Java code at all. It was all in the xml.
Docker official registry (Docker Hub) URL
You're able to get the current registry-url using docker info
:
...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...
That's also the url you may use to run your self hosted-registry:
docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2
Grep & use it right away:
$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/
Order by in Inner Join
You have to sort it if you want the data to come back a certain way. When you say you are expecting "Mohit
" to be the first row, I am assuming you say that because "Mohit
" is the first row in the [One]
table. However, when SQL Server joins tables, it doesn't necessarily join in the order you think.
If you want the first row from [One]
to be returned, then try sorting by [One].[ID]
. Alternatively, you can order by
any other column.
Reading data from DataGridView in C#
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Conditional step/stage in Jenkins pipeline
Doing the same in declarative pipeline syntax, below are few examples:
stage('master-branch-stuff') {
when {
branch 'master'
}
steps {
echo 'run this stage - ony if the branch = master branch'
}
}
stage('feature-branch-stuff') {
when {
branch 'feature/*'
}
steps {
echo 'run this stage - only if the branch name started with feature/'
}
}
stage('expression-branch') {
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
steps {
echo 'run this stage - when branch is not equal to master'
}
}
stage('env-specific-stuff') {
when {
environment name: 'NAME', value: 'this'
}
steps {
echo 'run this stage - only if the env name and value matches'
}
}
More effective ways coming up -
https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at -
https://jenkins.io/doc/book/pipeline/syntax/#when
The directive beforeAgent true
can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:
when { beforeAgent true; expression { return isStageConfigured(config) } }
Release post and docs
UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative
equals - Compares two values - strings, variables, numbers, booleans -
and returns true if they’re equal. I’m honestly not sure how we missed
adding this earlier! You can do "not equals" comparisons using the not
{ equals ... } combination too.
changeRequest - In its simplest form, this will return true if this
Pipeline is building a change request, such as a GitHub pull request.
You can also do more detailed checks against the change request,
allowing you to ask "is this a change request against the master
branch?" and much more.
buildingTag - A simple condition that just checks if the Pipeline is
running against a tag in SCM, rather than a branch or a specific
commit reference.
tag - A more detailed equivalent of buildingTag, allowing you to check
against the tag name itself.
How to override maven property in command line?
See Introduction to the POM
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
LISTAGG in Oracle to return distinct values
Very simple - use in your query a sub-query with a select distinct:
SELECT question_id,
LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM
(SELECT distinct question_id, element_id
FROM YOUR_TABLE)
GROUP BY question_id;
Wait for a void async method
Best practice is to mark function async void
only if it is fire and forget method, if you want to await on, you should mark it as async Task
.
In case if you still want to await, then wrap it like so await Task.Run(() => blah())
laravel 5.4 upload image
public function store()
{
$this->validate(request(), [
'title' => 'required',
'slug' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,gif'
]);
$fileName = null;
if (request()->hasFile('file')) {
$file = request()->file('file');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$file->move('./uploads/categories/', $fileName);
}
Category::create([
'title' => request()->get('title'),
'slug' => str_slug(request()->get('slug')),
'description' => request()->get('description'),
'category_img' => $fileName,
'category_status' => 'DEACTIVE'
]);
return redirect()->to('/admin/category');
}
Java2D: Increase the line width
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
Excel VBA Open a Folder
If you want to open a windows file explorer, you should call explorer.exe
Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)
Equivalent syxntax
Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus
Best practice multi language website
I had the same probem a while ago, before starting using Symfony framework.
Just use a function __() which has arameters pageId (or objectId, objectTable described in #2), target language and an optional parameter of fallback (default) language. The default language could be set in some global config in order to have an easier way to change it later.
For storing the content in database i used following structure: (pageId, language, content, variables).
pageId would be a FK to your page you want to translate. if you have other objects, like news, galleries or whatever, just split it into 2 fields objectId, objectTable.
language - obviously it would store the ISO language string EN_en, LT_lt, EN_us etc.
content - the text you want to translate together with the wildcards for variable replacing. Example "Hello mr. %%name%%. Your account balance is %%balance%%."
variables - the json encoded variables. PHP provides functions to quickly parse these. Example "name: Laurynas, balance: 15.23".
you mentioned also slug field. you could freely add it to this table just to have a quick way to search for it.
Your database calls must be reduced to minimum with caching the translations. It must be stored in PHP array, because it is the fastest structure in PHP language. How you will make this caching is up to you. From my experience you should have a folder for each language supported and an array for each pageId. The cache should be rebuilt after you update the translation. ONLY the changed array should be regenerated.
i think i answered that in #2
your idea is perfectly logical. this one is pretty simple and i think will not make you any problems.
URLs should be translated using the stored slugs in the translation table.
Final words
it is always good to research the best practices, but do not reinvent the wheel. just take and use the components from well known frameworks and use them.
take a look at Symfony translation component. It could be a good code base for you.
How to get records randomly from the oracle database?
Here's how to pick a random sample out of each group:
SELECT GROUPING_COLUMN,
MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE)
AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;
I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.
Update a dataframe in pandas while iterating row by row
A method you can use is itertuples()
, it iterates over DataFrame rows as namedtuples, with index value as first element of the tuple. And it is much much faster compared with iterrows()
. For itertuples()
, each row
contains its Index
in the DataFrame, and you can use loc
to set the value.
for row in df.itertuples():
if <something>:
df.at[row.Index, 'ifor'] = x
else:
df.at[row.Index, 'ifor'] = x
df.loc[row.Index, 'ifor'] = x
Under most cases, itertuples()
is faster than iat
or at
.
Thanks @SantiStSupery, using .at
is much faster than loc
.
How to combine two vectors into a data frame
Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.
myfunc <- function(a, b, names = NULL) {
setNames(data.frame(c(rep(deparse(substitute(a)), length(a)),
rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}
An example:
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
myfunc(x, y, c(x_name, y_name))
cond rating
1 x 1
2 x 2
3 x 3
4 y 100
5 y 200
6 y 300
Failure during conversion to COFF: file invalid or corrupt
I had this issue after installing dotnetframework4.5.
Open path below:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" ( in 64 bits machine)
or
"C:\Program Files\Microsoft Visual Studio 10.0\VC\bin" (in 32 bits machine)
In this path find file cvtres.exe and rename it to cvtres1.exe then compile your project again.
Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
I came across the same problem using a Wordpress page and plugin.
This didn't work for the iframe plugin
[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730#?platform=iphone"]
but this does:
[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730" width="100%" height="480" ]
As you see,
I just left off the #?platform=iphone
part in the end.
Regular expression matching a multiline block of text
My preference.
lineIter= iter(aFile)
for line in lineIter:
if line.startswith( ">" ):
someVaryingText= line
break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
if len(line.strip()) == 0:
break
acids.append( line )
At this point you have someVaryingText as a string, and the acids as a list of strings.
You can do "".join( acids )
to make a single string.
I find this less frustrating (and more flexible) than multiline regexes.
Python 2.6: Class inside a Class?
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
Better way to find last used row
I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.
Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.
Dim lWorksheetRecordCountScaler as Long
Dim lWorksheetRecordCount as Long
Const sDataColumn = "A" '<----Set to column that has data in all rows (Code, ID, etc.)
'Count the data records
lWorksheetRecordCountScaler = 100000 'Begin by counting in 100,000-record bites
lWorksheetRecordCount = lWorksheetRecordCountScaler
While lWorksheetRecordCountScaler >= 1
While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
Wend
'To the beginning of the previous bite, count 1/10th of the scale from there
lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10
Wend
lWorksheetRecordCount = lWorksheetRecordCount + 1 'Final answer
Isn't the size of character in Java 2 bytes?
Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.
Run a single migration file
Assuming fairly recent version of Rails you can always run:
rake db:migrate:up VERSION=20090408054532
Where version is the timestamp in the filename of the migration.
Edit: At some point over the last 8 years (I'm not sure what version) Rails added checks that prevent this from running if it has already been run. This is indicated by an entry in the schema_migrations
table. To re-run it, simply execute rake db:migrate:redo VERSION=20090408054532
instead.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
What is an OS kernel ? How does it differ from an operating system?
The technical definition of an operating system is "a platform that consists of specific set of libraries and infrastructure for applications to be built upon and interact with each other". A kernel is an operating system in that sense.
The end-user definition is usually something around "a software package that provides a desktop, shortcuts to applications, a web browser and a media player". A kernel doesn't match that definition.
So for an end-user a Linux distribution (say Ubuntu) is an Operating System while for a programmer the Linux kernel itself is a perfectly valid OS depending on what you're trying to achieve. For instance embedded systems are mostly just kernel with very small number of specialized processes running on top of them. In that case the kernel itself becomes the OS itself.
I think you can draw the line at what the majority of the applications running on top of that OS do require. If most of them require only kernel, the kernel is the OS, if most of them require X Window System running, then your OS becomes X + kernel.
In plain English, what does "git reset" do?
In general, git reset
's function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:
- A - B - C (HEAD, master)
and you realize you want master to point to B, not C, you will use git reset B
to move it there:
- A - B (HEAD, master) # - C is still here, but there's no branch pointing to it anymore
Digression: This is different from a checkout. If you'd run git checkout B
, you'd get this:
- A - B (HEAD) - C (master)
You've ended up in a detached HEAD state. HEAD
, work tree, index all match B
, but the master branch was left behind at C
. If you make a new commit D
at this point, you'll get this, which is probably not what you want:
- A - B - C (master)
\
D (HEAD)
Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.
Use cases
I cover many of the main use cases for git reset
within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit.
Things to be careful of
--hard
can cause you to really lose work. It modifies your work tree.
git reset [options] commit
can cause you to (sort of) lose commits. In the toy example above, we lost commit C
. It's still in the repo, and you can find it by looking at git reflog show HEAD
or git reflog show master
, but it's not actually accessible from any branch anymore.
Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (git checkout C; git branch <new branch name>
).
Arguments
Paraphrasing the man page, most common usage is of the form git reset [<commit>] [paths...]
, which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.
For example, git reset other-branch path/to/foo
resets everything in path/to/foo to its state in other-branch, git reset -- .
resets the current directory to its state in HEAD, and a simple git reset
resets everything to its state in HEAD.
The main work tree and index options
There are four main options to control what happens to your work tree and index during the reset.
Remember, the index is git's "staging area" - it's where things go when you say git add
in preparation to commit.
--hard
makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: git reset --hard
means git reset --hard HEAD
, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard
.
--mixed
is the default, i.e. git reset
means git reset --mixed
. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (git add ...
).
--soft
doesn't touch the index or work tree. All your files are intact as with --mixed
, but all the changes show up as changes to be committed
with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.
--merge
was added recently, and is intended to help you abort a failed merge. This is necessary because git merge
will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. git reset --merge
resets the index (like --mixed
- all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as git reset --merge
(meaning git reset --merge HEAD
) because you only want to reset away the merge, not actually move the branch. (HEAD
hasn't been updated yet, since the merge failed)
To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use git reset --merge
. It brings C and D back to how they were in HEAD
, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.
Want to know more?
I do think man git reset
is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)
Strange notation
The "strange notation" (HEAD^
and HEAD~1
) you mention is simply a shorthand for specifying commits, without having to use a hash name like 3ebe3f6
. It's fully documented in the "specifying revisions" section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things:
HEAD~
is short for HEAD~1
and means the commit's first parent. HEAD~2
means the commit's first parent's first parent. Think of HEAD~n
as "n commits before HEAD" or "the nth generation ancestor of HEAD".
HEAD^
(or HEAD^1
) also means the commit's first parent. HEAD^2
means the commit's second parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).
- The
^
and ~
operators can be strung together, as in HEAD~3^2
, the second parent of the third-generation ancestor of HEAD
, HEAD^^2
, the second parent of the first parent of HEAD
, or even HEAD^^^
, which is equivalent to HEAD~3
.
When to throw an exception?
I agree with japollock way up there--throw an acception when you are uncertain about the outcome of an operation. Calls to APIs, accessing filesystems, database calls, etc. Anytime you are moving past the "boundaries" of your programming languages.
I'd like to add, feel free to throw a standard exception. Unless you are going to do something "different" (ignore, email, log, show that twitter whale picture thingy, etc), then don't bother with custom exceptions.
How to get row count using ResultSet in Java?
Most drivers support forward only resultset - so method like last, beforeFirst etc are not supported.
The first approach is suitable if you are also getting the data in the same loop - otherwise the resultSet has already been iterated and can not be used again.
In most cases the requirement is to get the number of rows a query would return without fetching the rows. Iterating through the result set to find the row count is almost same as processing the data. It is better to do another count(*) query instead.
how does unix handle full path name with space and arguments?
I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like
>scriptName.sh arg1 arg2
And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as "$arg1" instead of $arg1
Here are the details
Is it possible to see more than 65536 rows in Excel 2007?
I am not 100% sure where all of the other suggestions are trying to go, but the issue is basically related to the extension that you have on the file. If you save the file as a Excel 97/2003 workbook it will not allow you to see all million rows. Create a new sheet and save it as a workbook and you will see all million. Note: the extension will be .xlsx
How to set Google Chrome in WebDriver
Mac OS:
You have to install ChromeDriver first:
brew cask install chromedriver
It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.
Visualizing branch topology in Git
I like, with git log
, to do:
git log --graph --oneline --branches
(also with --all, for viewing remote branches as well)
Works with recent Git releases: introduced since 1.6.3 (Thu, 7 May 2009)
"--pretty=<style>
" option to the log family of commands can now be spelled as "--format=<style>
".
In addition, --format=%formatstring
is a short-hand for --pretty=tformat:%formatstring
.
"--oneline
" is a synonym for "--pretty=oneline --abbrev-commit
".
PS D:\git\tests\finalRepo> git log --graph --oneline --branches --all
* 4919b68 a second bug10 fix
* 3469e13 a first bug10 fix
* dbcc7aa a first legacy evolution
| * 55aac85 another main evol
| | * 47e6ee1 a second bug10 fix
| | * 8183707 a first bug10 fix
| |/
| * e727105 a second evol for 2.0
| * 473d44e a main evol
|/
* b68c1f5 first evol, for making 1.0
You can also limit the span of the log display (number of commits):
PS D:\git\tests\finalRepo> git log --graph --oneline --branches --all -5
* 4919b68 a second bug10 fix
* 3469e13 a first bug10 fix
* dbcc7aa a first legacy evolution
| * 55aac85 another main evol
| | * 47e6ee1 a second bug10 fix
(show only the last 5 commits)
What I do not like about the current selected solution is:
git log --graph
It displayed way too much info (when I want only to look at a quick summary):
PS D:\git\tests\finalRepo> git log --graph
* commit 4919b681db93df82ead7ba6190eca6a49a9d82e7
| Author: VonC <[email protected]>
| Date: Sat Nov 14 13:42:20 2009 +0100
|
| a second bug10 fix
|
* commit 3469e13f8d0fadeac5fcb6f388aca69497fd08a9
| Author: VonC <[email protected]>
| Date: Sat Nov 14 13:41:50 2009 +0100
|
| a first bug10 fix
|
gitk
is great, but forces me to leave the shell session for another window, whereas displaying the last n commits quickly is often enough.
How to check currently internet connection is available or not in android
try using ConnectivityManager
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false
Also Add permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
What is Common Gateway Interface (CGI)?
A CGI is a program (or a Web API) you write, and save it on the Web Server site. CGI is a file.
This file sits and waits on the Web Server. When the client browser sends a request to the Web Server to execute your CGI file, the Web Server runs your CGI file on the server site. The inputs for this CGI program, if any, are from the client browser. The outputs of this CGI program are sent to the browser.
What language you use to write a CGI program? Other posts already mention c,java, php, perl, etc.
What is 'Currying'?
In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.
So how do you deal with something you'd naturally express as, say, f(x,y)
? Well, you take that as equivalent to f(x)(y)
-- f(x)
, call it g
, is a function, and you apply that function to y
. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).
As usual, wikipedia has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.
Configuring Git over SSH to login once
I think there are two different things here. The first one is that normal SSH authentication requires the user to put the account's password (where the account password will be authenticated against different methods, depending on the sshd configuration).
You can avoid putting that password using certificates. With certificates you still have to put a password, but this time is the password of your private key (that's independent of the account's password).
To do this you can follow the instructions pointed out by steveth45:
With Public Key Authentication.
If you want to avoid putting the certificate's password every time then you can use ssh-agent, as pointed out by DigitalRoss
The exact way you do this depends on Unix vs Windows, but essentially you need to run ssh-agent in the background when you log in, and then the first time you log in, run ssh-add to give the agent your passphrase. All ssh-family commands will then consult the agent and automatically pick up your passphrase.
Start here: man ssh-agent.
The only problem of ssh-agent is that, on *nix at least, you have to put the certificates password on every new shell. And then the certificate is "loaded" and you can use it to authenticate against an ssh server without putting any kind of password. But this is on that particular shell.
With keychain you can do the same thing as ssh-agent but "system-wide". Once you turn on your computer, you open a shell and put the password of the certificate. And then, every other shell will use that "loaded" certificate and your password will never be asked again until you restart your PC.
Gnome has a similar application, called Gnome Keyring that asks for your certificate's password the first time you use it and then it stores it securely so you won't be asked again.
Programmatically stop execution of python script?
You want sys.exit()
. From Python's docs:
>>> import sys
>>> print sys.exit.__doc__
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
So, basically, you'll do something like this:
from sys import exit
# Code!
exit(0) # Successful exit
Java reading a file into an ArrayList?
You can for example do this in this way (full code with exceptions handlig):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
passing object by reference in C++
What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &
) aren't called using actual addresses, i.e. &a
.
The simple answer is that declaring a function as pass-by-reference:
void foo(int& x);
is all we need. It's then passed by reference automatically.
You now call this function like so:
int y = 5;
foo(y);
and y
will be passed by reference.
You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy* param);
};
int CDummy::isitme (CDummy* param)
{
if (param == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a; // assigning address of a to b
if ( b->isitme(&a) ) // Called with &a (address of a) instead of a
cout << "yes, &a is b";
return 0;
}
Output:
yes, &a is b
How can I tail a log file in Python?
All the answers that use tail -f are not pythonic.
Here is the pythonic way: ( using no external tool or library)
def follow(thefile):
while True:
line = thefile.readline()
if not line or not line.endswith('\n'):
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open("run/foo/access-log","r")
loglines = follow(logfile)
for line in loglines:
print(line, end='')
How to send HTML-formatted email?
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
Difference between thread's context class loader and normal classloader
This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader
query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader()
when you have to call a method that is missing a ClassLoader
parameter.
When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()
). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.
When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader
as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader()
.
Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader()
, sun.misc.VM.latestUserDefinedLoader()
, or sun.reflect.Reflection.getCallerClass()
it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader()
exists only because whoever designed the ObjectInputStream
API forgot to accept the ClassLoader
as a parameter, and this mistake has haunted the Java community to this day.
That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader
(which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null
), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH
) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.
When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader
before the API call (and resetting it afterwards):
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// call some API that uses reflection without taking ClassLoader param
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
How do I remove documents using Node.js Mongoose?
If you are looking for only one object to be removed, you can use
Person.findOne({_id: req.params.id}, function (error, person){
console.log("This object will get deleted " + person);
person.remove();
});
In this example, Mongoose will delete based on matching req.params.id.
How to change option menu icon in the action bar?
//just edit menu.xml file
//add icon for item which will change default setting icon
//add sub menus
///menu.xml file
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:icon="@drawable/your_icon"
app:showAsAction="always" >
<menu>
<item android:id="@+id/action_menu1"
android:icon="@android:drawable/ic_menu_preferences"
android:title="menu 1" />
<item android:id="@+id/action_menu2"
android:icon="@android:drawable/ic_menu_help"
android:title="menu 2" />
</menu>
</item>
AngularJS - value attribute for select
you can use
state.name for state in states track by state.code
Where states in the JSON array, state is the variable name for each object in the array.
Hope this helps
Let JSON object accept bytes or let urlopen output strings
For anyone else trying to solve this using the requests
library:
import json
import requests
r = requests.get('http://localhost/index.json')
r.raise_for_status()
# works for Python2 and Python3
json.loads(r.content.decode('utf-8'))
regex.test V.S. string.match to know if a string matches a regular expression
Basic Usage
First, let's see what each function does:
regexObject.test( String )
Executes the search for a match between a regular expression and a specified string. Returns true or false.
string.match( RegExp )
Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null
if there are none.
Since null
evaluates to false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Performance
Is there any difference regarding performance?
Yes. I found this short note in the MDN site:
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
Is the difference significant?
The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:
Conclusion
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
Why can't I declare static methods in an interface?
The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:
public class A {
public method x() {...}
}
public class B {
public method x() {...}
}
public class C extends A, B { ... }
Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.
Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:
public interface A {
public static method x() {...}
}
public interface B {
public static method x() {...}
}
public class C implements A, B { ... }
Same problem here, what happen if you call C.x()?
Java Switch Statement - Is "or"/"and" possible?
The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.
// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
// handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
// handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
// handle digit case
} else {
// handle consonant case, assuming other characters are not possible
}
Of course, if this gets any more complicated, I'd recommend a regex matcher.
CSS: Control space between bullet and <li>
It seems you can (somewhat) control the spacing using padding on the <li> tag.
<style type="text/css">
li { padding-left: 10px; }
</style>
The catch is that it doesn't seem to allow you to scrunch it way-snug like your final example.
For that you could try turning off list-style-type and using •
<ul style="list-style-type: none;">
<li>•Some list text goes here.</li>
</ul>
How can I get the line number which threw exception?
I added an extension to Exception which returns the line, column, method, filename and message:
public static class Extensions
{
public static string ExceptionInfo(this Exception exception)
{
StackFrame stackFrame = (new StackTrace(exception, true)).GetFrame(0);
return string.Format("At line {0} column {1} in {2}: {3} {4}{3}{5} ",
stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber(),
stackFrame.GetMethod(), Environment.NewLine, stackFrame.GetFileName(),
exception.Message);
}
}
a tag as a submit button?
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
Get a particular cell value from HTML table using JavaScript
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body
is the id of the table body tag .
Finding modified date of a file/folder
You can try dirTimesJS.bat and fileTimesJS.bat
example:
C:\>dirTimesJS.bat %windir%
directory timestamps for C:\Windows :
Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4
Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6
Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2
C:\>fileTimesJS.bat %windir%\notepad.exe
file timestamps for C:\Windows\notepad.exe :
Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3
Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3
Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4
Java Garbage Collection Log messages
I just wanted to mention that one can get the detailed GC log with the
-XX:+PrintGCDetails
parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.
Also -Xloggc:gc.log
seems to generate the same output like -verbose:gc
but you can specify an output file in the first.
Example usage:
java -Xloggc:./memory.log -XX:+PrintGCDetails Memory
To visualize the data better you can try gcviewer (a more recent version can be found on github).
Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!
Android and Facebook share intent
The easiest way that I could find to pass a message from my app to facebook was programmatically copy to the clipboard and alert the user that they have the option to paste. It saves the user from manually doing it; my app is not pasting but the user might.
...
if (app.equals("facebook")) {
// overcome fb 'putExtra' constraint;
// copy message to clipboard for user to paste into fb.
ClipboardManager cb = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post", msg);
cb.setPrimaryClip(clip);
// tell the to PASTE POST with option to stop showing this dialogue
showDialog(this, getString(R.string.facebook_post));
}
startActivity(appIntent);
...
SQL Server: combining multiple rows into one row
There are several methods.
If you want just the consolidated string value returned, this is a good quick and easy approach
DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
AND ISSUE = 19602
SELECT @combinedString as StringValue
Which will return your combined string.
You can also try one of the XML methods e.g.
SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ','
FROM jira.customfieldvalue v2
WHERE v2.Customfield = v1.Customfield
AND v2.Issue = v1.issue
ORDER BY ID
FOR XML PATH('') ) D ( StringValues )
WHERE customfield = 12534
AND ISSUE = 19602
Lombok is not generating getter and setter
I am using Red hat Jboss developer studio. I solved this issue by:
The project has lombok
dependency. First look into your .m2
repository and find the lombok
jar
Double click on the jar, you will see installer there specify the path for IDE like C:\Users\xxx\devstudio\studio\devstudio.exe
Restart the IDE and update the maven project the error will go
How to remove gem from Ruby on Rails application?
If you're using Rails 3+, remove the gem from the Gemfile and run bundle install
.
If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install
should do the trick.
binning data in python with scipy/numpy
The Scipy (>=0.11) function scipy.stats.binned_statistic specifically addresses the above question.
For the same example as in the previous answers, the Scipy solution would be
import numpy as np
from scipy.stats import binned_statistic
data = np.random.rand(100)
bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]
Ineligible Devices section appeared in Xcode 6.x.x
My answer, perhaps listed already but i did not notice, was simple: I deleted the app in question from the target itself, then fired up Xcode and the target was then available. And yes, i tried most of the other suggestions, and was resorting to activating the target from the Product menu, but that was getting tedious.
Stop and Start a service via batch or cmd file?
You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.
net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%
Disclaimer: I've written this from the top of my head, but I think it'll work.
Removing all unused references from a project in Visual Studio projects
All you need is stone and bare knuckle then you can do it like a caveman.
- Remove unused namespaces (for each class)
- Run Debug build
- Copy your executable and remaining namespace references to new location
- Run the executable
- Missing Reference DLL error will occur
- Copy required DLL from Debug folder
- Repeat 4-6
- Gu Gu Ga Ga?
- Throw your stone
You can also rely on your build tools to let you know which reference is still required. It's the era of VS 2017, caveman still survived.
GROUP BY without aggregate function
You're experiencing a strict requirement of the GROUP BY clause. Every column not in the group-by clause must have a function applied to reduce all records for the matching "group" to a single record (sum, max, min, etc).
If you list all queried (selected) columns in the GROUP BY clause, you are essentially requesting that duplicate records be excluded from the result set. That gives the same effect as SELECT DISTINCT which also eliminates duplicate rows from the result set.
.Net picking wrong referenced assembly version
Maybe this helps or maybe not. I cleaned my debug and release versions then I renamed the OBJ folder. This finally got me thorugh. Previous steps were basically project removing references and them adding them back in at the project properties.
Multi-line bash commands in makefile
What's wrong with just invoking the commands?
foo:
echo line1
echo line2
....
And for your second question, you need to escape the $
by using $$
instead, i.e. bash -c '... echo $$a ...'
.
EDIT: Your example could be rewritten to a single line script like this:
gcc $(for i in `find`; do echo $i; done)
How to build a Horizontal ListView with RecyclerView?
Complete example
The only real difference between a vertical RecyclerView
and a horizontal one is how you set up the LinearLayoutManager
. Here is the code snippet. The full example is below.
LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);
This fuller example is modeled after my vertical RecyclerView
answer.
Update Gradle dependencies
Make sure the following dependencies are in your app gradle.build
file:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
You can update the version numbers to whatever is the most current.
Create activity layout
Add the RecyclerView
to your xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Create item layout
Each item in our RecyclerView
is going to have a single a colored View
over a TextView
. Create a new layout resource file.
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<View
android:id="@+id/colorView"
android:layout_width="100dp"
android:layout_height="100dp"/>
<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
Create the adapter
The RecyclerView
needs an adapter to populate the views in each row (horizontal item) with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<Integer> mViewColors;
private List<String> mAnimals;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<Integer> colors, List<String> animals) {
this.mInflater = LayoutInflater.from(context);
this.mViewColors = colors;
this.mAnimals = animals;
}
// inflates the row layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the view and textview in each row
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int color = mViewColors.get(position);
String animal = mAnimals.get(position);
holder.myView.setBackgroundColor(color);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mAnimals.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View myView;
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myView = itemView.findViewById(R.id.colorView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mAnimals.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
- Although not strictly necessary, I included the functionality for listening for click events on the items. This was available in the old
ListViews
and is a common need. You can remove this code if you don't need it.
Initialize RecyclerView in Activity
Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
private MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<Integer> viewColors = new ArrayList<>();
viewColors.add(Color.BLUE);
viewColors.add(Color.YELLOW);
viewColors.add(Color.MAGENTA);
viewColors.add(Color.RED);
viewColors.add(Color.BLACK);
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManager);
adapter = new MyRecyclerViewAdapter(this, viewColors, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show();
}
}
Notes
- Notice that the activity implements the
ItemClickListener
that we defined in our adapter. This allows us to handle item click events in onItemClick
.
Finished
That's it. You should be able to run your project now and get something similar to the image at the top.
Notes
Upload Image using POST form data in Python-requests
From wechat api doc:
curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Get bytes from std::string in C++
Normally, encryption functions take
encrypt(const void *ptr, size_t bufferSize);
as arguments. You can pass c_str and length directly:
encrypt(strng.c_str(), strng.length());
This way, extra space is allocated or wasted.
When should you NOT use a Rules Engine?
The one poit I've noticed to be "the double edged sword" is:
placing the logic in hands of non technical staff
I've seen this work great, when you have one or two multidisciplinary geniuses on the non technical side, but I've also seen the lack of technicity leading to bloat, more bugs, and in general 4x the development/maintenance cost.
Thus you need to consider your user-base seriously.
Byte Array and Int conversion in Java
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
What is the reason behind "non-static method cannot be referenced from a static context"?
I just realized, I think people shouldn't be exposed to the concept of "static" very early.
Static methods should probably be the exception rather than the norm. Especially early on anyways if you want to learn OOP. (Why start with an exception to the rule?) That's very counter-pedagogical of Java, that the "first" thing you should learn is the public static void main thing. (Few real Java applications have their own main methods anyways.)
"std::endl" vs "\n"
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl
flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.
How to use select/option/NgFor on an array of objects in Angular2
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"
Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.
Lets say the static date is March 10th, 2015, and is in cell O5.
The formula to determine the number of days between today and O5 would be, =O5-Today()
Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.
Pandas: Appending a row to a dataframe and specify its index label
The name
of the Series becomes the index
of the row in the DataFrame:
In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
In [100]: s = df.xs(3)
In [101]: s.name = 10
In [102]: df.append(s)
Out[102]:
A B C D
0 -2.083321 -0.153749 0.174436 1.081056
1 -1.026692 1.495850 -0.025245 -0.171046
2 0.072272 1.218376 1.433281 0.747815
3 -0.940552 0.853073 -0.134842 -0.277135
4 0.478302 -0.599752 -0.080577 0.468618
5 2.609004 -1.679299 -1.593016 1.172298
6 -0.201605 0.406925 1.983177 0.012030
7 1.158530 -2.240124 0.851323 -0.240378
10 -0.940552 0.853073 -0.134842 -0.277135
How to get the size of a JavaScript object?
Many thanks to everyone that has been working on code for this!
I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.
Anyway, I use it for something something like:
var myCache = {
cache: {},
order: [],
size: 0,
maxSize: 2 * 1024 * 1024, // 2mb
add: function(key, object) {
// Otherwise add new object
var size = this.getObjectSize(object);
if (size > this.maxSize) return; // Can't store this object
var total = this.size + size;
// Check for existing entry, as replacing it will free up space
if (typeof(this.cache[key]) !== 'undefined') {
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
total -= entry.size;
this.order.splice(i, 1);
break;
}
}
}
while (total > this.maxSize) {
var entry = this.order.shift();
delete this.cache[entry.key];
total -= entry.size;
}
this.cache[key] = object;
this.order.push({ size: size, key: key });
this.size = total;
},
get: function(key) {
var value = this.cache[key];
if (typeof(value) !== 'undefined') { // Return this key for longer
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
this.order.splice(i, 1);
this.order.push(entry);
break;
}
}
}
return value;
},
getObjectSize: function(object) {
// Code from above estimating functions
},
};
It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.
Use a list of values to select rows from a pandas dataframe
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
SQL: Return "true" if list of records exists?
DECLARE @values TABLE (ProductId int)
INSERT @values (1)
INSERT @values (10)
INSERT @values (100)
SELECT CASE WHEN (SELECT COUNT(*) FROM @values v) =
(SELECT COUNT(*) FROM Products p WHERE p.ProductId IN
(SELECT v.ProductId FROM @values v))
THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END [AreAllFound]
Finding duplicate rows in SQL Server
You have several way for Select duplicate rows
.
for my solutions , first consider this table for example
CREATE TABLE #Employee
(
ID INT,
FIRST_NAME NVARCHAR(100),
LAST_NAME NVARCHAR(300)
)
INSERT INTO #Employee VALUES ( 1, 'Ardalan', 'Shahgholi' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 4, 'name3', 'lname3' );
First solution :
SELECT DISTINCT *
FROM #Employee;
WITH #DeleteEmployee AS (
SELECT ROW_NUMBER()
OVER(PARTITION BY ID, First_Name, Last_Name ORDER BY ID) AS
RNUM
FROM #Employee
)
SELECT *
FROM #DeleteEmployee
WHERE RNUM > 1
SELECT DISTINCT *
FROM #Employee
Secound solution : Use identity
field
SELECT DISTINCT *
FROM #Employee;
ALTER TABLE #Employee ADD UNIQ_ID INT IDENTITY(1, 1)
SELECT *
FROM #Employee
WHERE UNIQ_ID < (
SELECT MAX(UNIQ_ID)
FROM #Employee a2
WHERE #Employee.ID = a2.ID
AND #Employee.FIRST_NAME = a2.FIRST_NAME
AND #Employee.LAST_NAME = a2.LAST_NAME
)
ALTER TABLE #Employee DROP COLUMN UNIQ_ID
SELECT DISTINCT *
FROM #Employee
and end of all solution use this command
DROP TABLE #Employee
Using Get-childitem to get a list of files modified in the last 3 days
I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.
([System.Object[]](gci c:\pstback\ -Filter *.pst |
? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count
It still doesn't return zero if empty, but testing '-lt 1' works.
Auto refresh page every 30 seconds
There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta
tag in your head
tag.
<meta http-equiv="refresh" content="30">
The browser will then refresh the page every 30 seconds.
If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload()
(docs) inside a setTimeout()
:
window.setTimeout(function () {
window.location.reload();
}, 30000);
If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.
Python loop for inside lambda
Just in case, if someone is looking for a similar problem...
Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code).
Instead, you can use a simple list comprehension.
[print(i) for i in x]
BTW, the return values will be a list on None s.
Project has no default.properties file! Edit the project properties to set one
If the project already contains a file default.properties you can open that file and edit+save it (add a space, save, remove that space, save). That worked for me.
A note with the above discussion:
R.java is getting generated automatically by doing the above described process. When I go and remove it, it gets generated again. Neither is it allowing me to edited the automatically generated one. – Compuser7
With respect to the comment quoted above, R.java is indeed an automatically generated class that contains references to all the resources (in the res folder) that belong with your project.
When Eclipse rebuilds, this file is regenerated, since most application (I mean Java code) rely on the fact that there are some resources (images, layouts and string values) available. When you remove the file R.java through Eclipse, Eclipse will see this change in the project as a reason to automatically rebuild (see the options under Project) the project, regenerating the R.java file.
So DON'T try to remove R.java, because Eclipse will regenerate it as soon as you rebuild the project, which will result in a match of patience ;)
Entity Framework Migrations renaming tables and columns
If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn
code which is required:
Step One Use the ColumnAttribute
to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged
)
public class ReportPages
{
[Column("Section_Id")] //Section_Id
public int Group_Id{get;set}
}
Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force
) in the Package Manager Console
public class ReportPages
{
[Column("Section_Id")] //Section_Id
public int Section_Id{get;set}
}
If you look at the Migration class you can see the automatically code generated is RenameColumn
.
Update an outdated branch against master in a Git repo
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
node.js, socket.io with SSL
For enterprise applications it should be noted that you should not be handling https in your code. It should be auto upgraded via IIS or nginx. The app shouldn't know about what protocols are used.
How to implement the factory method pattern in C++ correctly
First of all, there are cases when
object construction is a task complex
enough to justify its extraction to
another class.
I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.
Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!
There is an easy workaround for this:
struct Cartesian {
inline Cartesian(float x, float y): x(x), y(y) {}
float x, y;
};
struct Polar {
inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);
The only disadvantage is that it looks a bit verbose:
Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));
But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classes to avoid copying overhead.
As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically can be deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil? for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:
class Abstract {
public:
virtual void do() = 0;
};
class Factory {
public:
Abstract *create();
};
Factory f;
Abstract *a = f.create();
a->do();
In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.
How to Resize a Bitmap in Android?
Scale a bitmap with a target maximum size and width, while maintaining aspect ratio:
int maxHeight = 2000;
int maxWidth = 2000;
float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
When is null or undefined used in JavaScript?
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined
, making it somewhat unreliable compared to null
. Using the ==
operator, you can reliably use null
and undefined
interchangeably as far as I can tell. However, because of the advantage that null
cannot be redefined, I might would use it when using ==
.
For example, variable != null
will ALWAYS return false if variable
is equal to either null
or undefined
, whereas variable != undefined
will return false if variable
is equal to either null
or undefined
UNLESS undefined
is reassigned beforehand.
You can reliably use the ===
operator to differentiate between undefined
and null
, if you need to make sure that a value is actually undefined
(rather than null
).
According to the ECMAScript 5 spec:
- Both
Null
and Undefined
are two of the six built in types.
4.3.9 undefined value
primitive value used when a variable has not been assigned a value
4.3.11 null value
primitive value that represents the intentional absence of any object value
URL Encode a string in jQuery for an AJAX request
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
SQL ORDER BY multiple columns
Yes, the sorting is different.
Items in the ORDER BY
list are applied in order.
Later items only order peers left from the preceding step.
Why don't you just try?
ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies
It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.
Closing Applications
System.Windows.Forms.Application.Exit()
- Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit()
method is typically called from within a message loop, and forces Run()
to return. To exit a message loop for the current thread only, call ExitThread()
. This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run()
.
System.Environment.Exit(exitCode)
- Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode
permissions. If you do not, a SecurityException
error occurs. This is the call to use if you are running a console application.
I hope it is best to use Application.Exit
See also these links:
How can I set a css border on one side only?
#testDiv{
/* set green border independently on each side */
border-left: solid green 2px;
border-right: solid green 2px;
border-bottom: solid green 2px;
border-top: solid green 2px;
}
Why is Dictionary preferred over Hashtable in C#?
Collections
& Generics
are useful for handling group of objects. In .NET, all the collections objects comes under the interface IEnumerable
, which in turn has ArrayList(Index-Value))
& HashTable(Key-Value)
. After .NET framework 2.0, ArrayList
& HashTable
were replaced with List
& Dictionary
. Now, the Arraylist
& HashTable
are no more used in nowadays projects.
Coming to the difference between HashTable
& Dictionary
, Dictionary
is generic where as Hastable
is not Generic. We can add any type of object to HashTable
, but while retrieving we need to cast it to the required type. So, it is not type safe. But to dictionary
, while declaring itself we can specify the type of key and value, so there is no need to cast while retrieving.
Let's look at an example:
HashTable
class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}
}
}
Dictionary,
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int, string> dt = new Dictionary<int, string>();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair<int, String> kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
}
}
Why doesn't Git ignore my specified file?
Another possible reason – a few instances of git clients running at the same time. For example "git shell" + "GitHub Desktop", etc.
This happened to me, I was using "GitHub Desktop" as the main client and it was ignoring some new .gitignore settings: commit after commit:
- You commit something.
- Next, commit: it ignores .gitignore settings. Commit includes lots of temp files mentioned in the .gitignore.
- Clear git cache; check whether .gitignore is UTF8; remove files -> commit -> move files back; skip 1 commit – nothing helped.
Reason: the Visual Studio Code editor was running in the background with the same opened repository. VS Code has built-in git control, and this makes some conflicts.
Solution: double-check multiple, hidden git clients and use only one git client at once, especially while clearing git cache.
How to show Snackbar when Activity starts?
It can be done simply by using the following codes inside onCreate. By using android's default layout
Snackbar.make(findViewById(android.R.id.content),"Your Message",Snackbar.LENGTH_LONG).show();
How to get the exact local time of client?
my code is
<html>
<head>
<title>Title</title>
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
</script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
if you want more codes visit my blog http://mysimplejavascriptcode.blogspot.in/
Why am I getting error for apple-touch-icon-precomposed.png
An alternative solution is to simply add a route to your routes.rb
It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.
# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/
then add a method 'apple_touch_not_found' to your application_controller.rb
# application_controller.rb
def apple_touch_not_found
render plain: 'apple-touch icons not found', status: 404
end
How to resolve "Server Error in '/' Application" error?
vs2017 just added in these lines to csproj.user file
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
<IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>
with these lines in Web.config
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
<identity impersonate="false" />
<authentication mode="Windows" />
<authorization>
<allow users="yourNTusername" />
<deny users="?" />
</authorization>
And it worked
Catching errors in Angular HttpClient
You probably want to have something like this:
this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})
It highly depends also how do you use your service but this is the basic case.
Pull request vs Merge request
As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
git pull fails "unable to resolve reference" "unable to update local ref"
We got this issue when a developer on Mac created a branch with a greater than ">" symbol in the branch name.
That caused problems in TeamCity, and on local Windows based computers running SourceTree. BitBucket let it through without any problems.
To resolve the user removed the branch and recreated it. Which was nice and easy.
Convert negative data into positive data in SQL Server
The best solution is: from positive to negative or from negative to positive
For negative:
SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable
For positive:
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
Insertion Sort vs. Selection Sort
I'll give it yet another try: consider what happens in the lucky case of almost sorted array.
While sorting, the array can be thought of as having two parts: left hand side - sorted, right hand side - unsorted.
Insertion sort - pick first unsorted element and try to find a place for it among the already sorted part. Since you search from right to left it might very well happen that the first sorted element you are comparing to (the largest one, most right in the left part) is smaller than the picked element so you can immediately continue with the next unsorted element.
Selection sort - pick the first unsorted element and try to find the smallest element of the whole unsorted part, and exchange those two if desirable. The problem is, since the right part is unsorted, you have to go thought every element every time, since you cannot possibly be sure whether there is or is not even smaller element than the picked one.
Btw., this is exactly what heapsort improves upon selection sort - it is able to find the smallest element much more quickly because of the heap.
jQuery click events firing multiple times
All the stuff about .on() and .one() is great, and jquery is great.
But sometimes, you want it to be a little more obvious that the user isn't allowed to click, and in those cases you could do something like this:
function funName(){
$("#orderButton").prop("disabled", true);
// do a bunch of stuff
// and now that you're all done
setTimeout(function(){
$("#orderButton").prop("disabled",false);
$("#orderButton").blur();
}, 3000);
}
and your button would look like:
<button onclick='funName()'>Click here</button>
How to add a Hint in spinner in XML
In the adapter you can set the first item as disabled. Below is the sample code
@Override
public boolean isEnabled(int position) {
if (position == 0) {
// Disable the first item from Spinner
// First item will be use for hint
return false;
} else {
return true;
}
}
And set the first item to grey color.
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.BLACK);
}
return view;
}
And if the user selects the first item then do nothing.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = (String) parent.getItemAtPosition(position);
// If user change the default selection
// First item is disable and it is used for hint
if (position > 0) {
// Notify the selected item text
Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
}
}
Refer the below link for detail.
How to add a hint to Spinner in Android
How do I make HttpURLConnection use a proxy?
Set following before you openConnection,
System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");
If proxy requires authentication,
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");
How to resize the jQuery DatePicker control
I was trying these examples without success. Apparently other stylesheets on the page were setting default font sizes for different tags. If you adjust the ui-datepicker you are changing a div. If you change a div you need to make sure the contents of that div inherit that size. This is what finally worked for me:
<style type="text/css">
.ui-datepicker-calendar tr, .ui-datepicker-calendar td, .ui-datepicker-calendar td a, .ui-datepicker-calendar th{font-size:inherit;}
div.ui-datepicker{font-size:16px;width:inherit;height:inherit;}
.ui-datepicker-title span{font-size:16px;}
</style>
Good luck!
How to sanity check a date in Java
Two comments on the use of SimpleDateFormat.
it should be declared as a static instance
if declared as static access should be synchronized as it is not thread safe
IME that is better that instantiating an instance for each parse of a date.
How to convert a Base64 string into a Bitmap image to show it in a ImageView?
To check online you can use
http://codebeautify.org/base64-to-image-converter
You can convert string to image like this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image =(ImageView)findViewById(R.id.image);
//encode image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
}
}
http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html
Swift Set to Array
call this method and pass your set
func getArrayFromSet(set:NSSet)-> NSArray {
return set.map ({ String($0) })
}
Like This :
var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))
Convert a string to datetime in PowerShell
You need to specify the format it already has, in order to parse it:
$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)
Now you can output it in the format you need:
$InvoiceDate.ToString('yyyy-MM-dd')
or
'{0:yyyy-MM-dd}' -f $InvoiceDate
Counting array elements in Python
If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:
import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2
This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.
import numpy as np
len(a) == np.shape(a)[0]
To get the number of elements in a multi-dimensional array of arbitrary shape:
import numpy as np
size = 1
for dim in np.shape(a): size *= dim
WCF Exception: Could not find a base address that matches scheme http for the endpoint
Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" />
depending on your needs for authentication. The config below doesn't require any authentication.
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfiguration">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="XXX">
<endpoint
name="AAA"
address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpBindingConfiguration"
contract="YourContract" />
</service>
<services>
That will allow a WCF service with basicHttpBinding
to use HTTPS.
How to kill a nodejs process in Linux?
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
Get selected text from a drop-down list (select box) using jQuery
Use this
const select = document.getElementById("yourSelectId");
const selectedIndex = select.selectedIndex;
const selectedValue = select.value;
const selectedText = select.options[selectedIndex].text;
Then you get your selected value and text inside selectedValue
and selectedText
.
git replace local version with remote version
I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).
Simply do
git checkout remote/branch -- a/file b/another/file
If you want to do this for extensive subtrees and instead wish to affect the index directly use
git read-tree remote/branch:subdir/
You can then (optionally) update your working copy by doing
git checkout-index -u --force
How to run the sftp command with a password from Bash script?
You can use a Python script with scp and os library to make a system call.
- ssh-keygen -t rsa -b 2048 (local machine)
- ssh-copy-id user@remote_server_address
- create a Python script like:
import os
cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
os.system(cmd)
- create a rule in crontab to automate your script
- done
How to make a redirection on page load in JSF 1.x
Assume that foo.jsp is your jsp file. and following code is the button that you want do redirect.
<h:commandButton value="Redirect" action="#{trial.enter }"/>
And now we'll check the method for directing in your java (service) class
public String enter() {
if (userName.equals("xyz") && password.equals("123")) {
return "enter";
} else {
return null;
}
}
and now this is a part of faces-config.xml file
<managed-bean>
<managed-bean-name>'class_name'</managed-bean-name>
<managed-bean-class>'package_name'</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-case>
<from-outcome>enter</from-outcome>
<to-view-id>/foo.jsp</to-view-id>
<redirect />
</navigation-case>
HTTP Error 404.3-Not Found in IIS 7.5
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.