How can I turn a string into a list in Python?
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
CS0234: Mvc does not exist in the System.Web namespace
You need to include the reference to the assembly System.Web.Mvc in you project.
you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0
So you need to add it and then to include it as reference to your projrect
How to set background color in jquery
You actually got it. Just forgot some quotes.
$(this).css({backgroundColor: 'red'});
or
$(this).css('background-color', 'red');
You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -
. All CSS properties which have such a character are mapped with capital letters.
Reference: .css()
Convert int to a bit array in .NET
I just ran into an instance where...
int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];
...did not produce the results I was looking for. In 'myVal' above, the value stored in the array in position 21 was '0'. It should have been a '1'. I'm not sure why I received an inaccurate value for this and it baffled me until I found another way in C# to convert an INT to a bit array:
int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];
This produced the result 'true' as a boolean value for 'myVal'.
I realize this may not be the most efficient way to obtain this value, but it was very straight forward, simple, and readable.
How do I make a fully statically linked .exe with Visual Studio Express 2005?
I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:
How to: Deploy using XCopy (MSDN)
Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).
Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.
Finding the number of non-blank columns in an Excel sheet using VBA
Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:
Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow
It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:
Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn
This may also be of use to you:
With Sheet1.UsedRange
MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With
but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange
property.
How to copy and edit files in Android shell?
Since the permission policy on my device is a bit paranoid (cannot adb pull
application data), I wrote a script to copy files recursively.
Note: this recursive file/folder copy script is intended for Android!
copy-r:
#! /system/bin/sh
src="$1"
dst="$2"
dir0=`pwd`
myfind() {
local fpath=$1
if [ -e "$fpath" ]
then
echo $fpath
if [ -d "$fpath" ]
then
for fn in $fpath/*
do
myfind $fn
done
fi
else
: echo "$fpath not found"
fi
}
if [ ! -z "$dst" ]
then
if [ -d "$src" ]
then
echo 'the source is a directory'
mkdir -p $dst
if [[ "$dst" = /* ]]
then
: # Absolute path
else
# Relative path
dst=`pwd`/$dst
fi
cd $src
echo "COPYING files and directories from `pwd`"
for fn in $(myfind .)
do
if [ -d $fn ]
then
echo "DIR $dst/$fn"
mkdir -p $dst/$fn
else
echo "FILE $dst/$fn"
cat $fn >$dst/$fn
fi
done
echo "DONE"
cd $dir0
elif [ -f "$src" ]
then
echo 'the source is a file'
srcn="${src##*/}"
if [ -z "$srcn" ]
then
srcn="$src"
fi
if [[ "$dst" = */ ]]
then
mkdir -p $dst
echo "copying $src" '->' "$dst/$srcn"
cat $src >$dst/$srcn
elif [ -d "$dst" ]
then
echo "copying $src" '->' "$dst/$srcn"
cat $src >$dst/$srcn
else
dstdir=${dst%/*}
if [ ! -z "$dstdir" ]
then
mkdir -p $dstdir
fi
echo "copying $src" '->' "$dst"
cat $src >$dst
fi
else
echo "$src is neither a file nor a directory"
fi
else
echo "Use: copy-r src-dir dst-dir"
echo "Use: copy-r src-file existing-dst-dir"
echo "Use: copy-r src-file dst-dir/"
echo "Use: copy-r src-file dst-file"
fi
Here I provide the source of a lightweight find
for Android because on some devices this utility is missing. Instead of myfind
one can use find
, if it is defined on the device.
Installation:
$ adb push copy-r /sdcard/
Running within adb shell
(rooted):
# . /sdcard/copy-r files/ /sdcard/files3
or
# source /sdcard/copy-r files/ /sdcard/files3
(The hash #
above is the su
prompt, while .
is the command that causes the shell to run the specified file, almost the same as source
).
After copying, I can adb pull
the files from the sd-card.
Writing files to the app directory was trickier, I tried to set r/w permissions on files
and its subdirectories, it did not work (well, it allowed me to read, but not write, which is strange), so I had to do:
String[] cmdline = { "sh", "-c", "source /sdcard/copy-r /sdcard/files4 /data/data/com.example.myapp/files" };
try {
Runtime.getRuntime().exec(cmdline);
} catch (IOException e) {
e.printStackTrace();
}
in the application's onCreate().
PS just in case someone needs the code to unprotect application's directories to enable adb shell
access on a non-rooted phone,
setRW(appContext.getFilesDir().getParentFile());
public static void setRW(File... files) {
for (File file : files) {
if (file.isDirectory()) {
setRW(file.listFiles()); // Calls same method again.
} else {
}
file.setReadable(true, false);
file.setWritable(true, false);
}
}
although for some unknown reason I could read but not write.
Secondary axis with twinx(): how to add to legend?
A quick hack that may suit your needs..
Take off the frame of the box and manually position the two legends next to each other. Something like this..
ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)
Where the loc tuple is left-to-right and bottom-to-top percentages that represent the location in the chart.
Debugging PHP Mail() and/or PHPMailer
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
How does Trello access the user's clipboard?
Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.
We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.
Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)
Specifically, Trello does this:
TrelloClipboard = new class
constructor: ->
@value = ""
$(document).keydown (e) =>
# Only do this if there's something to be put on the clipboard, and it
# looks like they're starting a copy shortcut
if !@value || !(e.ctrlKey || e.metaKey)
return
if $(e.target).is("input:visible,textarea:visible")
return
# Abort if it looks like they've selected some text (maybe they're trying
# to copy out a bit of the description or something)
if window.getSelection?()?.toString()
return
if document.selection?.createRange().text
return
_.defer =>
$clipboardContainer = $("#clipboard-container")
$clipboardContainer.empty().show()
$("<textarea id='clipboard'></textarea>")
.val(@value)
.appendTo($clipboardContainer)
.focus()
.select()
$(document).keyup (e) ->
if $(e.target).is("#clipboard")
$("#clipboard-container").empty().hide()
set: (@value) ->
In the DOM we've got:
<div id="clipboard-container"><textarea id="clipboard"></textarea></div>
CSS for the clipboard stuff:
#clipboard-container {
position: fixed;
left: 0px;
top: 0px;
width: 0px;
height: 0px;
z-index: 100;
display: none;
opacity: 0;
}
#clipboard {
width: 1px;
height: 1px;
padding: 0px;
}
... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.
When you hover over a card, it calls
TrelloClipboard.set(cardUrl)
... so then the clipboard helper knows what to select when the Ctrl key is pressed.
Error:attempt to apply non-function
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
CSS Background image not loading
I had the same problem and after reading this found the issue, it was the slash.
Windows Path:
images\green_cup.png
CSS that worked:
images/green_cup.png
images\green_cup.png does not work.
Phil
Overlaying histograms with ggplot2 in R
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
How to exclude subdirectories in the destination while using /mir /xd switch in robocopy
The way you can exclude a destination directory while using the /mir is by making sure the destination directory also exists on the source. I went into my source drive and created blank directories with the same name as on the destination, and then added that directory name to the /xd. It successfully mirrored everything while excluding the directory on the source, thereby leaving the directory on the destination intact.
load Js file in HTML
If this is your detail.html
I don't see where do you load detail.js
?
Maybe this
<script src="js/index.js"></script>
should be this
<script src="js/detail.js"></script>
?
What is the difference between canonical name, simple name and class name in Java Class?
getName() – returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
getCanonicalName() – returns the canonical name of the underlying class as defined by the Java Language Specification.
getSimpleName() – returns the simple name of the underlying class, that is the name it has been given in the source code.
package com.practice;
public class ClassName {
public static void main(String[] args) {
ClassName c = new ClassName();
Class cls = c.getClass();
// returns the canonical name of the underlying class if it exists
System.out.println("Class = " + cls.getCanonicalName()); //Class = com.practice.ClassName
System.out.println("Class = " + cls.getName()); //Class = com.practice.ClassName
System.out.println("Class = " + cls.getSimpleName()); //Class = ClassName
System.out.println("Class = " + Map.Entry.class.getName()); // -> Class = java.util.Map$Entry
System.out.println("Class = " + Map.Entry.class.getCanonicalName()); // -> Class = java.util.Map.Entry
System.out.println("Class = " + Map.Entry.class.getSimpleName()); // -> Class = Entry
}
}
One difference is that if you use an anonymous class you can get a null value when trying to get the name of the class using the getCanonicalName()
Another fact is that getName()
method behaves differently than the getCanonicalName()
method for inner classes. getName()
uses a dollar as the separator between the enclosing class canonical name and the inner class simple name.
To know more about retrieving a class name in Java.
How to restrict UITextField to take only numbers in Swift?
Dead simple solution for Double
numbers (keep it mind that this is not the best user-friendly solution), in your UITextFieldDelegate
delegate:
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let currentString = textField.text as NSString? else {
return false
}
let newString = currentString.replacingCharacters(in: range, with: string)
return Double(newString) != nil
}
how to get the ipaddress of a virtual box running on local machine
Login to virtual machine use below command to check ip address. (anyone will work)
- ifconfig
- ip addr show
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
Removing multiple keys from a dictionary safely
Found a solution with pop
and map
d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)
The output of this:
{'d': 'valueD'}
I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.
Update
The above code will throw an error if a key does not exist in the dict.
DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']
def remove_keys(key):
try:
DICTIONARY.pop(key, None)
except:
pass # or do any action
list(map(remove_key, keys))
print(DICTIONARY)
output:
DICTIONARY = {'b': 'valueB', 'd': 'valueD'}
How do I get logs/details of ansible-playbook module executions?
Ansible command-line help, such as ansible-playbook --help
shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.
long long in C/C++
Try:
num3 = 100000000000LL;
And BTW, in C++ this is a compiler extension, the standard does not define long long, thats part of C99.
PDF Blob - Pop up window not showing content
You need to set the responseType
to arraybuffer
if you would like to create a blob
from your response data:
$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
more information: Sending_and_Receiving_Binary_Data
How to "pull" from a local branch into another one?
Quite old post, but it might help somebody new into git.
I will go with
git rebase master
- much cleaner log history and no merge commits (if done properly)
- need to deal with conflicts, but it's not that difficult.
How can I use SUM() OVER()
Query would be like this:
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT
FROM #Empl ORDER BY AccountID
Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.
First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 =>
17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10
so result would appear like attached snapshot.
Image, saved to sdcard, doesn't appear in Android's Gallery app
You need to give permissions to the Gallery app.
Just long press the gallery app icon in the home screen and tap on 'APP INFO' that pops up at the top of the screen. Doing it will show the gallery app settings. Now go in Permissions tab and enable the storage, camera permissions by toggling it.
Now go to your native gallery app and you will get the your saved images.
Excel data validation with suggestions/autocomplete
ExtendOffice.com offers a VBA solution that worked for me in Excel 2016. Here's my description of the steps. I included additional details to make it easier. I also modified the VBA code slightly. If this doesn't work for you, retry the steps or check out the instructions on the ExtendOffice page.
Add data validation to a cell (or range of cells). Allow = List. Source = [the range with the values you want for the auto-complete / drop-down]. Click OK. You should now have a drop-down but with a weak auto-complete feature.
With a cell containing your newly added data validation, insert an ActiveX combo box (NOT a form control combo box). This is done from the Developer ribbon. If you don't have the Developer ribbon you will need to add it from the Excel options menu.
From the Developer tab in the Controls section, click "Design Mode". Select the combo box you just inserted. Then in the same ribbon section click "Properties". In the Properties window, change the name of the combo box to "TempComboBox".
Press ALT + F11 to go to the Visual Basic Editor. On the left-hand side, double click the worksheet with your data validation to open the code for that sheet. Copy and paste the following code onto the sheet. NOTE: I modified the code slightly so that it works even with Option Explicit
enabled at the top of the sheet.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal target As Range)
'Update by Extendoffice: 2018/9/21
' Update by Chris Brackett 2018-11-30
Dim xWs As Worksheet
Set xWs = Application.ActiveSheet
On Error Resume Next
Dim xCombox As OLEObject
Set xCombox = xWs.OLEObjects("TempCombo")
' Added this to auto select all text when activating the combox box.
xCombox.SetFocus
With xCombox
.ListFillRange = vbNullString
.LinkedCell = vbNullString
.Visible = False
End With
Dim xStr As String
Dim xArr
If target.Validation.Type = xlValidateList Then
' The target cell contains Data Validation.
target.Validation.InCellDropdown = False
' Cancel the "SelectionChange" event.
Dim Cancel As Boolean
Cancel = True
xStr = target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = vbNullString Then Exit Sub
With xCombox
.Visible = True
.Left = target.Left
.Top = target.Top
.Width = target.Width + 5
.Height = target.Height + 5
.ListFillRange = xStr
If .ListFillRange = vbNullString Then
xArr = Split(xStr, ",")
Me.TempCombo.List = xArr
End If
.LinkedCell = target.Address
End With
xCombox.Activate
Me.TempCombo.DropDown
End If
End Sub
Private Sub TempCombo_KeyDown( _
ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
Select Case KeyCode
Case 9 ' Tab key
Application.ActiveCell.Offset(0, 1).Activate
Case 13 ' Pause key
Application.ActiveCell.Offset(1, 0).Activate
End Select
End Sub
Make sure the the "Microsoft Forms 2.0 Object Library" is referenced. In the Visual Basic Editor, go to Tools > References, check the box next to that library (if not already checked) and click OK. To verify that it worked, go to Debug > Compile VBA Project.
Finally, save your project and click in a cell with the data validation you added. You should see a combo box with a drop-down list of suggestions that updates with each letter you type.
How to Specify "Vary: Accept-Encoding" header in .htaccess
This was driving me crazy, but it seems that aularon's edit was missing the colon after "Vary"
. So changing "Vary Accept-Encoding"
to "Vary: Accept-Encoding"
fixed the issue for me.
I would have commented below the post, but it doesn't seem like it will let me.
Anyhow, I hope this saves someone the same trouble I was having.
How to stop C++ console application from exiting immediately?
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
Correct way to handle conditional styling in React
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
How does one set up the Visual Studio Code compiler/debugger to GCC?
Just wanted to add that if you want to debug stuff, you should compile with debug information before you debug, otherwise the debugger won't work. So, in g++ you need to do g++ -g source.cpp
. The -g
flag means that the compiler will insert debugging information into your executable, so that you can run gdb on it.
Centering image and text in R Markdown for a PDF report
None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.
The include_graphics()
function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo
to FALSE
and fig.align=center
you get the wished result.
```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```
cmd line rename file with date and time
problem in %time:~0,2%
can't set to 24 hrs format, ended with space(1-9), instead of 0(1-9)
go around with:
set HR=%time:~0,2%
set HR=%Hr: =0% (replace space with 0 if any <has a space in between : =0>)
then replace %time:~0,2%
with %HR%
good luck
psycopg2: insert multiple rows with one query
I built a program that inserts multiple lines to a server that was located in another city.
I found out that using this method was about 10 times faster than executemany
. In my case tup
is a tuple containing about 2000 rows. It took about 10 seconds when using this method:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
and 2 minutes when using this method:
cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)
How to Implement DOM Data Binding in JavaScript
So, I decided to throw my own solution in the pot. Here is a working fiddle. Note this only runs on very modern browsers.
What it uses
This implementation is very modern - it requires a (very) modern browser and users two new technologies:
MutationObserver
s to detect changes in the dom (event listeners are used as well)
Object.observe
to detect changes in the object and notifying the dom. Danger, since this answer has been written O.o has been discussed and decided against by the ECMAScript TC, consider a polyfill.
How it works
- On the element, put a
domAttribute:objAttribute
mapping - for example bind='textContent:name'
- Read that in the dataBind function. Observe changes to both the element and the object.
- When a change occurs - update the relevant element.
The solution
Here is the dataBind
function, note it's just 20 lines of code and could be shorter:
function dataBind(domElement, obj) {
var bind = domElement.getAttribute("bind").split(":");
var domAttr = bind[0].trim(); // the attribute on the DOM element
var itemAttr = bind[1].trim(); // the attribute the object
// when the object changes - update the DOM
Object.observe(obj, function (change) {
domElement[domAttr] = obj[itemAttr];
});
// when the dom changes - update the object
new MutationObserver(updateObj).observe(domElement, {
attributes: true,
childList: true,
characterData: true
});
domElement.addEventListener("keyup", updateObj);
domElement.addEventListener("click",updateObj);
function updateObj(){
obj[itemAttr] = domElement[domAttr];
}
// start the cycle by taking the attribute from the object and updating it.
domElement[domAttr] = obj[itemAttr];
}
Here is some usage:
HTML:
<div id='projection' bind='textContent:name'></div>
<input type='text' id='textView' bind='value:name' />
JavaScript:
var obj = {
name: "Benjamin"
};
var el = document.getElementById("textView");
dataBind(el, obj);
var field = document.getElementById("projection");
dataBind(field,obj);
Here is a working fiddle. Note that this solution is pretty generic. Object.observe and mutation observer shimming is available.
Excel column number from column name
While you were looking for a VBA solution, this was my top result on google when looking for a formula solution, so I'll add this for anyone who came here for that like I did:
Excel formula to return the number from a column letter (From @A. Klomp's comment above), where cell A1 holds your column letter(s):
=column(indirect(A1&"1"))
As the indirect function is volatile, it recalculates whenever any cell is changed, so if you have a lot of these it could slow down your workbook. Consider another solution, such as the 'code' function, which gives you the number for an ASCII character, starting with 'A' at 65. Note that to do this you would need to check how many digits are in the column name, and alter the result depending on 'A', 'BB', or 'CCC'.
Excel formula to return the column letter from a number (From this previous question How to convert a column number (eg. 127) into an excel column (eg. AA), answered by @Ian), where A1 holds your column number:
=substitute(address(1,A1,4),"1","")
Note that both of these methods work regardless of how many letters are in the column name.
Hope this helps someone else.
Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?
It's been a significant percentage of our business migrating people from Heroku to AWS. There are advantages to both, but it's gets messy on Heroku after a while... once you need a certain level of complexity no longer easy to maintain with Heroku's limitations.
That said, there are increasingly options to have the ease of Heroku and the flexibility of AWS by being on AWS with great frameworks/tools.
How to view the dependency tree of a given npm module?
You can generate NPM dependency trees without the need of installing
a dependency by using the command
npm list
This will generate a dependency tree for the project at the current directory and print it to the console.
You can get the dependency tree of a specific dependency like so:
npm list [dependency]
You can also set the maximum depth level by doing
npm list --depth=[depth]
Note that you can only view the dependency tree of a dependency that you have installed either globally, or locally to the NPM project.
How do I script a "yes" response for installing programs?
Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).
Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.
lambda expression join multiple tables with select and where clause
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
Using Page_Load and Page_PreRender in ASP.Net
Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load
is the more typical event to work with.
In Python, can I call the main() of an imported module?
It's just a function. Import it and call it:
import myModule
myModule.main()
If you need to parse arguments, you have two options:
Parse them in main()
, but pass in sys.argv
as a parameter (all code below in the same module myModule
):
def main(args):
# parse arguments using optparse or argparse or what have you
if __name__ == '__main__':
import sys
main(sys.argv[1:])
Now you can import and call myModule.main(['arg1', 'arg2', 'arg3'])
from other another module.
Have main()
accept parameters that are already parsed (again all code in the myModule
module):
def main(foo, bar, baz='spam'):
# run with already parsed arguments
if __name__ == '__main__':
import sys
# parse sys.argv[1:] using optparse or argparse or what have you
main(foovalue, barvalue, **dictofoptions)
and import and call myModule.main(foovalue, barvalue, baz='ham')
elsewhere and passing in python arguments as needed.
The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py
) no import
statement is being used, so python calls that module "__main__"
. But if that same filename.py
code is treated as a module (import filename
), then python uses that as the module name instead. In both cases the variable __name__
is set, and testing against that tells you how your code was run.
Creating a class object in c++
In the first case you are creating the object on the heap
using new
.
In the second case you are creating the object on the stack
, so it will be disposed of when going out of scope.
In C++
you'll need to delete objects on the heap
explicitly using delete
when you don't Need them anymore.
To call a static method from a class, do
Singleton* singleton = Singleton::get_sample();
in your main-function or wherever.
combining two string variables
you need to take out the quotes:
soda = a + b
(You want to refer to the variables a
and b
, not the strings "a" and "b")
matplotlib savefig() plots different from show()
You render your matplotlib plots to different devices (e.g., on-screen via Quartz versus to to-file via pdf using different functions (plot versus savefig) whose parameters are nearly the same, yet the default values for those parameters are not the same for both functions.
Put another way, the savefig default parameters are different from the default display parameters.
Aligning them is simple if you do it in the matplotlib config file. The template file is included with the source package, and named matplotlibrc.template. If you did not create one when you installed matplotlib, you can get this template from the matplotlib source, or from the matplotlib website.
Once you have customized this file the way you want, rename it to matplotlibrc (no extension) and save it to the directory .matplotlib (note the leading '.') which should be in your home directory.
The config parameters for saving figures begins at about line 314 in the supplied matplotlibrc.template (first line before this section is: ### SAVING FIGURES).
In particular, you will want to look at these:
savefig.dpi : 100 # figure dots per inch
savefig.facecolor : white # figure facecolor when saving
savefig.edgecolor : white # figure edgecolor when saving
savefig.extension : auto # what extension to use for savefig('foo'), or 'auto'
Below these lines are the settings for font type and various image format-specific parameters.
These same parameters for display, i.e., PLT.show(), begin at about line 277 a in the matplotlibrc.template (this section preceded with the line: ### FIGURE):
figure.figsize : 8, 6
figure.dpi : 80
figure.facecolor : 0.75
figure.edgecolor : white
As you can see by comparing the values of these two blocks of parameters, the default settings for the same figure attribute are different for savefig versus display (show).
SQL Server : check if variable is Empty or NULL for WHERE clause
Just use
If @searchType is null means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType is NULL
If @searchType is an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType = ''
If @searchType is null or an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''
Programmatically scroll a UIScrollView
You can scroll to some point in a scroll view with one of the following statements in Objective-C
[scrollView setContentOffset:CGPointMake(x, y) animated:YES];
or Swift
scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)
See the guide "Scrolling the Scroll View Content" from Apple as well.
To do slideshows with UIScrollView
, you arrange all images in the scroll view, set up a repeated timer, then -setContentOffset:animated:
when the timer fires.
But a more efficient approach is to use 2 image views and swap them using transitions or simply switching places when the timer fires. See iPhone Image slideshow for details.
Get HTML source of WebElement in Selenium WebDriver using Python
Using the attribute method is, in fact, easier and more straightforward.
Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be element.attribute(Class)
.
The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the string of an element, element.attribute(String)
.
Computational complexity of Fibonacci Sequence
Just ask yourself how many statements need to execute for F(n)
to complete.
For F(1)
, the answer is 1
(the first part of the conditional).
For F(n)
, the answer is F(n-1) + F(n-2)
.
So what function satisfies these rules? Try an (a > 1):
an == a(n-1) + a(n-2)
Divide through by a(n-2):
a2 == a + 1
Solve for a
and you get (1+sqrt(5))/2 = 1.6180339887
, otherwise known as the golden ratio.
So it takes exponential time.
Propagate all arguments in a bash shell script
If you include $@
in a quoted string with other characters the behavior is very odd when there are multiple arguments, only the first argument is included inside the quotes.
Example:
#!/bin/bash
set -x
bash -c "true foo $@"
Yields:
$ bash test.sh bar baz
+ bash -c 'true foo bar' baz
But assigning to a different variable first:
#!/bin/bash
set -x
args="$@"
bash -c "true foo $args"
Yields:
$ bash test.sh bar baz
+ args='bar baz'
+ bash -c 'true foo bar baz'
writing to serial port from linux command line
SCREEN:
NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo
or printf
I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)
You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:
screen /dev/ttyS0 19200,cs8
(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.
ECHO:
Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0
) while I was sending the echo command.
PRINTF:
I found that one can also use printf's '%x' command:
c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT
Again, for printf, start cat < /dev/ttyS0
before sending the command.
Android View shadow
I know this question has already been answered but I want you to know that I found a drawable
on Android Studio
that is very similar to the pics you have in the question:
Take a look at this:
android:background="@drawable/abc_menu_dropdown_panel_holo_light"
It looks like this:
Hope it will be helpful
Edit
The option above is for the older versions of Android Studio
so you may not find it. For newer versions:
android:background="@android:drawable/dialog_holo_light_frame"
Moreover, if you want to have your own custom shape, I suggest to use a drawing software like Photoshop
and draw it.
Don't forget to save it as .9.png
file (example: my_background.9.png
)
Read the documentation: Draw 9-patch
Edit 2
An even better and less hard working solution is to use a CardView
and set app:cardPreventCornerOverlap="false"
to prevent views to overlap the borders:
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="2dp"
app:cardElevation="2dp"
app:cardPreventCornerOverlap="false"
app:contentPadding="0dp">
<!-- your layout stuff here -->
</android.support.v7.widget.CardView>
Also make sure to have included the latest version in the build.gradle
, current is
compile 'com.android.support:cardview-v7:26.0.0'
Is there a way to detach matplotlib plots so that the computation can continue?
On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using 'pick_event' callbacks) before continuing.
In order to block execution until the plot window is closed, I used the following:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)
# set processing to continue when window closed
def onclose(event):
fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)
fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed
# continue with further processing, perhaps using result from callbacks
Note, however, that canvas.start_event_loop_default() produced the following warning:
C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
warnings.warn(str,DeprecationWarning)
although the script still ran.
Is it bad practice to use break to exit a loop in Java?
While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.
How to get TimeZone from android mobile?
Simplest Solution With Simple Date Format:
SimpleDateFormat("ZZZZZ"):
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("ZZZZZ",Locale.getDefault());
String localTime = date.format(currentLocalTime);
System.out.println(localTime+ " TimeZone " );
==> Output is : +05:30
What's the best way to limit text length of EditText in Android
XML
android:maxLength="10"
Programmatically:
int maxLength = 10;
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(maxLength);
yourEditText.setFilters(filters);
Note: internally, EditText & TextView parse the value of android:maxLength
in XML and use InputFilter.LengthFilter()
to apply it.
See: TextView.java#L1564
Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"
I had a similar issue, my error was:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]
I use jboss
and glassfish
so I changed the web.xml
to the following:
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
Instead of:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
Hope this work for you.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Hunk #1 FAILED at 1. What's that mean?
In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.
To patch despite those differences, it's possible to use the following two arguments :
--ignore-whitespace : It ignores whitespace differences (indentation, etc).
--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.
Don't forget to user "--dry-run" : It'll try the patch without applying it.
Example :
patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch
More informations about Fuzz :
https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html
Populating spinner directly in the layout xml
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Load local HTML file in a C# WebBrowser
Note that the file:///
scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));
Can I force a UITableView to hide the separator between empty cells?
The following worked very well for me for this problem:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
CGRect frame = [self.view frame];
frame.size.height = frame.size.height - (kTableRowHeight * numberOfRowsInTable);
UIView *footerView = [[UIView alloc] initWithFrame:frame];
return footerView; }
Where kTableRowHeight is the height of my row cells and numberOfRowsInTable is the number of rows I had in the table.
Hope that helps,
Brenton.
Git pull - Please move or remove them before you can merge
If you are getting error like
- branch master -> FETCH_HEAD
error: The following untracked working tree files would be overwritten by merge:
src/dj/abc.html
Please move or remove them before you merge.
Aborting
Try removing the above file manually(Careful). Git will merge this file from master branch.
Syntax error near unexpected token 'fi'
As well as having then
on a new line, you also need a space before and after the [
, which is a special symbol in BASH.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [ $((fname % 2)) -eq 1 ]
then
echo "removing $fname\n"
rm "$f"
fi
done
Adding an .env file to React Project
You have to install npm install env-cmd
Make .env in the root directory and update like this & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_NODE_ENV="production"
REACT_APP_DB="http://localhost:5000"
Update package.json
"scripts": {
"start": "env-cmd react-scripts start",
"build": "env-cmd react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Get the current displaying UIViewController on the screen in AppDelegate.m
You could also post a notification via NSNotificationCenter. This let's you deal with a number of situations where traversing the view controller hierarchy might be tricky - for example when modals are being presented, etc.
E.g.,
// MyAppDelegate.h
NSString * const UIApplicationDidReceiveRemoteNotification;
// MyAppDelegate.m
NSString * const UIApplicationDidReceiveRemoteNotification = @"UIApplicationDidReceiveRemoteNotification";
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationDidReceiveRemoteNotification
object:self
userInfo:userInfo];
}
In each of your View Controllers:
-(void)viewDidLoad {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(didReceiveRemoteNotification:)
name:UIApplicationDidReceiveRemoteNotification
object:nil];
}
-(void)viewDidUnload {
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:UIApplicationDidReceiveRemoteNotification
object:nil];
}
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
// see http://stackoverflow.com/a/2777460/305149
if (self.isViewLoaded && self.view.window) {
// handle the notification
}
}
You could also use this approach to instrument controls which need to update when a notification is received and are used by several view controllers. In that case, handle the add/remove observer calls in the init and dealloc methods, respectively.
How to start new activity on button click
Take Button in xml first.
<Button
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
android:text="Your Text"
/>
Make listner of button.
pre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
How to resize Image in Android?
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file
How do you check current view controller class in Swift?
let viewControllers = navController?.viewControllers
for aViewController in viewControllers! {
if aViewController .isKind(of: (MyClass?.classForCoder)!) {
_ = navController?.popToViewController(aViewController, animated: true)
}
}
SQL update trigger only when column is modified
One should check if QtyToRepair
is updated at first.
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (QtyToRepair)
BEGIN
UPDATE SCHEDULE
SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S INNER JOIN Inserted I
ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
Efficiently replace all accented characters in a string?
For the lads using TypeScript and those who don't want to deal with string prototypes, here is a typescript version of Ed.'s answer:
// Usage example:
"Some string".replace(/[^a-zA-Z0-9-_]/g, char => ToLatinMap.get(char) || '')
// Map:
export let ToLatinMap: Map<string, string> = new Map<string, string>([
["Á", "A"],
["A", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["A", "A"],
["Â", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["Ä", "A"],
["A", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["À", "A"],
["?", "A"],
["?", "A"],
["A", "A"],
["A", "A"],
["Å", "A"],
["?", "A"],
["?", "A"],
["?", "A"],
["Ã", "A"],
["?", "AA"],
["Æ", "AE"],
["?", "AE"],
["?", "AE"],
["?", "AO"],
["?", "AU"],
["?", "AV"],
["?", "AV"],
["?", "AY"],
["?", "B"],
["?", "B"],
["?", "B"],
["?", "B"],
["?", "B"],
["?", "B"],
["C", "C"],
["C", "C"],
["Ç", "C"],
["?", "C"],
["C", "C"],
["C", "C"],
["?", "C"],
["?", "C"],
["D", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["?", "D"],
["Ð", "D"],
["?", "D"],
["?", "DZ"],
["?", "DZ"],
["É", "E"],
["E", "E"],
["E", "E"],
["?", "E"],
["?", "E"],
["Ê", "E"],
["?", "E"],
["?", "E"],
["?", "E"],
["?", "E"],
["?", "E"],
["?", "E"],
["Ë", "E"],
["E", "E"],
["?", "E"],
["?", "E"],
["È", "E"],
["?", "E"],
["?", "E"],
["E", "E"],
["?", "E"],
["?", "E"],
["E", "E"],
["?", "E"],
["?", "E"],
["?", "E"],
["?", "ET"],
["?", "F"],
["ƒ", "F"],
["?", "G"],
["G", "G"],
["G", "G"],
["G", "G"],
["G", "G"],
["G", "G"],
["?", "G"],
["?", "G"],
["G", "G"],
["?", "H"],
["?", "H"],
["?", "H"],
["H", "H"],
["?", "H"],
["?", "H"],
["?", "H"],
["?", "H"],
["H", "H"],
["Í", "I"],
["I", "I"],
["I", "I"],
["Î", "I"],
["Ï", "I"],
["?", "I"],
["I", "I"],
["?", "I"],
["?", "I"],
["Ì", "I"],
["?", "I"],
["?", "I"],
["I", "I"],
["I", "I"],
["I", "I"],
["I", "I"],
["?", "I"],
["?", "D"],
["?", "F"],
["?", "G"],
["?", "R"],
["?", "S"],
["?", "T"],
["?", "IS"],
["J", "J"],
["?", "J"],
["?", "K"],
["K", "K"],
["K", "K"],
["?", "K"],
["?", "K"],
["?", "K"],
["?", "K"],
["?", "K"],
["?", "K"],
["?", "K"],
["L", "L"],
["?", "L"],
["L", "L"],
["L", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["?", "L"],
["L", "L"],
["?", "LJ"],
["?", "M"],
["?", "M"],
["?", "M"],
["?", "M"],
["N", "N"],
["N", "N"],
["N", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["?", "N"],
["Ñ", "N"],
["?", "NJ"],
["Ó", "O"],
["O", "O"],
["O", "O"],
["Ô", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["Ö", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["O", "O"],
["?", "O"],
["Ò", "O"],
["?", "O"],
["O", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["O", "O"],
["?", "O"],
["?", "O"],
["O", "O"],
["O", "O"],
["O", "O"],
["Ø", "O"],
["?", "O"],
["Õ", "O"],
["?", "O"],
["?", "O"],
["?", "O"],
["?", "OI"],
["?", "OO"],
["?", "E"],
["?", "O"],
["?", "OU"],
["?", "P"],
["?", "P"],
["?", "P"],
["?", "P"],
["?", "P"],
["?", "P"],
["?", "P"],
["?", "Q"],
["?", "Q"],
["R", "R"],
["R", "R"],
["R", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "R"],
["?", "C"],
["?", "E"],
["S", "S"],
["?", "S"],
["Š", "S"],
["?", "S"],
["S", "S"],
["S", "S"],
["?", "S"],
["?", "S"],
["?", "S"],
["?", "S"],
["T", "T"],
["T", "T"],
["?", "T"],
["?", "T"],
["?", "T"],
["?", "T"],
["?", "T"],
["?", "T"],
["?", "T"],
["T", "T"],
["T", "T"],
["?", "A"],
["?", "L"],
["?", "M"],
["?", "V"],
["?", "TZ"],
["Ú", "U"],
["U", "U"],
["U", "U"],
["Û", "U"],
["?", "U"],
["Ü", "U"],
["U", "U"],
["U", "U"],
["U", "U"],
["U", "U"],
["?", "U"],
["?", "U"],
["U", "U"],
["?", "U"],
["Ù", "U"],
["?", "U"],
["U", "U"],
["?", "U"],
["?", "U"],
["?", "U"],
["?", "U"],
["?", "U"],
["?", "U"],
["U", "U"],
["?", "U"],
["U", "U"],
["U", "U"],
["U", "U"],
["?", "U"],
["?", "U"],
["?", "V"],
["?", "V"],
["?", "V"],
["?", "V"],
["?", "VY"],
["?", "W"],
["W", "W"],
["?", "W"],
["?", "W"],
["?", "W"],
["?", "W"],
["?", "W"],
["?", "X"],
["?", "X"],
["Ý", "Y"],
["Y", "Y"],
["Ÿ", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["?", "Y"],
["Z", "Z"],
["Ž", "Z"],
["?", "Z"],
["?", "Z"],
["Z", "Z"],
["?", "Z"],
["?", "Z"],
["?", "Z"],
["?", "Z"],
["?", "IJ"],
["Œ", "OE"],
["?", "A"],
["?", "AE"],
["?", "B"],
["?", "B"],
["?", "C"],
["?", "D"],
["?", "E"],
["?", "F"],
["?", "G"],
["?", "G"],
["?", "H"],
["?", "I"],
["?", "R"],
["?", "J"],
["?", "K"],
["?", "L"],
["?", "L"],
["?", "M"],
["?", "N"],
["?", "O"],
["?", "OE"],
["?", "O"],
["?", "OU"],
["?", "P"],
["?", "R"],
["?", "N"],
["?", "R"],
["?", "S"],
["?", "T"],
["?", "E"],
["?", "R"],
["?", "U"],
["?", "V"],
["?", "W"],
["?", "Y"],
["?", "Z"],
["á", "a"],
["a", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["a", "a"],
["â", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["ä", "a"],
["a", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["à", "a"],
["?", "a"],
["?", "a"],
["a", "a"],
["a", "a"],
["?", "a"],
["?", "a"],
["å", "a"],
["?", "a"],
["?", "a"],
["?", "a"],
["ã", "a"],
["?", "aa"],
["æ", "ae"],
["?", "ae"],
["?", "ae"],
["?", "ao"],
["?", "au"],
["?", "av"],
["?", "av"],
["?", "ay"],
["?", "b"],
["?", "b"],
["?", "b"],
["?", "b"],
["?", "b"],
["?", "b"],
["b", "b"],
["?", "b"],
["?", "o"],
["c", "c"],
["c", "c"],
["ç", "c"],
["?", "c"],
["c", "c"],
["?", "c"],
["c", "c"],
["?", "c"],
["?", "c"],
["d", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["?", "d"],
["d", "d"],
["?", "d"],
["?", "d"],
["i", "i"],
["?", "j"],
["?", "j"],
["?", "j"],
["?", "dz"],
["?", "dz"],
["é", "e"],
["e", "e"],
["e", "e"],
["?", "e"],
["?", "e"],
["ê", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["ë", "e"],
["e", "e"],
["?", "e"],
["?", "e"],
["è", "e"],
["?", "e"],
["?", "e"],
["e", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["e", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["?", "e"],
["?", "et"],
["?", "f"],
["ƒ", "f"],
["?", "f"],
["?", "f"],
["?", "g"],
["g", "g"],
["g", "g"],
["g", "g"],
["g", "g"],
["g", "g"],
["?", "g"],
["?", "g"],
["?", "g"],
["g", "g"],
["?", "h"],
["?", "h"],
["?", "h"],
["h", "h"],
["?", "h"],
["?", "h"],
["?", "h"],
["?", "h"],
["?", "h"],
["?", "h"],
["h", "h"],
["?", "hv"],
["í", "i"],
["i", "i"],
["i", "i"],
["î", "i"],
["ï", "i"],
["?", "i"],
["?", "i"],
["?", "i"],
["ì", "i"],
["?", "i"],
["?", "i"],
["i", "i"],
["i", "i"],
["?", "i"],
["?", "i"],
["i", "i"],
["?", "i"],
["?", "d"],
["?", "f"],
["?", "g"],
["?", "r"],
["?", "s"],
["?", "t"],
["?", "is"],
["j", "j"],
["j", "j"],
["?", "j"],
["?", "j"],
["?", "k"],
["k", "k"],
["k", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["?", "k"],
["l", "l"],
["l", "l"],
["?", "l"],
["l", "l"],
["l", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["?", "l"],
["l", "l"],
["?", "lj"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "m"],
["?", "m"],
["?", "m"],
["?", "m"],
["?", "m"],
["?", "m"],
["n", "n"],
["n", "n"],
["n", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["?", "n"],
["ñ", "n"],
["?", "nj"],
["ó", "o"],
["o", "o"],
["o", "o"],
["ô", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["ö", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["o", "o"],
["?", "o"],
["ò", "o"],
["?", "o"],
["o", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["o", "o"],
["?", "o"],
["?", "o"],
["o", "o"],
["o", "o"],
["ø", "o"],
["?", "o"],
["õ", "o"],
["?", "o"],
["?", "o"],
["?", "o"],
["?", "oi"],
["?", "oo"],
["?", "e"],
["?", "e"],
["?", "o"],
["?", "o"],
["?", "ou"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "p"],
["?", "q"],
["?", "q"],
["?", "q"],
["?", "q"],
["r", "r"],
["r", "r"],
["r", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "c"],
["?", "c"],
["?", "e"],
["?", "r"],
["s", "s"],
["?", "s"],
["š", "s"],
["?", "s"],
["s", "s"],
["s", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["?", "s"],
["g", "g"],
["?", "o"],
["?", "o"],
["?", "u"],
["t", "t"],
["t", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["?", "t"],
["t", "t"],
["?", "t"],
["t", "t"],
["?", "th"],
["?", "a"],
["?", "ae"],
["?", "e"],
["?", "g"],
["?", "h"],
["?", "h"],
["?", "h"],
["?", "i"],
["?", "k"],
["?", "l"],
["?", "m"],
["?", "m"],
["?", "oe"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "r"],
["?", "t"],
["?", "v"],
["?", "w"],
["?", "y"],
["?", "tz"],
["ú", "u"],
["u", "u"],
["u", "u"],
["û", "u"],
["?", "u"],
["ü", "u"],
["u", "u"],
["u", "u"],
["u", "u"],
["u", "u"],
["?", "u"],
["?", "u"],
["u", "u"],
["?", "u"],
["ù", "u"],
["?", "u"],
["u", "u"],
["?", "u"],
["?", "u"],
["?", "u"],
["?", "u"],
["?", "u"],
["?", "u"],
["u", "u"],
["?", "u"],
["u", "u"],
["?", "u"],
["u", "u"],
["u", "u"],
["?", "u"],
["?", "u"],
["?", "ue"],
["?", "um"],
["?", "v"],
["?", "v"],
["?", "v"],
["?", "v"],
["?", "v"],
["?", "v"],
["?", "v"],
["?", "vy"],
["?", "w"],
["w", "w"],
["?", "w"],
["?", "w"],
["?", "w"],
["?", "w"],
["?", "w"],
["?", "w"],
["?", "x"],
["?", "x"],
["?", "x"],
["ý", "y"],
["y", "y"],
["ÿ", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["?", "y"],
["z", "z"],
["ž", "z"],
["?", "z"],
["?", "z"],
["?", "z"],
["z", "z"],
["?", "z"],
["?", "z"],
["?", "z"],
["?", "z"],
["?", "z"],
["?", "z"],
["z", "z"],
["?", "z"],
["?", "ff"],
["?", "ffi"],
["?", "ffl"],
["?", "fi"],
["?", "fl"],
["?", "ij"],
["œ", "oe"],
["?", "st"],
["?", "a"],
["?", "e"],
["?", "i"],
["?", "j"],
["?", "o"],
["?", "r"],
["?", "u"],
["?", "v"],
["?", "x"],
]);
Grep only the first match and stop
You can pipe grep
result to head
in conjunction with stdbuf.
Note, that in order to ensure stopping after Nth match, you need to using stdbuf
to make sure grep
don't buffer its output:
stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1
As soon as head
consumes 1 line, it terminated and grep
will receive SIGPIPE
because it still output something to pipe while head
was gone.
This assumed that no file names contain newline.
How to process SIGTERM signal gracefully?
First, I'm not certain that you need a second thread to set the shutdown_flag
.
Why not set it directly in the SIGTERM handler?
An alternative is to raise an exception from the SIGTERM
handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with
/contextmanager
and try: ... finally:
blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.
Example program signals-test.py
:
#!/usr/bin/python
from time import sleep
import signal
import sys
def sigterm_handler(_signo, _stack_frame):
# Raises SystemExit(0):
sys.exit(0)
if sys.argv[1] == "handle_signal":
signal.signal(signal.SIGTERM, sigterm_handler)
try:
print "Hello"
i = 0
while True:
i += 1
print "Iteration #%i" % i
sleep(1)
finally:
print "Goodbye"
Now see the Ctrl+C behaviour:
$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
File "./signals-test.py", line 21, in <module>
sleep(1)
KeyboardInterrupt
$ echo $?
1
This time I send it SIGTERM
after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}')
:
$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143
This time I enable my custom SIGTERM
handler and send it SIGTERM
:
$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0
Creating table variable in SQL server 2008 R2
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
Why is 1/1/1970 the "epoch time"?
History.
The earliest versions of Unix time had
a 32-bit integer incrementing at a
rate of 60 Hz, which was the rate of
the system clock on the hardware of
the early Unix systems. The value 60
Hz still appears in some software
interfaces as a result. The epoch also
differed from the current value. The
first edition Unix Programmer's Manual
dated November 3, 1971 defines the
Unix time as "the time since 00:00:00,
Jan. 1, 1971, measured in sixtieths of
a second".
Can lambda functions be templated?
C++11 lambdas can't be templated as stated in other answers but decltype()
seems to help when using a lambda within a templated class or function.
#include <iostream>
#include <string>
using namespace std;
template<typename T>
void boring_template_fn(T t){
auto identity = [](decltype(t) t){ return t;};
std::cout << identity(t) << std::endl;
}
int main(int argc, char *argv[]) {
std::string s("My string");
boring_template_fn(s);
boring_template_fn(1024);
boring_template_fn(true);
}
Prints:
My string
1024
1
I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.
How to get content body from a httpclient call?
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
accessing a docker container from another container
It's easy.
If you have two or more running container, complete next steps:
docker network create myNetwork
docker network connect myNetwork web1
docker network connect myNetwork web2
Now you connect from web1 to web2 container or the other way round.
Use the internal network IP addresses which you can find by running:
docker network inspect myNetwork
Note that only internal IP addresses and ports are accessible to the containers connected by the network bridge.
So for example assuming that web1 container was started with: docker run -p 80:8888 web1
(meaning that its server is running on port 8888 internally), and inspecting myNetwork
shows that web1's IP is 172.0.0.2, you can connect from web2 to web1 using curl 172.0.0.2:8888
).
How to escape the equals sign in properties files
In your specific example you don't need to escape the equals - you only need to escape it if it's part of the key. The properties file format will treat all characters after the first unescaped equals as part of the value.
Forgot Oracle username and password, how to retrieve?
Open your SQL command line and type the following:
SQL> connect / as sysdba
Once connected,you can enter the following query to get details of username and password:
SQL> select username,password from dba_users;
This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user.
For changing the password,use the below query:
SQL> alter user username identified by password;
Here username is the name of user whose password you want to change and password is the new password.
Getting all files in directory with ajax
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?
Here is a solutions for MAC PC:
Open terminal and type following command to show hidden files:
defaults write com.apple.finder AppleShowAllFiles YES
after that go to current user folder using finder, then you can see the Library folder in it which is hidden type
suppose in my case the username is 'Delta' so the folder path is:
OS X: ~Delta/Library/Preferences/SmartGit/<main-smartgit-version>
Remove settings file and change option to Non Commercial..
Measuring code execution time
Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTimes to measure execution time in .NET.
How do I declare class-level properties in Objective-C?
Properties have values only in objects, not classes.
If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static
in the implementation file.
You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.
Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool
in Cocoa.
wait() or sleep() function in jquery?
xml4jQuery plugin gives sleep(ms,callback) method. Remaining chain would be executed after sleep period.
_x000D_
_x000D_
$(".toFill").html("Click here")
.$on('click')
.html('Loading...')
.sleep(1000)
.html( 'done')
.toggleClass('clickable')
.prepend('Still clickable <hr/>');
_x000D_
.toFill{border: dashed 2px palegreen; border-radius: 1em; display: inline-block;padding: 1em;}
.clickable{ cursor: pointer; border-color: blue;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.xml4jquery.com/ajax/libs/xml4jquery/1.1.2/xml4jquery.js"></script>
<div class="toFill clickable"></div>
_x000D_
_x000D_
_x000D_
ASP.NET Identity reset password
In current release
Assuming you have handled the verification of the request to reset the forgotten password, use following code as a sample code steps.
ApplicationDbContext =new ApplicationDbContext()
String userId = "<YourLogicAssignsRequestedUserId>";
String newPassword = "<PasswordAsTypedByUser>";
ApplicationUser cUser = UserManager.FindById(userId);
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
store.SetPasswordHashAsync(cUser, hashedNewPassword);
In AspNet Nightly Build
The framework is updated to work with Token for handling requests like ForgetPassword. Once in release, simple code guidance is expected.
Update:
This update is just to provide more clear steps.
ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
String userId = User.Identity.GetUserId();//"<YourLogicAssignsRequestedUserId>";
String newPassword = "test@123"; //"<PasswordAsTypedByUser>";
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
ApplicationUser cUser = await store.FindByIdAsync(userId);
await store.SetPasswordHashAsync(cUser, hashedNewPassword);
await store.UpdateAsync(cUser);
Rotating x axis labels in R for barplot
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
Trim last character from a string
An example Extension class to simplify this: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
Usage
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
What determines the monitor my app runs on?
Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.
So I am not sure there is a way to tell every program where to open. Hope that helps some.
using setTimeout on promise chain
To keep the promise chain going, you can't use setTimeout()
the way you did because you aren't returning a promise from the .then()
handler - you're returning it from the setTimeout()
callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then()
handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x)
method on your promises like this:
_x000D_
_x000D_
function delay(t, v) {_x000D_
return new Promise(function(resolve) { _x000D_
setTimeout(resolve.bind(null, v), t)_x000D_
});_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
return this.then(function(v) {_x000D_
return delay(t, v);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
console.log(v);_x000D_
});
_x000D_
_x000D_
_x000D_
Or, use the Bluebird promise library which already has the .delay()
method built-in.
How do I release memory used by a pandas dataframe?
It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659
The monkey patch detailed on this issue has resolved the problem for me:
# monkeypatches.py
# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
libc.malloc_trim(0)
except (OSError, AttributeError):
libc = None
__old_del = getattr(pd.DataFrame, '__del__', None)
def __new_del(self):
if __old_del:
__old_del(self)
libc.malloc_trim(0)
if libc:
print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
pd.DataFrame.__del__ = __new_del
else:
print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)
Debugging iframes with Chrome developer tools
Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.
Update: This is no longer true. See Metagrapher's answer.
Eclipse/Maven error: "No compiler is provided in this environment"
In my case, I had created a run configuration and whenever I tried to run it, the error would be displayed. After searching on some websites, I edited the run configuration and under JRE tab, selected the runtime JRE as 'workspace default JRE' which I had already configured to point to my local Java JDK installation (ex. C:\Program Files (x86)\Java\jdk1.8.0_51). This solved my issue. Maybe it helps someone out there.
Enter key pressed event handler
The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.
One can get special keys like ENTER by overriding the IsInputKey method:
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
Then one can use the KeyDown event in the following way:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
java.math.BigInteger cannot be cast to java.lang.Integer
As we see from the javaDoc, BigInteger
is not a subclass of Integer
:
java.lang.Object java.lang.Object
java.lang.Number java.lang.Number
java.math.BigInteger java.lang.Integer
And that's the reason why casting from BigInteger
to Integer
is impossible.
Casting of java primitives will do some conversion (like casting from double
to int
) while casting of types will never transform classes.
Presenting modal in iOS 13 fullscreen
Latest for iOS 13 and Swift 5.x
let vc = ViewController(nibName: "ViewController", bundle: nil)
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
Best way to track onchange as-you-type in input type="text"?
To track each try this example and before that completely reduce cursor blink rate to zero.
_x000D_
_x000D_
<body>_x000D_
//try onkeydown,onkeyup,onkeypress_x000D_
<input type="text" onkeypress="myFunction(this.value)">_x000D_
<span> </span>_x000D_
<script>_x000D_
function myFunction(val) {_x000D_
//alert(val);_x000D_
var mySpan = document.getElementsByTagName("span")[0].innerHTML;_x000D_
mySpan += val+"<br>";_x000D_
document.getElementsByTagName("span")[0].innerHTML = mySpan;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
onblur : event generates on exit
onchange : event generates on exit if any changes made in inputtext
onkeydown: event generates on any key press (for key holding long times also)
onkeyup : event generates on any key release
onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other
Call An Asynchronous Javascript Function Synchronously
You can also convert it into callbacks.
function thirdPartyFoo(callback) {
callback("Hello World");
}
function foo() {
var fooVariable;
thirdPartyFoo(function(data) {
fooVariable = data;
});
return fooVariable;
}
var temp = foo();
console.log(temp);
Convert factor to integer
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015
It's recommended to try any or all of the following:
Restart Visual Studio
Try Running As Administrator (right-click Visual Studio and choose "Run As Administrator")
Check for any updates for Visual Studio (download and install them if any are available)
Try opening a different solution / project
If problems persist, you might try the following options:
Restart your local machine
Attempt to reset Visual Studio to System Defaults (this can be done from the options within Visual Studio)
Attempt to repair your Visual Studio installation
jQuery UI Color Picker
That is because you are trying to access the plugin before it's loaded. You should try making a call to it when the DOM is loaded by surrounding it with this:
$(document).ready(function(){
$("#colorpicker").colorpicker();
}
Implement division with bit-wise operator
This solution works perfectly.
#include <stdio.h>
int division(int dividend, int divisor, int origdiv, int * remainder)
{
int quotient = 1;
if (dividend == divisor)
{
*remainder = 0;
return 1;
}
else if (dividend < divisor)
{
*remainder = dividend;
return 0;
}
while (divisor <= dividend)
{
divisor = divisor << 1;
quotient = quotient << 1;
}
if (dividend < divisor)
{
divisor >>= 1;
quotient >>= 1;
}
quotient = quotient + division(dividend - divisor, origdiv, origdiv, remainder);
return quotient;
}
int main()
{
int n = 377;
int d = 7;
int rem = 0;
printf("Quotient : %d\n", division(n, d, d, &rem));
printf("Remainder: %d\n", rem);
return 0;
}
How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
how to show progress bar(circle) in an activity having a listview before loading the listview with data
Please use the sample at tutorialspoint.com. The whole implementation only needs a few lines of code without changing your xml file. Hope this helps.
STEP 1: Import library
import android.app.ProgressDialog;
STEP 2: Declare ProgressDialog global variable
ProgressDialog loading = null;
STEP 3: Start new ProgressDialog and use the following properties (please be informed that this sample only covers the basic circle loading bar without the real time progress status).
loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage(Constant.Message.AuthenticatingUser);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
STEP 4: If you are using AsyncTasks, you can start showing the dialog in onPreExecute method. Otherwise, just place the code in the beginning of your button onClick event.
loading.show();
STEP 5: If you are using AsyncTasks, you can close the progress dialog by placing the code in onPostExecute method. Otherwise, just place the code before closing your button onClick event.
loading.dismiss();
Tested it with my Nexus 5 android v4.0.3. Good luck!
Adding content to a linear layout dynamically?
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
Javascript add method to object
This all depends on how you're creating Foo
, and how you intend to use .bar()
.
First, are you using a constructor-function for your object?
var myFoo = new Foo();
If so, then you can extend the Foo
function's prototype
property with .bar
, like so:
function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };
var myFoo = new Foo();
myFoo.bar();
In this fashion, each instance of Foo
now has access to the SAME instance of .bar
.
To wit: .bar
will have FULL access to this
, but will have absolutely no access to variables
within the constructor function:
function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };
var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
// ...or a value of `secret` in a higher/global scope
In another way, you could define a function to return any object (not this
), with .bar
created as a property of that object:
function giveMeObj () {
var private = 42,
privateBar = function () { console.log(private); },
public_interface = {
bar : privateBar
};
return public_interface;
}
var myObj = giveMeObj();
myObj.bar(); // 42
In this fashion, you have a function which creates new objects.
Each of those objects has a .bar
function created for them.
Each .bar
function has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .bar
still has access to this
as well, as this
, when you call the function like myObj.bar();
will always refer to myObj
(public_interface
, in my example Foo
).
The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar
, which will eat into memory.
You could also do this inside of a constructor function, setting this.bar = function () {};
inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.
So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through this
or myObj.X
)?
and the second question is:
Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?
For example, if you gave every triangle and every texture their own .draw
function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...
If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).
Implicit function declarations in C
Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc)
.
Edit: no, I was wrong about int
for the arguments. Instead it passes whatever type the argument is. So it could be an int
or a double
or a char*
. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.
For more details look up K&R C
.
How to make div same height as parent (displayed as table-cell)
You have to set the height
for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):
.child {
width: 30px;
background-color: red;
display: table-cell;
vertical-align: top;
position:relative;
}
.content {
position:absolute;
top:0;
bottom:0;
width:100%;
background-color: blue;
}
Fiddle
Kill process by name?
import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
p = psutil.Process(i)
p_name=p.name
print str(i)+" "+str(p.name)
if p_name=="PerfExp.exe":
print "*"*20+" mam ho "+"*"*20
p.kill()
How can I get the name of an html page in Javascript?
This will work even if the url ends with a /
:
var segments = window.location.pathname.split('/');
var toDelete = [];
for (var i = 0; i < segments.length; i++) {
if (segments[i].length < 1) {
toDelete.push(i);
}
}
for (var i = 0; i < toDelete.length; i++) {
segments.splice(i, 1);
}
var filename = segments[segments.length - 1];
console.log(filename);
Does bootstrap have builtin padding and margin classes?
I would like to give an example which I tried by understanding above documentation and works correctly.
If you wish to apply 25% padding on left and right sides medium screen size then please use px-md-1.
It works as desired and can similarly follow for other screen sizes. :)
How to add an action to a UIAlertView button using Swift iOS
Swift 3.0 Version of Jake's Answer
// Create the alert controller
let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
Forwarding port 80 to 8080 using NGINX
you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _ your_domain;
location /health {
access_log off;
return 200 "healthy\n";
}
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
How to pass a vector to a function?
Anytime you're tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn't pass a couple of iterators instead. Chances are that by doing so, you'll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).
In this case, of course, there's not much point since the standard library already has perfectly good binary searching, but when/if you write something that's not already there, being able to use it on different types of containers is often quite handy.
Setting user agent of a java URLConnection
Off hand, setting the http.agent
system property to ""
might do the trick (I don't have the code in front of me).
You might get away with:
System.setProperty("http.agent", "");
but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).
The property can also be set through JNLP files (available to applets from 6u10) and on the command line:
-Dhttp.agent=
Or for wrapper commands:
-J-Dhttp.agent=
Set the layout weight of a TextView programmatically
This work for me, and I hope it will work for you also
Set the LayoutParams for the parent view first:
myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.FILL_PARENT));
then set for the TextView (child):
TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT,1f);
//-- set components margins
textViewParam.setMargins(5, 0, 5,0);
myTextView.setLayoutParams(textViewParam);
How to download a file over HTTP?
I agree with Corey, urllib2 is more complete than urllib and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:
import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()
Will work fine. Or, if you don't want to deal with the "response" object you can call read() directly:
import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
In excel how do I reference the current row but a specific column?
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
how to send an array in url request
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Wpf DataGrid Add new row
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
Conversion from 12 hours time to 24 hours time in java
We can solve this by using String Buffer
String s;
static String timeConversion(String s) {
StringBuffer st=new StringBuffer(s);
for(int i=0;i<=st.length();i++){
if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '4');
}else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '5');
}else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '6');
}else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '7');
}else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '8');
}else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '9');
}else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '1');
}else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '2');
}else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '0');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
st.setCharAt(0, '1');
st.setCharAt(1, '2');
}
if(st.charAt(8)=='P'){
st.setCharAt(8,' ');
}else if(st.charAt(8)== 'A'){
st.setCharAt(8,' ');
}
if(st.charAt(9)=='M'){
st.setCharAt(9,' ');
}
}
String result=st.toString();
return result;
}
Window.open as modal popup?
You can try open a modal dialog with html5 and css3, try this code:
_x000D_
_x000D_
.windowModal {_x000D_
position: fixed;_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
background: rgba(0,0,0,0.8);_x000D_
z-index: 99999;_x000D_
opacity:0;_x000D_
-webkit-transition: opacity 400ms ease-in;_x000D_
-moz-transition: opacity 400ms ease-in;_x000D_
transition: opacity 400ms ease-in;_x000D_
pointer-events: none;_x000D_
}_x000D_
.windowModal:target {_x000D_
opacity:1;_x000D_
pointer-events: auto;_x000D_
}_x000D_
_x000D_
.windowModal > div {_x000D_
width: 400px;_x000D_
position: relative;_x000D_
margin: 10% auto;_x000D_
padding: 5px 20px 13px 20px;_x000D_
border-radius: 10px;_x000D_
background: #fff;_x000D_
background: -moz-linear-gradient(#fff, #999);_x000D_
background: -webkit-linear-gradient(#fff, #999);_x000D_
background: -o-linear-gradient(#fff, #999);_x000D_
}_x000D_
.close {_x000D_
background: #606061;_x000D_
color: #FFFFFF;_x000D_
line-height: 25px;_x000D_
position: absolute;_x000D_
right: -12px;_x000D_
text-align: center;_x000D_
top: -10px;_x000D_
width: 24px;_x000D_
text-decoration: none;_x000D_
font-weight: bold;_x000D_
-webkit-border-radius: 12px;_x000D_
-moz-border-radius: 12px;_x000D_
border-radius: 12px;_x000D_
-moz-box-shadow: 1px 1px 3px #000;_x000D_
-webkit-box-shadow: 1px 1px 3px #000;_x000D_
box-shadow: 1px 1px 3px #000;_x000D_
}_x000D_
_x000D_
.close:hover { background: #00d9ff; }
_x000D_
<a href="#divModal">Open Modal Window</a>_x000D_
_x000D_
<div id="divModal" class="windowModal">_x000D_
<div>_x000D_
<a href="#close" title="Close" class="close">X</a>_x000D_
<h2>Modal Dialog</h2>_x000D_
<p>This example shows a modal window without using javascript only using html5 and css3, I try it it¡</p>_x000D_
<p>Using javascript, with new versions of html5 and css3 is not necessary can do whatever we want without using js libraries.</p>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Convert date to datetime in Python
One way to convert from date to datetime that hasn't been mentioned yet:
from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')
Complex nesting of partials and templates
For subsections it's as easy as leveraging strings in ng-include:
<ul id="subNav">
<li><a ng-click="subPage='section1/subpage1.htm'">Sub Page 1</a></li>
<li><a ng-click="subPage='section1/subpage2.htm'">Sub Page 2</a></li>
<li><a ng-click="subPage='section1/subpage3.htm'">Sub Page 3</a></li>
</ul>
<ng-include src="subPage"></ng-include>
Or you can create an object in case you have links to sub pages all over the place:
$scope.pages = { page1: 'section1/subpage1.htm', ... };
<ul id="subNav">
<li><a ng-click="subPage='page1'">Sub Page 1</a></li>
<li><a ng-click="subPage='page2'">Sub Page 2</a></li>
<li><a ng-click="subPage='page3'">Sub Page 3</a></li>
</ul>
<ng-include src="pages[subPage]"></ng-include>
Or you can even use $routeParams
$routeProvider.when('/home', ...);
$routeProvider.when('/home/:tab', ...);
$scope.params = $routeParams;
<ul id="subNav">
<li><a href="#/home/tab1">Sub Page 1</a></li>
<li><a href="#/home/tab2">Sub Page 2</a></li>
<li><a href="#/home/tab3">Sub Page 3</a></li>
</ul>
<ng-include src=" '/home/' + tab + '.html' "></ng-include>
You can also put an ng-controller at the top-most level of each partial
Calculating distance between two geographic locations
I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.
C# example
/// <summary>
/// Calculates the distance between two locations using the Great Circle Distance algorithm
/// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
private static double DistanceBetween(GeoLocation first, GeoLocation second)
{
double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));
double centralAngleBetweenLocationsInRadians = Math.Acos(
Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
Math.Cos(longitudeDifferenceInRadians));
const double earthRadiusInMeters = 6357 * 1000;
return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
}
private static double ToRadians(double degrees)
{
return degrees * Math.PI / 180;
}
how to add the missing RANDR extension
I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.
The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).
New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/
(eg /opt/firefox31/
). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.
Formatting doubles for output in C#
Digits after decimal point
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
Some funny examples
String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);
Git Diff with Beyond Compare
Run these commands for Beyond Compare 3(if the BCompare.exe path is different in your system, please replace it according to yours):
git config --global diff.tool bc3
git config --global difftool.bc3.cmd "\"c:/program files (x86)/beyond compare 3/BCompare.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false
Then use git difftool
Make error: missing separator
In my case error caused next. I've tried to execute commands globally i.e outside of any target.
UPD. To run command globally one must be properly formed. For example command
ln -sf ../../user/curl/$SRC_NAME ./$SRC_NAME
would become:
$(shell ln -sf ../../user/curl/$(SRC_NAME) ./$(SRC_NAME))
Android Studio shortcuts like Eclipse
These are some of the useful shortcuts for Android studio (Windows)
Double Shift - Search EveryWhere
Ctrl + Shift+A - quick command search
Ctrl +N - Find Class (capable of finding internall
classes aswell)
Ctrl +Shift+N - Find File
Alt+F7 - Find Uses (To get the call hierarchy)
Ctrl+B - goto class definition.
Ctrl+LeftClick - goto to symbol(variable, method, class) definition/definition.
Ctrl+Alt+Left - Back
Ctrl+Alt+Right - Right
Shift+f6 - Refactor/Rename
SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
Java Convert GMT/UTC to Local time doesn't work as expected
I also recommend using Joda as mentioned before.
Solving your problem using standard Java Date
objects only can be done as follows:
// **** YOUR CODE **** BEGIN ****
long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String format = "yyyy/MM/dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC (Works Fine)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
+ gmtTime.toString() + "," + gmtTime.getTime());
// **** YOUR CODE **** END ****
// Convert UTC to Local Time
Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
+ fromGmt.toString() + "-" + fromGmt.getTime());
Output:
Local:Tue Oct 15 12:19:40 CEST 2013,1381832380522 --> UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000
UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000 --> Local:Tue Oct 15 12:19:40 CEST 2013-1381832380000
How and where are Annotations used in Java?
It attaches additional information about code by (a) compiler check or (b) code analysis
**
- Following are the Built-in annotations:: 2 types
**
Type 1) Annotations applied to java code:
@Override // gives error if signature is wrong while overriding.
Public boolean equals (Object Obj)
@Deprecated // indicates the deprecated method
Public doSomething()....
@SuppressWarnings() // stops the warnings from printing while compiling.
SuppressWarnings({"unchecked","fallthrough"})
Type 2) Annotations applied to other annotations:
@Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at run-time through reflection.
@Documented - Marks another annotation for inclusion in the documentation.
@Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to
@Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
**
**
http://en.wikipedia.org/wiki/Java_annotation#Custom_annotations
FOR BETTER UNDERSTANDING TRY BELOW LINK:ELABORATE WITH EXAMPLES
http://www.javabeat.net/2007/08/annotations-in-java-5-0/
jquery clear input default value
Just a shorthand
$(document).ready(function() {
$(".input").val("Email Address");
$(".input").on("focus click", function(){
$(this).val("");
});
});
</script>
C# - Print dictionary
More cleaner way using LINQ
var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);
String concatenation: concat() vs "+" operator
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
What is log4j's default log file dumping path
You have copy this sample code from Here,right?
now, as you can see there property
file they have define, have you done same thing?
if not then add below code in your project with property file for log4j
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
make changes as per your requirement like log
path
Express-js can't GET my static files, why?
Webpack makes things awkward
As a supplement to all the other already existing solutions:
First things first: If you base the paths of your files and directories on the cwd
(current working directory), things should work as usual, as the cwd
is the folder where you were when you started node
(or npm start
, yarn run
etc).
However...
If you are using webpack, __dirname
behavior will be very different, depending on your node.__dirname
settings, and your webpack version:
- In Webpack v4, the default behavior for
__dirname
is just /
, as documented here.
- In Webpack v5, per the documentation here, the default is already for
__filename
and __dirname
to behave as-is but for the output file, thereby achieving the same result as the config change for v4.
Example
For example, let's say:
- you want to add the static
public
folder
- it is located next to your output (usually
dist
) folder, and you have no sub-folders in dist
, it's probably going to look like this
const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))
(important: again, this is independent of where your source file is, only looks at where your output files are!)
More advanced Webpack scenarios
Things get more complicated if you have multiple entry points in different output directories, as the __dirname
for the same file might be different for output file (that is each file in entry
), depending on the location of the output file that this source file was merged into, and what's worse, the same source file might be merged into multiple different output files.
You probably want to avoid this kind of scenario scenario, or, if you cannot avoid it, use Webpack to manage and infuse the correct paths for you, possibly via the DefinePlugin
or the EnvironmentPlugin
.
jQuery - Sticky header that shrinks when scrolling down
Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).
Here is my solution, throttling the js scroll event (usefull for mobile devices)
JS:
$(function() {
var $document, didScroll, offset;
offset = $('.menu').position().top;
$document = $(document);
didScroll = false;
$(window).on('scroll touchmove', function() {
return didScroll = true;
});
return setInterval(function() {
if (didScroll) {
$('.menu').toggleClass('fixed', $document.scrollTop() > offset);
return didScroll = false;
}
}, 250);
});
CSS:
.menu {
background: pink;
top: 5px;
}
.fixed {
width: 100%;
position: fixed;
top: 0;
}
HTML:
<div class="menu">MENU FIXED ON TOP</div>
http://codepen.io/anon/pen/BgqHw
convert epoch time to date
Please take care that the epoch time is in second and Date object accepts Long value which is in milliseconds.
Hence you would have to multiply epoch value with 1000 to use it as long value .
Like below :-
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
Long dateLong=Long.parseLong(sdf.format(epoch*1000));
How can I create directories recursively?
a fresh answer to a very old question:
starting from python 3.2 you can do this:
import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)
thanks to the exist_ok
flag this will not even complain if the directory exists (depending on your needs....).
starting from python 3.4 (which includes the pathlib module) you can do this:
from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)
starting from python 3.5 mkdir
also has an exist_ok
flag - setting it to True
will raise no exception if the directory exists:
path.mkdir(parents=True, exist_ok=True)