Flask ImportError: No Module Named Flask
The simplest answer to this problem is specifying the correct path to flask in your environment. Make sure the script you are running knows how to get to the flask installation. Using print(sys.path) as mentioned above certainly helped to figure out the path(s) the script was using.
How can I get input radio elements to horizontally align?
In your case, you just need to remove the line breaks (<br>
tags) between the elements - input
elements are inline-block
by default (in Chrome at least). (updated example).
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
I'd suggest using <label>
elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>
's for
attribute with the <input>
's id
: (example)
<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>
<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>
<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>
..or wrap the <label>
elements around the <input>
elements directly: (example)
<label>
<input type="radio" name="editList" value="always"/>Always
</label>
<label>
<input type="radio" name="editList" value="never"/>Never
</label>
<label>
<input type="radio" name="editList" value="costChange"/>Cost Change
</label>
You can also get fancy and use the :checked
pseudo class.
How can I label points in this scatterplot?
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
How to convert LINQ query result to List?
List<course> = (from c in obj.tbCourses
select
new course(c)).toList();
You can convert the entity object to a list directly on the call. There are methods to converting it to different data struct (list, array, dictionary, lookup, or string)
How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster")
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
else
cLayout = "~/Views/Shared/_Layout.cshtml";
Layout = cLayout;
}
Read Complete Article here "How to Render different Layout in ASP.NET MVC"
Metadata file '.dll' could not be found
In my case, I solved this problem after noticing that I had referenced a .Net Framework 4.7 project as a dependency on a .Net Framework 4.6.1 project. After migrating project 4.7 to 4.6.1 my application compiled normally
How to capitalize first letter of each word, like a 2-word city?
There's a good answer here:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
How to get the width of a react element
This could be handled perhaps in a simpler way by using callback refs.
React allows you to pass a function into a ref, which returns the underlying DOM element or component node. See: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
const MyComponent = () => {
const myRef = node => console.log(node ? node.innerText : 'NULL!');
return <div ref={myRef}>Hello World</div>;
}
This function gets fired whenever the underlying node is changed. It will be null in-between updates, so we need to check for this. Example:
const MyComponent = () => {
const [time, setTime] = React.useState(123);
const myRef = node => console.log(node ? node.innerText : 'NULL!');
setTimeout(() => setTime(time+1), 1000);
return <div ref={myRef}>Hello World {time}</div>;
}
/*** Console output:
Hello World 123
NULL!
Hello World 124
NULL!
...etc
***/
While this does't handle resizing as such (we would still need a resize listener to handle the user resizing the window) I'm not sure that is what the OP was asking for. And this version will handle the node resizing due to an update.
So here is a custom hook based on this idea:
export const useClientRect = () => {
const [rect, setRect] = useState({width:0, height:0});
const ref = useCallback(node => {
if (node !== null) {
const { width, height } = node.getBoundingClientRect();
setRect({ width, height });
}
}, []);
return [rect, ref];
};
The above is based on https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
Note the hook returns a ref callback, instead of being passed a ref. And we employ useCallback to avoid re-creating a new ref function each time; not vital, but considered good practice.
Usage is like this (based on Marco Antônio's example):
const MyComponent = ({children}) => {
const [rect, myRef] = useClientRect();
const { width, height } = rect;
return (
<div ref={myRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
{children}
<div/>
)
}
What is WebKit and how is it related to CSS?
Addition to what @KennyTM said:
- IE
- Edge
- Firefox
- Engine: Gecko
- CSS-prefix:
-moz
- Opera
- Engine:
Presto ? Blink1
- CSS-prefix:
-o
(Presto) and -webkit
(Blink)
- Safari
- Engine: WebKit
- CSS-prefix:
-webkit
- Chrome
1) On February 12 2013 Opera (version 15+) announces they moving away from their own engine Presto to WebKit named Blink.
2) On April 3 2013 Google (Chrome version 28+) announces they are going to use the WebKit-based Blink engine.
3) On December 6 2018 Microsoft (Microsoft Edge 79+ stable) announces they are going to use the WebKit-based Blink engine.
How to serialize an object into a string
Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
import java.util.Optional;
final class ObjectHelper {
private ObjectHelper() {}
static Optional<String> convertToString(final Serializable object) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(object);
return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));
} catch (final IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {
final byte[] data = Base64.getDecoder().decode(objectAsString);
try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
return Optional.of((T) ois.readObject());
} catch (final IOException | ClassNotFoundException e) {
e.printStackTrace();
return Optional.empty();
}
}
}
Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration
I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace.
I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!
what a trial converting from website to web application project can be!
Why does the Google Play store say my Android app is incompatible with my own device?
To give an extra solution to the above 'This app is incompatible with your...' problem, let me share my solution for a different problem cause. I tried installing an app on a low-end Samsung Galaxy Y (GT-S6350) device and got this error from the Play store. To test various AndroidManifest configurations, I created an account and followed the routine as described in https://stackoverflow.com/a/5449397/372838 until my device showed up in the supported device list.
It turned out that a lot of devices become incompatible when you use the Camera permission:
<uses-permission android:name="android.permission.CAMERA" />
When I removed that specific permission, the application was available for 1180 devices instead of 870. Hope it will help someone
Edit existing excel workbooks and sheets with xlrd and xlwt
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
Convert string with commas to array
use the built-in map function with an anonymous function, like so:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
How to define unidirectional OneToMany relationship in JPA
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
Cant get text of a DropDownList in code - can get value but not text
add list using
<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>
and then try
DropDownList1.SelectedItem.Text
I found your mistake.
<asp:ListItem>United States</asp:ListItem>
change this to
<asp:ListItem>United States1</asp:ListItem>
Then you will got the actual value.
What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected
How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
Unable to create Genymotion Virtual Device
I followed following steps
- I removed everything under {~/.Genymobile/Genymotion/ova} folder (with only doing this step it works sometimes)
- removed everything under {~/.Genymobile/Genymotion/bin} folder
After which I downloaded the fresh copy and it worked like magic.
Hope this helps.
How to get the url parameters using AngularJS
When using angularjs with express
On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
This receives a URL template and the path of the given location. The I just call it with:
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path());
Putting it all together my controller is:
.controller('TestController', ['$scope', function($scope, $window) {
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);
The result will be:
{ table: "users", id: "1", place_id: "43", interval: "week" }
Hope this helps someone out there!
How can strings be concatenated?
More efficient ways of concatenating strings are:
join():
Very efficent, but a bit hard to read.
>>> Section = 'C_type'
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings
>>> print new_str
>>> 'Sec_C_type'
String formatting:
Easy to read and in most cases faster than '+' concatenating
>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'
Objective-C and Swift URL encoding
int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
jQuery multiselect drop down menu
<select id="mycontrolId" multiple="multiple">
<option value="1" >one</option>
<option value="2" >two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
var data = "1,3,4"; var dataarray = data.split(",");
$("#mycontrolId").val(dataarray);
Display XML content in HTML page
If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
Selenium and xPath - locating a link by containing text
I think the problem is here:
[contains(text()='Some text')]
To break this down,
- The
[]
are a conditional that operates on each individual node in
that node set -- each span node in your case. It matches if any of the individual nodes it operates
on match the conditions inside the brackets.
text()
is a selector
that matches all of the text nodes that are children of the context
node -- it returns a node set.
contains
is a function that operates
on a string. If it is passed a node set, the node set is converted
into a string by returning the string-value of the node in the
node-set that is first in document order.
You should try to change this to
[text()[contains(.,'Some text')]]
The outer []
are a conditional that operates on each individual node
in that node set text()
is a selector that matches all of the text
nodes that are children of the context node -- it returns a node
set.
The inner []
are a conditional that operates on each node in that
node set.
contains
is a function that operates on a string. Here it is passed
an individual text node (.
).
Set a variable if undefined in JavaScript
Logical nullish assignment, ES2020+ solution
New operators are currently being added to the browsers, ??=
, ||=
, and &&=
. This post will focus on ??=
.
This checks if left side is undefined
or null
, short-circuiting if already defined. If not, the right-side is assigned to the left-side variable.
Comparing Methods
// Using ??=
name ??= "Dave"
// Previously, ES2020
name = name ?? "Dave"
// Before that (not equivalent, but commonly used)
name = name || "Dave" // name ||= "Dave"
Basic Examples
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
// Equivalent to
a = a ?? true
Object/Array Examples
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
??= Browser Support Jan 2021 - 81%
??= Mozilla Documentation
||= Mozilla Documentation
&&= Mozilla Documentation
Copy table from one database to another
Assuming that you want different names for the tables.
If you are using PHPmyadmin you can use their SQL option in the menu. Then you simply copy the SQL-code from the first table and paste it into the new table.
That worked out for me when I was moving from localhost to a webhost.
Hope it works for you!
Error Code 1292 - Truncated incorrect DOUBLE value - Mysql
I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and
in between multiple fields during update, e.g.
update user
set token='lamblala',
accessverion='dummy' and
key='somekey'
where user = 'myself'
The problem in above query can be resolved by replacing and
with comma(,
)
%i or %d to print integer in C using printf()?
I am just adding example here because I think examples make it easier to understand.
In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().
For example:
int main()
{
int num,num2;
scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i
printf("%d\t%d",num,num2);
return 0;
}
Output:
You can see the different results for identical inputs.
num
:
We are reading num
using %d
so when we enter 010
it ignores the first 0
and treats it as decimal 10
.
num2
:
We are reading num2
using %i
.
That means it will treat decimals, octals, and hexadecimals differently.
When it give num2
010
it sees the leading 0
and parses it as octal.
When we print it using %d
it prints the decimal equivalent of octal 010
which is 8
.
How to sort an array based on the length of each element?
We can use Array.sort method to sort this array.
ES5 solution
_x000D_
_x000D_
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_
For ascending sort order: a.length - b.length
For descending sort order: b.length - a.length
ES6 solution
Attention: not all browsers can understand ES6 code!
In ES6 we can use an arrow function expressions.
_x000D_
_x000D_
let array = ["ab", "abcdefgh", "abcd"];
array.sort((a, b) => b.length - a.length);
console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_
Error message "Linter pylint is not installed"
- Open a terminal (
ctrl+~
)
- Run the command
pip install pylint
If that doesn't work: On the off chance you've configured a non-default Python path for your editor, you'll need to match that Python's install location with the pip executable you're calling from the terminal.
This is an issue because the Python extension's settings enable Pylint by default. If you'd rather turn off linting, you can instead change this setting from true
to false
in your user or workspace settings:
"python.linting.pylintEnabled": false
I want to convert std::string into a const wchar_t *
If you have a std::wstring object, you can call c_str()
on it to get a wchar_t*
:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar
routine. That will give you an LPWSTR
, which is equivalent to wchar_t*
.
Build and Install unsigned apk on device without the development server?
As of react-native 0.57, none of the previously provided answers will work anymore, as the directories in which gradle expects to find the bundle and the assets have changed.
Simple way without react-native bundle
The simplest way to build a debug build is without using the react-native bundle
command at all, but by simply modifying your app/build.gradle
file.
Inside the project.ext.react
map in the app/build.gradle
file, add the bundleInDebug: true
entry.
If you want it to not be a --dev
build (no warnings and minified bundle) then you should also add the devDisabledInDebug: true
entry to the same map.
With react-native bundle
If for some reason you need to or want to use the react-native bundle
command to create the bundle and then the ./gradlew assembleDebug
to create the APK with the bundle and the assets you have to make sure to put the bundle and the assets in the correct paths, where gradle can find them.
As of react-native 0.57 those paths are
android/app/build/generated/assets/react/debug/index.android.js
for the bundle
and android/app/build/generated/res/react/debug
for the assets. So the full commands for manually bundling and building the APK with the bundle and assets are:
react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/generated/assets/react/debug/index.android.bundle --assets-dest ./android/app/build/res/react/debug
and then
./gradlew assembleDebug
Bundle and assets path
Note that that paths where gradle looks for the bundle and the assets might be subject to change. To find out where those paths are, look at the react.gradle
file in your node_modules/react-native
directory. The lines starting with def jsBundleDir =
and def resourcesDir =
specify the directories where gradle looks for the bundle and the assets respectively.
How to efficiently use try...catch blocks in PHP
When an exception is thrown, execution is immediately halted and continues at the catch{}
block. This means that, if you place the database calls in the same try{}
block and $tableAresults = $dbHandler->doSomethingWithTableA();
throws an exception, $tableBresults = $dbHandler->doSomethingElseWithTableB();
will not occur. With your second option, $tableBresults = $dbHandler->doSomethingElseWithTableB();
will still occur since it is after the catch{}
block, when execution has resumed.
There is no ideal option for every situation; if you want the second operation to continue regardless, then you must use two blocks. If it is acceptable (or desirable) to have the second operation not occur, then you should use only one.
Getting distance between two points based on latitude/longitude
I arrived at a much simpler and robust solution which is using geodesic
from geopy
package since you'll be highly likely using it in your project anyways so no extra package installation needed.
Here is my solution:
from geopy.distance import geodesic
origin = (30.172705, 31.526725) # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)
print(geodesic(origin, dist).meters) # 23576.805481751613
print(geodesic(origin, dist).kilometers) # 23.576805481751613
print(geodesic(origin, dist).miles) # 14.64994773134371
geopy
How to run TypeScript files from command line?
Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.
#!/usr/bin/env bash
NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc
export TSC="$NODEPATH/tsc"
export NODE="$NODEPATH/node"
TSCFILE=$1 # only parameter is the name of the ts file you created.
function show_usage() {
echo "ts2node [ts file]"
exit 0
}
if [ "$TSCFILE" == "" ]
then
show_usage;
fi
JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"
$TSC $TSCFILE && $NODE $JSFILE
You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:
# tsrun myscript.ts
Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.
Difference between except: and except Exception as e: in Python
Using the second form gives you a variable (named based upon the as
clause, in your example e
) in the except
block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.
How to center a window on the screen in Tkinter?
This answer is better for understanding beginner
#
import tkinter as tk
win = tk.Tk() # Creating instance of Tk class
win.title("Centering windows")
win.resizable(False, False) # This code helps to disable windows from resizing
window_height = 500
window_width = 900
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))
win.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
win.mainloop()
ASP.NET Core Web API Authentication
You can implement a middleware which handles Basic authentication.
public async Task Invoke(HttpContext context)
{
var authHeader = context.Request.Headers.Get("Authorization");
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Basic ".Length).Trim();
System.Console.WriteLine(token);
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialstring.Split(':');
if(credentials[0] == "admin" && credentials[1] == "admin")
{
var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "Basic");
context.User = new ClaimsPrincipal(identity);
}
}
else
{
context.Response.StatusCode = 401;
context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
}
await _next(context);
}
This code is written in a beta version of asp.net core. Hope it helps.
How do you subtract Dates in Java?
Well you can remove the third calendar instance.
GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());
RSA: Get exponent and modulus given a public key
I manage to find the answer for this solution, have to do javascript injection for this to install atob
const atob:any = require('atob');
asn1(pem: any){
asn1parser.Enc.base64ToBuf = function (b64:any) {
return asn1parser.Enc.binToBuf(atob(b64));
};
const dertest = asn1parser.PEM.parseBlock(pem).der;
var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
var buf = asn1parser.ASN1.parse(dertest);
var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
First you should learn about loops, in this case most suitable is for
loop. For instance let's initialize whole table with increasing values starting with 0:
final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
Now you can modify it to initialize your table with values as per your assignment.
But what happen if you replace condition i < SIZE
with i < 11
? Well, you will get IndexOutOfBoundException
, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.
In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.
How to reset Android Studio
On Mac OS X
Remove these directories:
~/Library/Application Support/AndroidStudioBeta
~/Library/Caches/AndroidStudioBeta
~/Library/Logs/AndroidStudioBeta
~/Library/Preferences/AndroidStudioBeta
C/C++ macro string concatenation
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
PHP fwrite new line
How about you store it like this?
Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
Access a JavaScript variable from PHP
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
How to use if - else structure in a batch file?
IF...ELSE IF
constructs work very well in batch files, in particular when you use only one conditional expression on each IF line:
IF %F%==1 (
::copying the file c to d
copy "%sourceFile%1" "%destinationFile1%"
) ELSE IF %F%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%" )
In your example you use IF...AND...IF
type construct, where 2 conditions must be met simultaneously. In this case you can still use IF...ELSE IF
construct, but with extra parentheses to avoid uncertainty for the next ELSE condition:
IF %F%==1 (IF %C%==1 (
::copying the file c to d
copy "%sourceFile1%" "%destinationFile1%" )
) ELSE IF %F%==1 (IF %C%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%"))
The above construct is equivalent to:
IF %F%==1 (
IF %C%==1 (
::copying the file c to d
copy "%sourceFile1%" "%destinationFile1%"
) ELSE IF %C%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%"))
Processing sequence of batch commands depends on CMD.exe parsing order. Just make sure your construct follows that logical order, and as a rule it will work. If your batch script is processed by Cmd.exe without errors, it means this is the correct (i.e. supported by your OS Cmd.exe version) construct, even if someone said otherwise.
Rails raw SQL example
You can do direct SQL to have a single query for both tables. I'll provide a sanitized query example to hopefully keep people from putting variables directly into the string itself (SQL injection danger), even though this example didn't specify the need for it:
@results = []
ActiveRecord::Base.connection.select_all(
ActiveRecord::Base.send(:sanitize_sql_array,
["... your SQL query goes here and ?, ?, ? are replaced...;", a, b, c])
).each do |record|
# instead of an array of hashes, you could put in a custom object with attributes
@results << {col_a_name: record["col_a_name"], col_b_name: record["col_b_name"], ...}
end
Edit: as Huy said, a simple way is ActiveRecord::Base.connection.execute("...")
. Another way is ActiveRecord::Base.connection.exec_query('...').rows
. And you can use native prepared statements, e.g. if using postgres, prepared statement can be done with raw_connection, prepare, and exec_prepared as described in https://stackoverflow.com/a/13806512/178651
You can also put raw SQL fragments into ActiveRecord relational queries: http://guides.rubyonrails.org/active_record_querying.html
and in associations, scopes, etc. You could probably construct the same SQL with ActiveRecord relational queries and can do cool things with ARel as Ernie mentions in http://erniemiller.org/2010/03/28/advanced-activerecord-3-queries-with-arel/. And, of course there are other ORMs, gems, etc.
If this is going to be used a lot and adding indices won't cause other performance/resource issues, consider adding an index in the DB for payment_details.created_at and for payment_errors.created_at.
If lots of records and not all records need to show up at once, consider using pagination:
If you need to paginate, consider creating a view in the DB first called payment_records which combines the payment_details and payment_errors tables, then have a model for the view (which will be read-only). Some DBs support materialized views, which might be a good idea for performance.
Also consider hardware or VM specs on Rails server and DB server, config, disk space, network speed/latency/etc., proximity, etc. And consider putting DB on different server/VM than the Rails app if you haven't, etc.
How to make bootstrap column height to 100% row height?
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle:
http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
Copy multiple files with Ansible
Use the following source code for copy multiple files on your client machine.
- name: Copy data to the client machine
hosts: hostname
become_method: sudo
become_user: root
become: true
tasks:
# Copy twice as sometimes files get skipped (mostly only one file skipped from a folder if the folder does not exist)
- name: Copy UFO-Server
copy:
src: "source files path"
dest: "destination file path"
owner: root
group: root
mode: 0644
backup: yes
ignore_errors: true
Note:
If you are passing multiple paths by using variable then
src: "/root/{{ item }}"
If you are passing path by using a variable for different items then
src: "/root/{{ item.source_path }}"
Moment.js - How to convert date string into date?
Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');
Dec 4, 2020 4:58 PM
OtherFormats
moment.locale(); // en
moment().format('LT'); // 4:59 PM
moment().format('LTS'); // 4:59:47 PM
moment().format('L'); // 12/08/2020
moment().format('l'); // 12/8/2020
moment().format('LL'); // December 8, 2020
moment().format('ll'); // Dec 8, 2020
moment().format('LLL'); // December 8, 2020 4:59 PM
moment().format('lll'); // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM
writing to serial port from linux command line
echo '\x12\x02'
will not be interpreted, and will literally write the string \x12\x02
(and append a newline) to the specified serial port. Instead use
echo -n ^R^B
which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.
The stty
command should work, unless another program is interfering. A common culprit is gpsd
which looks for GPS devices being plugged in.
onclick open window and specific size
Anyone looking for a quick Vue file component, here you go:
// WindowUrl.vue
<template>
<a :href="url" :class="classes" @click="open">
<slot></slot>
</a>
</template>
<script>
export default {
props: {
url: String,
width: String,
height: String,
classes: String,
},
methods: {
open(e) {
// Prevent the link from opening on the parent page.
e.preventDefault();
window.open(
this.url,
'targetWindow',
`toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
);
}
}
}
</script>
Usage:
<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
Print Shipping Label
</window-url>
Run Bash Command from PHP
Your shell_exec is executed by www-data user, from its directory.
You can try
putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");
Where your script is located in /home/user/bin
Later on you can
$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;
To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh
Java method to sum any number of ints
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
Find the version of an installed npm package
From the root of the package do:
node -p "require('./package.json').version"
EDIT: (so you need to cd
into the module's home directory if you are not already there. If you have installed the module with npm install
, then it will be under node_modules/<module_name>
)
EDIT 2: updated as per answer from @jeff-dickey
How to set HTML Auto Indent format on Sublime Text 3?
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
Checking on a thread / remove from list
Better way is to use Queue class:
http://docs.python.org/library/queue.html
Look at the good example code in the bottom of documentation page:
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
What is trunk, branch and tag in Subversion?
The trunk is the main line of development in a SVN repository.
A branch is a side-line of development created to make larger, experimental or disrupting work without annoying users of the trunk version. Also, branches can be used to create development lines for multiple versions of the same product, like having a place to backport bugfixes into a stable release.
Finally, tags are markers to highlight notable revisions in the history of the repository, usually things like "this was released as 1.0".
See the HTML version of "Version Control with Subversion", especially Chapter 4: Branching and Merging or buy it in paper (e.g. from amazon) for an in-depth discussion of the technical details.
As others (e.g. Peter Neubauer below) the underlying implementation as /tags
/branches
and /trunk
directories is only conventional and not in any way enforced by the tools. Violating these conventions leads to confusion all around, as this breaks habits and expectations of others accessing the repository. Special care must be taken to avoid committing new changes into tags, which should be frozen.
I use TortoiseSVN but no Visual Studio integration. I keep the "Check for modifications" dialog open on the second monitor the whole time, so I can track which files I have touched. But see the "Best SVN Tools" question, for more recommendations.
What are the lengths of Location Coordinates, latitude and longitude?
If the latitude coordinate is reported as -6.3572375290155 or -63.572375290155 in decimal degrees then you could round-off and store up to 6 decimal places for 10 cm (or 0.1 meters) precision.
Overview
The valid range of latitude in degrees is -90 and +90 for the southern and northern hemisphere respectively. Longitude is in the range -180 and +180 specifying coordinates west and east of the Prime Meridian, respectively.
For reference, the Equator has a latitude of 0°, the North pole has a latitude of 90° north (written 90° N or +90°), and the South pole has a latitude of -90°.
The Prime Meridian has a longitude of 0° that goes through Greenwich, England. The International Date Line (IDL) roughly follows the 180° longitude. A longitude with a positive value falls in the eastern hemisphere and the negative value falls in the western hemisphere.
Decimal degrees precision
Six (6) decimal places precision in coordinates using decimal degrees notation is at a 10 cm (or 0.1 meters) resolution. Each .000001 difference in coordinate decimal degree is approximately 10 cm in length. For example, the imagery of Google Earth and Google Maps is typically at the 1-meter resolution, and some places have a higher resolution of 1 inch per pixel. One meter resolution can be represented using 5 decimal places so more than 6 decimal places are extraneous for that resolution. The distance between longitudes at the equator is the same as latitude, but the distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.
For millimeter (mm) precision then represent lat/lon with 8 decimal places in decimal degrees format. Since most applications don't need that level of precision 6 decimal places is sufficient for most cases.
In the other direction, whole decimal degrees represent a distance of ~111 km (or 60 nautical miles) and a 0.1 decimal degree difference represents a ~11 km distance.
Here is a table of # decimal places difference in latitude with the delta degrees and the estimated distance in meters using 0,0 as the starting point.
Decimal places |
Decimal degrees |
Distance (meters) |
|
1 |
0.10000000 |
11,057.43 |
11 km |
2 |
0.01000000 |
1,105.74 |
1 km |
3 |
0.00100000 |
110.57 |
|
4 |
0.00010000 |
11.06 |
|
5 |
0.00001000 |
1.11 |
|
6 |
0.00000100 |
0.11 |
11 cm |
7 |
0.00000010 |
0.01 |
1 cm |
8 |
0.00000001 |
0.001 |
1 mm |
Degrees-minute-second (DMS) representation
For DMS notation 1 arc second = 1/60/60 degree = ~30 meter length and 0.1 arc sec delta is ~3 meters.
Example:
0° 0' 0" W, 0° 0' 0" N
? 0° 0' 0" W, 0° 0' 1" N
? 30.715 meters
0° 0' 0" W, 0° 0' 0" N
? 0° 0' 0" W, 0° 0' 0.1" N
? 3.0715 meters
1 arc minute = 1/60 degree = ~2000m (2km)
Update:
Here is an amusing comic strip about coordinate precision.
How to change the scrollbar color using css
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
See This Demo
Can a Windows batch file determine its own file name?
Below is my initial code:
@echo off
Set z=%%
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.
I noticed that file name given by %~0 and %0 is the way it was entered in the command-shell and not how that file is actually named. So if you want the literal case used for the file name you should use %~n0. However, this will leave out the file extension. But if you know the file name you could add the
following code.
set b=%~0
echo %~n0%b:~8,4%
I have learned that ":~8,4%" means start at the 9th character of the variable and then show show the next 4 characters. The range is 0 to the end of the variable string. So %Path% would be very long!
fIlEnAmE.bat
012345678901
However, this is not as sound as Jool's solution (%~x0) above.
My Evidence:
C:\bin>filename.bat
%0.......filename.bat
%~0......filename.bat
. . .
C:\bin>fIlEnAmE.bat
%0.......fIlEnAmE.bat
%~0......fIlEnAmE.bat
%n0......n0
%x0......x0
%~n0.....FileName
%dp0.....dp0
%~dp0....C:\bin\
%~n0%b:~8,4%...FileName.bat
Press any key to continue . . .
C:\bin>dir
Volume in drive C has no label.
Volume Serial Number is CE18-5BD0
Directory of C:\bin
. . .
05/02/2018 11:22 PM 208 FileName.bat
Here is the final code
@echo off
Set z=%%
set b=%~0
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.
echo A complex solution:
echo ===================================
echo %z%~n0%z%b:~8,4%z%...%~n0%b:~8,4%
echo ===================================
echo.
echo The preferred solution:
echo ===================================
echo %z%~n0%z%~x0.......%~n0%~x0
echo ===================================
pause
How to get a jqGrid selected row cells value
Just to add, you can also retrieve a jqGrid cell value, based on the rowID plus column index (rather than the Column name):
So, to fetch the value in the forth column (column index # 3) for the row with primary key ID 1234, we could use this:
var rowID = 1234;
var columnIndex = 3;
var cellValue = $("#" + rowID).find('td').eq(columnIndex).text();
Btw, on a completely unrelated topic (but please don't vote me down):
I didn't realise that you can, fairly easily, link text boxes to your jqGrid, so your users can do instant searching, without having to open the Search dialog.
To do this, you need a bit of HTML like this:
<input type="text" name="employeeName" id="employeeName" style="width:250px" />
<!-- This will be my jqGrid control and pager -->
<table id="tblEmployees"></table>
<div id="pager"></div>
And a bit of JavaScript like this:
$("#employeeName").on('change keyup paste', function () {
SearchByEmployeeName();
});
function SearchByEmployeeName()
{
// Fetch the text from our <input> control
var searchString = $("#employeeName").val();
// Prepare to pass a new search filter to our jqGrid
var f = { groupOp: "AND", rules: [] };
// Remember to change the following line to reflect the jqGrid column you want to search for your string in
// In this example, I'm searching through the UserName column.
f.rules.push({ field: "UserName", op: "cn", data: searchString });
var grid = $('#tblEmployees');
grid[0].p.search = f.rules.length > 0;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
This is a real game-changer for me... it really makes jqGrid much more user friendly.
Users can immediately start typing in their search string, rather than needing to open the Search dialog, remember to change the operator to "contains", then start typing, and close the search dialog again.
How do I do a bulk insert in mySQL using node.js
If you want to insert object, use this:
currentLogs = [
{ socket_id: 'Server', message: 'Socketio online', data: 'Port 3333', logged: '2014-05-14 14:41:11' },
{ socket_id: 'Server', message: 'Waiting for Pi to connect...', data: 'Port: 8082', logged: '2014-05-14 14:41:11' }
];
console.warn(currentLogs.map(logs=>[ logs.socket_id , logs.message , logs.data , logs.logged ]));
The output will be:
[
[ 'Server', 'Socketio online', 'Port 3333', '2014-05-14 14:41:11' ],
[
'Server',
'Waiting for Pi to connect...',
'Port: 8082',
'2014-05-14 14:41:11'
]
]
Also, please check the documentation to know more about the map function.
Plot mean and standard deviation
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
Codeigniter $this->db->get(), how do I return values for a specific row?
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
href overrides ng-click in Angular.js
You can simply prevent the default behavior of the click event directly in your template.
<a href="#" ng-click="$event.preventDefault();logout()" />
Per the angular documentation,
Directives like ngClick and ngFocus expose a $event object within the scope of that expression.
Looking for a short & simple example of getters/setters in C#
Most languages do it this way, and you can do it in C# too.
public void setRAM(int RAM)
{
this.RAM = RAM;
}
public int getRAM()
{
return this.RAM;
}
But C# also gives a more elegant solution to this :
public class Computer
{
int ram;
public int RAM
{
get
{
return ram;
}
set
{
ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
}
}
}
And later access it with.
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;
For newer versions of C# it's even better :
public class Computer
{
public int RAM { get; set; }
}
and later :
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;
Bundle ID Suffix? What is it?
The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.
It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.
An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:
com.awesomeapps.thebestapp
In this case the suffix is thebestapp
.
Iterating through a variable length array
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
or
for(String value : array)
{
System.out.println(value);
}
The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.
Just for completeness you can do the while loop this way:
int index = 0;
while(index < myArray.length)
{
final String value;
value = myArray[index];
System.out.println(value);
index++;
}
But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).
How to check a string for specific characters?
Quick comparison of timings in response to the post by Abbafei:
import timeit
def func1():
phrase = 'Lucky Dog'
return any(i in 'LD' for i in phrase)
def func2():
phrase = 'Lucky Dog'
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
func1_time = timeit.timeit(func1, number=100000)
func2_time = timeit.timeit(func2, number=100000)
print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))
Output:
Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
So the code is more compact with any, but faster with the conditional.
EDIT : TL;DR -- For long strings, if-then is still much faster than any!
I decided to compare the timing for a long random string based on some of the valid points raised in the comments:
# Tested in Python 2.7.14
import timeit
from string import ascii_letters
from random import choice
def create_random_string(length=1000):
random_list = [choice(ascii_letters) for x in range(length)]
return ''.join(random_list)
def function_using_any(phrase):
return any(i in 'LD' for i in phrase)
def function_using_if_then(phrase):
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
random_string = create_random_string(length=2000)
func1_time = timeit.timeit(stmt="function_using_any(random_string)",
setup="from __main__ import function_using_any, random_string",
number=200000)
func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
setup="from __main__ import function_using_if_then, random_string",
number=200000)
print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))
Output:
Time for function using any: 0.1342546
Time for function using if-then: 0.0201827
If-then is almost an order of magnitude faster than any!
Check if an element is present in an array
You can use indexOf
But not working well in the last version of internet explorer.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
I suggest you use the following code:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
android studio 0.4.2: Gradle project sync failed error
After following Carlos steps I ended up deleting the
C:\Users\MyPath.AndroidStudioPreview Directory
Then re imported the project it seemed to fix my issue completely for the meanwhile, And speedup my AndroidStudio
Hope it helps anyone
Passing variable number of arguments around
To pass the ellipses on, you have to convert them to a va_list and use that va_list in your second function. Specifically;
void format_string(char *fmt,va_list argptr, char *formatted_string);
void debug_print(int dbg_lvl, char *fmt, ...)
{
char formatted_string[MAX_FMT_SIZE];
va_list argptr;
va_start(argptr,fmt);
format_string(fmt, argptr, formatted_string);
va_end(argptr);
fprintf(stdout, "%s",formatted_string);
}
Change image size with JavaScript
If you want to resize an image after it is loaded, you can attach to the onload
event of the <img>
tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload
event for <img>
).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>
how to bypass Access-Control-Allow-Origin?
I have fixed this problem when calling a MVC3 Controller.
I added:
Response.AddHeader("Access-Control-Allow-Origin", "*");
before my
return Json(model, JsonRequestBehavior.AllowGet);
And also my $.ajax
was complaining that it does not accept Content-type header in my ajax call, so I commented it out as I know its JSON being passed to the Action.
Hope that helps.
What does $_ mean in PowerShell?
This is the variable for the current value in the pipe line, which is called $PSItem
in Powershell 3 and newer.
1,2,3 | %{ write-host $_ }
or
1,2,3 | %{ write-host $PSItem }
For example in the above code the %{}
block is called for every value in the array. The $_
or $PSItem
variable will contain the current value.
How to wrap text in textview in Android
Just set layout_with
to a definate size, when the text fills the maximum width it will overflow to the next line causing a wrap effect.
<TextView
android:id="@+id/segmentText"
android:layout_marginTop="10dp"
android:layout_below="@+id/segmentHeader"
android:text="You have the option to record in one go or segments(if you swap options
you will loose your current recordings)"
android:layout_width="300dp"
android:layout_height="wrap_content"/>
What is code coverage and how do YOU measure it?
Code coverage has been explained well in the previous answers. So this is more of an answer to the second part of the question.
We've used three tools to determine code coverage.
- JTest - a proprietary tool built over JUnit. (It generates unit tests as well.)
- Cobertura - an open source code coverage tool that can easily be coupled with JUnit tests to generate reports.
- Emma - another - this one we've used for a slightly different purpose than unit testing. It has been used to generate coverage reports when the web application is accessed by end-users. This coupled with web testing tools (example: Canoo) can give you very useful coverage reports which tell you how much code is covered during typical end user usage.
We use these tools to
- Review that developers have written good unit tests
- Ensure that all code is traversed during black-box testing
Recursive query in SQL Server
Try this:
;WITH CTE
AS
(
SELECT DISTINCT
M1.Product_ID Group_ID,
M1.Product_ID
FROM matches M1
LEFT JOIN matches M2
ON M1.Product_Id = M2.matching_Product_Id
WHERE M2.matching_Product_Id IS NULL
UNION ALL
SELECT
C.Group_ID,
M.matching_Product_Id
FROM CTE C
JOIN matches M
ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID
You can use OPTION(MAXRECURSION n)
to control recursion depth.
SQL FIDDLE DEMO
Set variable in jinja
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
How should I do integer division in Perl?
you can:
use integer;
it is explained by Michael Ratanapintha or else use manually:
$a=3.7;
$b=2.1;
$c=int(int($a)/int($b));
notice, 'int' is not casting. this is function for converting number to integer form.
this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.
C++ equivalent of Java's toString?
You can also do it this way, allowing polymorphism:
class Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Base: " << b << "; ";
}
private:
int b;
};
class Derived : public Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Derived: " << d << "; ";
}
private:
int d;
}
std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }
how to check the version of jar file?
You need to unzip it and check its META-INF/MANIFEST.MF
file, e.g.
unzip -p file.jar | head
or more specific:
unzip -p file.jar META-INF/MANIFEST.MF
What's the fastest way to do a bulk insert into Postgres?
UNNEST
function with arrays can be used along with multirow VALUES syntax. I'm think that this method is slower than using COPY
but it is useful to me in work with psycopg and python (python list
passed to cursor.execute
becomes pg ARRAY
):
INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
VALUES (
UNNEST(ARRAY[1, 2, 3]),
UNNEST(ARRAY[100, 200, 300]),
UNNEST(ARRAY['a', 'b', 'c'])
);
without VALUES
using subselect with additional existance check:
INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
SELECT * FROM (
SELECT UNNEST(ARRAY[1, 2, 3]),
UNNEST(ARRAY[100, 200, 300]),
UNNEST(ARRAY['a', 'b', 'c'])
) AS temptable
WHERE NOT EXISTS (
SELECT 1 FROM tablename tt
WHERE tt.fieldname1=temptable.fieldname1
);
the same syntax to bulk updates:
UPDATE tablename
SET fieldname1=temptable.data
FROM (
SELECT UNNEST(ARRAY[1,2]) AS id,
UNNEST(ARRAY['a', 'b']) AS data
) AS temptable
WHERE tablename.id=temptable.id;
PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
Use either. They are both equally (in)secure, as in many cases SERVER_NAME is just populated from HTTP_HOST anyway. I normally go for HTTP_HOST, so that the user stays on the exact host name they started on. For example if I have the same site on a .com and .org domain, I don't want to send someone from .org to .com, particularly if they might have login tokens on .org that they'd lose if sent to the other domain.
Either way, you just need to be sure that your webapp will only ever respond for known-good domains. This can be done either (a) with an application-side check like Gumbo's, or (b) by using a virtual host on the domain name(s) you want that does not respond to requests that give an unknown Host header.
The reason for this is that if you allow your site to be accessed under any old name, you lay yourself open to DNS rebinding attacks (where another site's hostname points to your IP, a user accesses your site with the attacker's hostname, then the hostname is moved to the attacker's IP, taking your cookies/auth with it) and search engine hijacking (where an attacker points their own hostname at your site and tries to make search engines see it as the ‘best’ primary hostname).
Apparently the discussion is mainly about $_SERVER['PHP_SELF'] and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.
Pfft. Well you shouldn't use anything in any attribute without escaping with htmlspecialchars($string, ENT_QUOTES)
, so there's nothing special about server variables there.
calculating the difference in months between two dates
The accepted answer works perfectly when you want full months.
I needed partial months. This is the solution I came up with for partial months:
/// <summary>
/// Calculate the difference in months.
/// This will round up to count partial months.
/// </summary>
/// <param name="lValue"></param>
/// <param name="rValue"></param>
/// <returns></returns>
public static int MonthDifference(DateTime lValue, DateTime rValue)
{
var yearDifferenceInMonths = (lValue.Year - rValue.Year) * 12;
var monthDifference = lValue.Month - rValue.Month;
return yearDifferenceInMonths + monthDifference +
(lValue.Day > rValue.Day
? 1 : 0); // If end day is greater than start day, add 1 to round up the partial month
}
I also needed a year difference with the same need for partial years. Here is the solution I came up with:
/// <summary>
/// Calculate the differences in years.
/// This will round up to catch partial months.
/// </summary>
/// <param name="lValue"></param>
/// <param name="rValue"></param>
/// <returns></returns>
public static int YearDifference(DateTime lValue, DateTime rValue)
{
return lValue.Year - rValue.Year +
(lValue.Month > rValue.Month // Partial month, same year
? 1
: ((lValue.Month = rValue.Month)
&& (lValue.Day > rValue.Day)) // Partial month, same year and month
? 1 : 0);
}
Using Spring RestTemplate in generic method with generic parameter
My own implementation of generic restTemplate call:
private <REQ, RES> RES queryRemoteService(String url, HttpMethod method, REQ req, Class reqClass) {
RES result = null;
try {
long startMillis = System.currentTimeMillis();
// Set the Content-Type header
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application","json"));
// Set the request entity
HttpEntity<REQ> requestEntity = new HttpEntity<>(req, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP POST request, marshaling the request to JSON, and the response to a String
ResponseEntity<RES> responseEntity = restTemplate.exchange(url, method, requestEntity, reqClass);
result = responseEntity.getBody();
long stopMillis = System.currentTimeMillis() - startMillis;
Log.d(TAG, method + ":" + url + " took " + stopMillis + " ms");
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return result;
}
To add some context, I'm consuming RESTful service with this, hence all requests and responses are wrapped into small POJO like this:
public class ValidateRequest {
User user;
User checkedUser;
Vehicle vehicle;
}
and
public class UserResponse {
User user;
RequestResult requestResult;
}
Method which calls this is the following:
public User checkUser(User user, String checkedUserName) {
String url = urlBuilder()
.add(USER)
.add(USER_CHECK)
.build();
ValidateRequest request = new ValidateRequest();
request.setUser(user);
request.setCheckedUser(new User(checkedUserName));
UserResponse response = queryRemoteService(url, HttpMethod.POST, request, UserResponse.class);
return response.getUser();
}
And yes, there's a List dto-s as well.
How to insert values into the database table using VBA in MS access
since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.
Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
InDate = Me.FromDateTxt
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
Access parent URL from iframe
I've had issues with this. If using a language like php when your page first loads in the iframe grab $_SERVER['HTTP_REFFERER']
and set it to a session variable.
This way when the page loads in the iframe you know the full parent url and query string of the page that loaded it. With cross browser security it's a bit of a headache counting on window.parent anything if you you different domains.
Javascript getElementsByName.value not working
document.getElementsByName("name")
will get several elements called by same name .
document.getElementsByName("name")[Number]
will get one of them.
document.getElementsByName("name")[Number].value
will get the value of paticular element.
The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.
Youtube - downloading a playlist - youtube-dl
I found the best solution after many attempts for this problem.
youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}
How to open a Bootstrap modal window using jQuery?
If you use links's onclick function to call a modal by jQuery, the "href" can't be null.
For example:
... ...
<a href="" onclick="openModal()">Open a Modal by jQuery</a>
... ...
... ...
<script type="text/javascript">
function openModal(){
$('#myModal').modal();
}
</script>
The Modal can't show.
The right code is :
<a href="#" onclick="openModal()">Open a Modal by jQuery</a>
Is PowerShell ready to replace my Cygwin shell on Windows?
I found PowerShell programming to be not worth the effort.
I have several years of experience with shell scripting under Unix, but I found it enormously difficult to do much of anything with PowerShell.
It seems like many functions require you to interrogate the Windows Management Interface and issue SQL-like commands to get the information you need.
For example, I wanted to write a script to remove all files with a specific suffix from a directory tree. Under Unix, this would be a simple ...
find . -name \*.xyz -exec rm {} \;
After a couple of hours dicking around with Scripting.FileSystemObject
and WScript.Shell
and issuing "SELECT * FROM Win32_ShortcutFile WHERE Drive = '" & drive & "' AND Path = '" & searchFolder & "'", I finally gave up and settled for Windows Explorer's Search command and just do it manually. There's probably some way to do what I wanted, but I didn't see anything obvious and all the examples on the MSDN site were so trivial as to be worthless.
EDIT Heh, of course as soon as I wrote this I poked around some more and found what I had been missing: the -recurse
option to the remove-item command is faulty (revealed if you use get-help remove-item -detailed
).
I had been trying "remove-item -filter '* .xyz' -recurse" and it wasn't working, so I gave up on it.
Turns out you need to use get-childitem -filter '*.xyz' -recurse | remove-item
Convert unsigned int to signed int C
Since converting unsigned values use to represent positive numbers converting it can be done by setting the most significant bit to 0. Therefore a program will not interpret that as a Two`s complement value. One caveat is that this will lose information for numbers that near max of the unsigned type.
template <typename TUnsigned, typename TSinged>
TSinged UnsignedToSigned(TUnsigned val)
{
return val & ~(1 << ((sizeof(TUnsigned) * 8) - 1));
}
Create Elasticsearch curl query for not null and not empty("")
A null value and an empty string both result in no value being indexed, in which case you can use the exists
filter
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"constant_score" : {
"filter" : {
"exists" : {
"field" : "myfield"
}
}
}
}
}
'
Or in combination with (eg) a full text search on the title
field:
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"filtered" : {
"filter" : {
"exists" : {
"field" : "myfield"
}
},
"query" : {
"match" : {
"title" : "search keywords"
}
}
}
}
}
'
Use URI builder in Android or create URL with variables
There is another way of using Uri
and we can achieve the same goal
http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
To build the Uri you can use this:
final String FORECAST_BASE_URL =
"http://api.example.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
You can declare all this the above way or even inside the Uri.parse()
and appendQueryParameter()
Uri builtUri = Uri.parse(FORECAST_BASE_URL)
.buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, "json")
.appendQueryParameter(UNITS_PARAM, "metric")
.appendQueryParameter(DAYS_PARAM, Integer.toString(7))
.build();
At last
URL url = new URL(builtUri.toString());
Conversion failed when converting from a character string to uniqueidentifier
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
How do you check for permissions to write to a directory or file?
Since this isn't closed, i would like to submit a new entry for anyone looking to have something working properly for them... using an amalgamation of what i found here, as well as using DirectoryServices to debug the code itself and find the proper code to use, here's what i found that works for me in every situation... note that my solution extends DirectoryInfo object... :
public static bool IsReadable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow=false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
public static bool IsWriteable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return me.IsReadable() && isAllow;
}
Java: Converting String to and from ByteBuffer and associated problems
Unless things have changed, you're better off with
public static ByteBuffer str_to_bb(String msg, Charset charset){
return ByteBuffer.wrap(msg.getBytes(charset));
}
public static String bb_to_str(ByteBuffer buffer, Charset charset){
byte[] bytes;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
return new String(bytes, charset);
}
Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.
How to parse Excel (XLS) file in Javascript/HTML5
XLS is a binary proprietary format used by Microsoft. Parsing XLS with server side languages is very difficult without using some specific library or Office Interop. Doing this with javascript is mission impossible. Thanks to the HTML5 File API you can read its binary contents but in order to parse and interpret it you will need to dive into the specifications of the XLS format. Starting from Office 2007, Microsoft embraced the Open XML file formats (xslx
for Excel) which is a standard.
Sorting object property by values
For completeness sake, this function returns sorted array of object properties:
function sortObject(obj) {
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
arr.push({
'key': prop,
'value': obj[prop]
});
}
}
arr.sort(function(a, b) { return a.value - b.value; });
//arr.sort(function(a, b) { a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); //use this to sort as strings
return arr; // returns array
}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var arr = sortObject(list);
console.log(arr); // [{key:"bar", value:15}, {key:"me", value:75}, {key:"you", value:100}, {key:"foo", value:116}]
Jsfiddle with the code above is here. This solution is based on this article.
Updated fiddle for sorting strings is here. You can remove both additional .toLowerCase() conversions from it for case sensitive string comparation.
Does Python have a toString() equivalent, and can I convert a db.Model element to String?
In python, the str()
method is similar to the toString()
method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__()
method of the parameter object to get its string representation.
In this case, however, you are comparing a UserProperty
author from the database, which is of type users.User
with the nickname string. You will want to compare the nickname
property of the author instead with todo.author.nickname
in your template.
Python - difference between two strings
What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj
and zlib.decompressobj
with the zdict
parameter set to your "base word", e.g. afrykanerskojezyczny
.
Caveats are zdict
is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.
Java, Calculate the number of days between two dates
I know this thread is two years old now, I still don't see a correct answer here.
Unless you want to use Joda or have Java 8 and if you need to subract dates influenced by daylight saving.
So I have written my own solution. The important aspect is that it only works if you really only care about dates because it's necessary to discard the time information, so if you want something like 25.06.2014 - 01.01.2010 = 1636
, this should work regardless of the DST:
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
public static long getDayCount(String start, String end) {
long diff = -1;
try {
Date dateStart = simpleDateFormat.parse(start);
Date dateEnd = simpleDateFormat.parse(end);
//time is always 00:00:00, so rounding should help to ignore the missing hour when going from winter to summer time, as well as the extra hour in the other direction
diff = Math.round((dateEnd.getTime() - dateStart.getTime()) / (double) 86400000);
} catch (Exception e) {
//handle the exception according to your own situation
}
return diff;
}
As the time is always 00:00:00
, using double and then Math.round()
should help to ignore the missing 3600000 ms (1 hour) when going from winter to summer time, as well as the extra hour if going from summer to winter.
This is a small JUnit4 test I use to prove it:
@Test
public void testGetDayCount() {
String startDateStr = "01.01.2010";
GregorianCalendar gc = new GregorianCalendar(locale);
try {
gc.setTime(simpleDateFormat.parse(startDateStr));
} catch (Exception e) {
}
for (long i = 0; i < 10000; i++) {
String dateStr = simpleDateFormat.format(gc.getTime());
long dayCount = getDayCount(startDateStr, dateStr);
assertEquals("dayCount must be equal to the loop index i: ", i, dayCount);
gc.add(GregorianCalendar.DAY_OF_YEAR, 1);
}
}
... or if you want to see what it does 'life', replace the assertion with just:
System.out.println("i: " + i + " | " + dayCount + " - getDayCount(" + startDateStr + ", " + dateStr + ")");
... and this is what the output should look like:
i: 0 | 0 - getDayCount(01.01.2010, 01.01.2010)
i: 1 | 1 - getDayCount(01.01.2010, 02.01.2010)
i: 2 | 2 - getDayCount(01.01.2010, 03.01.2010)
i: 3 | 3 - getDayCount(01.01.2010, 04.01.2010)
...
i: 1636 | 1636 - getDayCount(01.01.2010, 25.06.2014)
...
i: 9997 | 9997 - getDayCount(01.01.2010, 16.05.2037)
i: 9998 | 9998 - getDayCount(01.01.2010, 17.05.2037)
i: 9999 | 9999 - getDayCount(01.01.2010, 18.05.2037)
Check if passed argument is file or directory in Bash
At least write the code without the bushy tree:
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
exit 1
fi
When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:
$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$
Given that you are having problems, you should debug the script by adding:
ls -l "${PASSED}"
This will show you what ls
thinks about the names you pass the script.
Detecting an undefined object property
Simply anything is not defined in JavaScript, is undefined, doesn't matter if it's a property inside an Object/Array or as just a simple variable...
JavaScript has typeof
which make it very easy to detect an undefined variable.
Simply check if typeof whatever === 'undefined'
and it will return a boolean.
That's how the famous function isUndefined()
in AngularJs v.1x is written:
function isUndefined(value) {return typeof value === 'undefined';}
So as you see the function receive a value, if that value is defined, it will return false
, otherwise for undefined values, return true
.
So let's have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:
var stackoverflow = {};
stackoverflow.javascipt = 'javascript';
var today;
var self = this;
var num = 8;
var list = [1, 2, 3, 4, 5];
var y = null;
and we check them as below, you can see the results in front of them as a comment:
isUndefined(stackoverflow); //false
isUndefined(stackoverflow.javascipt); //false
isUndefined(today); //true
isUndefined(self); //false
isUndefined(num); //false
isUndefined(list); //false
isUndefined(y); //false
isUndefined(stackoverflow.java); //true
isUndefined(stackoverflow.php); //true
isUndefined(stackoverflow && stackoverflow.css); //true
As you see we can check anything with using something like this in our code, as mentioned you can simply use typeof
in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.
Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.
If you check a property on an object and the object doesn't exist, will throw an error and stop the whole application running.
isUndefined(x.css);
VM808:2 Uncaught ReferenceError: x is not defined(…)
So simple you can wrap inside an if statement like below:
if(typeof x !== 'undefined') {
//do something
}
Which also equal to isDefined in Angular 1.x...
function isDefined(value) {return typeof value !== 'undefined';}
Also other javascript frameworks like underscore has similar defining check, but I recommend you use typeof
if you already not using any frameworks.
I also add this section from MDN which has got useful information about typeof, undefined and void(0).
Strict equality and undefined
You can use undefined and the strict equality and inequality operators to determine whether a variable has
a value. In the following code, the variable x is not defined, and the
if statement evaluates to true.
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
Note: The strict equality operator rather than the standard equality
operator must be used here, because x == undefined also checks whether
x is null, while strict equality doesn't. null is not equivalent to
undefined. See comparison operators for details.
Typeof operator and undefined
Alternatively, typeof can be used:
var x;
if (typeof x === 'undefined') {
// these statements execute
}
One reason to use typeof is that it does not throw an error if the
variable has not been declared.
// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if (x === undefined) { // throws a ReferenceError
}
However, this kind of technique should be avoided. JavaScript is a
statically scoped language, so knowing if a variable is declared can
be read by seeing whether it is declared in an enclosing context. The
only exception is the global scope, but the global scope is bound to
the global object, so checking the existence of a variable in the
global context can be done by checking the existence of a property on
the global object (using the in operator, for instance).
Void operator and undefined
The void operator is a third alternative.
var x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
more > here
npm install gives error "can't find a package.json file"
I'm not sure what you're trying to do here:
npm install
alone in your home directory shouldn't do much -- it's not the root of a node app, so there's nothing to install, since there's no package.json.
There are two possible solutions:
1) cd
to a node app and run npm install
there. OR
2) if you're trying to install something as a command to use in the shell (You don't have a node application), npm install -g packagename
. -g
flag tells it to install in global namespace.
AddTransient, AddScoped and AddSingleton Services Differences
- Singleton is a single instance for the lifetime of the application
domain.
- Scoped is a single instance for the duration of the scoped
request, which means per HTTP request in ASP.NET.
- Transient is a single instance per code request.
Normally the code request should be made through a constructor parameter, as in
public MyConsumingClass(IDependency dependency)
I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.
How to sort by Date with DataTables jquery plugin?
Create a hidden column "dateOrder" (for example) with the date as string with the format "yyyyMMddHHmmss" and use the property "orderData" to point to that column.
var myTable = $("#myTable").dataTable({
columns: [
{ data: "id" },
{ data: "date", "orderData": 4 },
{ data: "name" },
{ data: "total" },
{ data: "dateOrder", visible: false }
] });
Make column fixed position in bootstrap
Following the solution here http://jsfiddle.net/dRbe4/,
<div class="row">
<div class="col-lg-3 fixed">
Fixed content
</div>
<div class="col-lg-9 scrollit">
Normal scrollable content
</div>
</div>
I modified some css to work just perfect:
.fixed {
position: fixed;
width: 25%;
}
.scrollit {
float: left;
width: 71%
}
Thanks @Lowkase for sharing the solution.
How to redraw DataTable with new data
datatable.rows().iterator('row', function ( context, index ) {
var data = this.row(index).data();
var row = $(this.row(index).node());
data[0] = 'new data';
datatable.row(row).data(data).draw();
});
What is the difference between tree depth and height?
Another way to understand those concept is as follow:
Depth: Draw a horizontal line at the root position and treat this line as ground. So the depth of the root is 0, and all its children are grow downward so each level of nodes has the current depth + 1.
Height: Same horizontal line but this time the ground position is external nodes, which is the leaf of tree and count upward.
best OCR (Optical character recognition) example in android
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two
like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
CSS @font-face not working in ie
I read a lot of tutorials that suggested hacks, so I came up with this solution I think is better... It seems to work fine.
@font-face {
font-family: MyFont; src: url('myfont.ttf');
}
@font-face{
font-family: MyFont_IE; src: url('myfont.eot');
}
.my_font{
font-family: MyFont, MyFont_IE, Arial, Helvetica, sans-serif;
}
COUNT / GROUP BY with active record?
I believe you'll want something like this:
$this->db->select('user_id, COUNT(user_id) as total');
$this->db->group_by('user_id');
$this->db->order_by('total', 'desc');
$this->db->get('tablename', 10);
This will produce a result like
| USER_ID | TOTAL |
| 12 | 3 |
| 15 | 2 |
| 18 | 1 |
UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.
Sending cookies with postman
Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.
use video as background for div
Why not fix a <video>
and use z-index:-1
to put it behind all other elements?
html, body { width:100%; height:100%; margin:0; padding:0; }
<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
<video id="video" style="width:100%; height:100%">
....
</video>
</div>
<div class='content'>
....
Demo
If you want it within a container you have to add a container element and a little more CSS
/* HTML */
<div class='vidContain'>
<div class='vid'>
<video> ... </video>
</div>
<div class='content'> ... The rest of your content ... </div>
</div>
/* CSS */
.vidContain {
width:300px; height:200px;
position:relative;
display:inline-block;
margin:10px;
}
.vid {
position: absolute;
top: 0; left:0;
width: 100%; height: 100%;
z-index: -1;
}
.content {
position:absolute;
top:0; left:0;
background: black;
color:white;
}
Demo
PowerShell array initialization
The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.
$array = new-object object[] 5
for($i=0; $i -lt $array.Length;$i++)
{
$array[$i] = $FALSE
}
How to filter an array from all elements of another array
_x000D_
_x000D_
/* Here's an example that uses (some) ES6 Javascript semantics to filter an object array by another object array. */_x000D_
_x000D_
// x = full dataset_x000D_
// y = filter dataset_x000D_
let x = [_x000D_
{"val": 1, "text": "a"},_x000D_
{"val": 2, "text": "b"},_x000D_
{"val": 3, "text": "c"},_x000D_
{"val": 4, "text": "d"},_x000D_
{"val": 5, "text": "e"}_x000D_
],_x000D_
y = [_x000D_
{"val": 1, "text": "a"},_x000D_
{"val": 4, "text": "d"} _x000D_
];_x000D_
_x000D_
// Use map to get a simple array of "val" values. Ex: [1,4]_x000D_
let yFilter = y.map(itemY => { return itemY.val; });_x000D_
_x000D_
// Use filter and "not" includes to filter the full dataset by the filter dataset's val._x000D_
let filteredX = x.filter(itemX => !yFilter.includes(itemX.val));_x000D_
_x000D_
// Print the result._x000D_
console.log(filteredX);
_x000D_
_x000D_
_x000D_
How to get index of an item in java.util.Set
A small static custom method in a Util
class would help:
public static int getIndex(Set<? extends Object> set, Object value) {
int result = 0;
for (Object entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
If you need/want one class that is a Set
and offers a getIndex()
method, I strongly suggest to implement a new Set
and use the decorator pattern:
public class IndexAwareSet<T> implements Set {
private Set<T> set;
public IndexAwareSet(Set<T> set) {
this.set = set;
}
// ... implement all methods from Set and delegate to the internal Set
public int getIndex(T entry) {
int result = 0;
for (T entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
}
MySQL query to get column names?
You can use the following query for MYSQL:
SHOW `columns` FROM `your-table`;
Below is the example code which shows How to implement above syntax in php to list the names of columns:
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
For Details about output of SHOW COLUMNS FROM TABLE
visit: MySQL Refrence.
Serializing an object as UTF-8 XML in .NET
Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).
To get the actual UTF-8 octets you could use:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
serializer.Serialize(streamWriter, entry);
byte[] utf8EncodedXml = memoryStream.ToArray();
I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var xw = XmlWriter.Create(memStm))
{
serializer.Serialize(xw, entry);
var utf8 = memStm.ToArray();
}
Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.
TypeScript static classes
Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:
class Point {
constructor(public x: number, public y: number) {
throw new Error('cannot instantiate using a static class');
}
public distance(p: Point) {
var dx = this.x - p.x;
var dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
static origin = new Point(0, 0);
static distance(p1: Point, p2: Point) {
return p1.distance(p2);
}
}
where Point.distance()
is a static (or "class") method.
Difference between using gradlew and gradle
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
- Download and install the correct
gradle
version
- Parse the arguments
- Call a
gradle
task
Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
Where is the Global.asax.cs file?
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
What are the differences between Visual Studio Code and Visual Studio?
Visual Studio
- IDE
- Except for free editions, it is a paid IDE.
- It is quite heavy on CPU and lags on lower end PCs.
- It is mostly used for Windows software development including DirectX programs, Windows API, etc.
- Advanced IntelliSense (best one ever; Visual Studio Code's IntelliSense extension takes second place)
- It features built-in debuggers, easy-to-configure project settings (though developers tend to not use the GUI ones)
- Microsoft support (more than Visual Studio Code)
- Mostly used for C/C++ (Windows), .NET and C# projects along with SQL Server, database, etc.
- Extreme large download size, space utilization and the slow downs over time.
- It is the only con that forces me to use Visual Studio Code for smaller projects*
- Includes tools to generate dependency graphs. Refactoring tools have great support for Visual Studio.
- Has a VYSIWYG editor for VB.NET, C++.NET, and C#. (It is easy enough for first time users instead of getting through
windows.h
)
Visual Studio Code
- Free open source text editor
- Has IntelliSense (but it doesn't work out of box if Visual Studio is not installed, need to configure to point to MinGW, etc.)
- Smaller download size and RAM requirements. With IntelliSense it requires around 300 MB RAM. (Edit : Some header files tend to blow up memory requirements to 7-8 GBs eg. OpenGL and GLM Libraries)
- It works on lower-end PCs. (it is still slow to start up especially if PowerShell is used instead of CMD)
- Lower support (open source, so you can modify it yourself)
- Build tasks are project specific. Even if you want to build it in a vanilla configuration.
- Mostly used for web development (this applies to all free text editors). They tend to show off JavaScript / HTML support over C/C++. Visual Studio shows off Visual Basic/C++ over other languages.
- Lack of good extensions (it's still new though)
- Gives you a hard time to reconfigure your project/workspace settings. I prefer the GUI way.
- Cross platform
- Has an integrated terminal (PowerShell is too slow at startup though)
- It is best for smaller projects and test code (you know if you are bored and want to print "Hello, World!", it does not make sense to wait 3-5 minutes while Visual Studio loads up, and then another minute or 2 at project creation and then finally getting it to print "Hello, World!").
Error while inserting date - Incorrect date value:
This is the date format:
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
Why do you insert '07-25-2012' format when MySQL format is '2012-07-25'?. Actually you get this error if the sql_mode is traditional/strict mode
else it just enters 0000-00-00 and gives a warning: 1265 - Data truncated for column 'col1' at row 1
.
For loop in Oracle SQL
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
How do I handle a click anywhere in the page, even when a certain element stops the propagation?
In cooperation with Andy E, this is the dark side of the force:
var _old = jQuery.Event.prototype.stopPropagation;
jQuery.Event.prototype.stopPropagation = function() {
this.target.nodeName !== 'SPAN' && _old.apply( this, arguments );
};
Example: http://jsfiddle.net/M4teA/2/
Remember, if all the events were bound via jQuery, you can handle those cases just here. In this example, we just call the original .stopPropagation()
if we are not dealing with a <span>
.
You cannot prevent the prevent, no.
What you could do is, to rewrite those event handlers manually in-code. This is tricky business, but if you know how to access the stored handler methods, you could work around it. I played around with it a little, and this is my result:
$( document.body ).click(function() {
alert('Hi I am bound to the body!');
});
$( '#bar' ).click(function(e) {
alert('I am the span and I do prevent propagation');
e.stopPropagation();
});
$( '#yay' ).click(function() {
$('span').each(function(i, elem) {
var events = jQuery._data(elem).events,
oldHandler = [ ],
$elem = $( elem );
if( 'click' in events ) {
[].forEach.call( events.click, function( click ) {
oldHandler.push( click.handler );
});
$elem.off( 'click' );
}
if( oldHandler.length ) {
oldHandler.forEach(function( handler ) {
$elem.bind( 'click', (function( h ) {
return function() {
h.apply( this, [{stopPropagation: $.noop}] );
};
}( handler )));
});
}
});
this.disabled = 1;
return false;
});
Example: http://jsfiddle.net/M4teA/
Notice, the above code will only work with jQuery 1.7. If those click events were bound with an earlier jQuery version or "inline", you still can use the code but you would need to access the "old handler" differently.
I know I'm assuming a lot of "perfect world" scenario things here, for instance, that those handles explicitly call .stopPropagation()
instead of returning false
. So it still might be a useless academic example, but I felt to come out with it :-)
edit: hey, return false;
will work just fine, the event objects is accessed in the same way.
Setting the default Java character encoding
Solve this problem in my project. Hope it helps someone.
I use LIBGDX java framework and also had this issue in my android studio project.
In Mac OS encoding is correct, but in Windows 10 special characters and symbols and
also russian characters show as questions like: ????? and other incorrect symbols.
Change in android studio project settings:
File->Settings...->Editor-> File Encodings
to UTF-8 in all three fields (Global Encoding, Project Encoding and Default below).
In any java file set:
System.setProperty("file.encoding","UTF-8");
And for test print debug log:
System.out.println("My project encoding is : "+ Charset.defaultCharset());
Invalid length for a Base-64 char array
I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.
As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)
The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.
As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.
So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.
The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.
Here's some example code
string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));
Setting focus to iframe contents
This is something that worked for me, although it smells a bit wrong:
var iframe = ...
var doc = iframe.contentDocument;
var i = doc.createElement('input');
i.style.display = 'none';
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);
hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.
Creating a dynamic choice field
As pointed by Breedly and Liang, Ashok's solution will prevent you from getting the select value when posting the form.
One slightly different, but still imperfect, way to solve that would be:
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
super(waypointForm, self).__init__(*args, **kwargs)
This could cause some concurrence problems, though.
SVN Repository on Google Drive or DropBox
While possible, it's potentially very risky - if you attempt to commit changes to the repository from 2 different locations simultaneously, you'll get a giant mess due to the file conflicts. Get a free private SVN host somewhere, or set up a repository on a server you have access to.
Edit based on a recent experience: If you have files open that are managed by Dropbox and your computer crashes, your files may be truncated to 0 bytes. If this happens to the files which manage your repository, your repository will be corrupted. If you discover this soon enough, you can use Dropbox's "recover old version" feature but you're still taking a risk.
Wait until page is loaded with Selenium WebDriver for Python
Very good answers here. Quick example of wait for XPATH
.
# wait for sizes to load - 2s timeout
try:
WebDriverWait(driver, 2).until(expected_conditions.presence_of_element_located(
(By.XPATH, "//div[@id='stockSizes']//a")))
except TimeoutException:
pass
Regex for remove everything after | (with | )
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
how to fix java.lang.IndexOutOfBoundsException
This error happens because your list lstpp
is empty (Nothing at index 0). So either there is a bug in your getResult()
function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).
How do you get the process ID of a program in Unix or Linux using Python?
For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc
Works on python 2 and 3 ( The only difference is the Exception tree, therefore the "except Exception", which i dislike but kept to maintain compatibility. Also could've created custom exception.)
#!/usr/bin/env python
import os
import sys
for dirname in os.listdir('/proc'):
if dirname == 'curproc':
continue
try:
with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
content = fd.read().decode().split('\x00')
except Exception:
continue
for i in sys.argv[1:]:
if i in content[0]:
# dirname is also the number of PID
print('{0:<12} : {1}'.format(dirname, ' '.join(content)))
Sample Output (it works like pgrep):
phoemur ~/python $ ./pgrep.py bash
1487 : -bash
1779 : /bin/bash
Creating a comma separated list from IList<string> or IEnumerable<string>
We have a utility function, something like this:
public static string Join<T>( string delimiter,
IEnumerable<T> collection, Func<T, string> convert )
{
return string.Join( delimiter,
collection.Select( convert ).ToArray() );
}
Which can be used for joining lots of collections easily:
int[] ids = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233};
string csv = StringUtility.Join(",", ids, i => i.ToString() );
Note that we have the collection param before the lambda because intellisense then picks up the collection type.
If you already have an enumeration of strings all you need to do is the ToArray:
string csv = string.Join( ",", myStrings.ToArray() );
The operation cannot be completed because the DbContext has been disposed error
Objects exposed as IQueryable<T>
and IEnumerable<T>
don't actually "execute" until they are iterated over or otherwise accessed, such as being composed into a List<T>
. When EF returns an IQueryable<T>
it is essentially just composing something capable of retrieving data, it isn't actually performing the retrieve until you consume it.
You can get a feel for this by putting a breakpoint where the IQueryable
is defined, vs. when the .ToList()
is called. (From inside the scope of the data context as Jofry has correctly pointed out.) The work to pull the data is done during the ToList()
call.
Because of that, you need to keep the IQueryable<T>
within the scope of the data context.
What does asterisk * mean in Python?
I only have one thing to add that wasn't clear from the other answers (for completeness's sake).
You may also use the stars when calling the function. For example, say you have code like this:
>>> def foo(*args):
... print(args)
...
>>> l = [1,2,3,4,5]
You can pass the list l into foo like so...
>>> foo(*l)
(1, 2, 3, 4, 5)
You can do the same for dictionaries...
>>> def foo(**argd):
... print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}
How to convert TimeStamp to Date in Java?
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
Fetching distinct values on a column using Spark DataFrame
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
How to split strings over multiple lines in Bash?
Depending on what sort of risks you will accept and how well you know and trust the data, you can use simplistic variable interpolation.
$: x="
this
is
variably indented
stuff
"
$: echo "$x" # preserves the newlines and spacing
this
is
variably indented
stuff
$: echo $x # no quotes, stacks it "neatly" with minimal spacing
this is variably indented stuff
How to store a dataframe using Pandas
pyarrow compatibility across versions
Overall move has been to pyarrow/feather (deprecation warnings from pandas/msgpack). However I have a challenge with pyarrow with transient in specification Data serialized with pyarrow 0.15.1 cannot be deserialized with 0.16.0 ARROW-7961. I'm using serialization to use redis so have to use a binary encoding.
I've retested various options (using jupyter notebook)
import sys, pickle, zlib, warnings, io
class foocls:
def pyarrow(out): return pa.serialize(out).to_buffer().to_pybytes()
def msgpack(out): return out.to_msgpack()
def pickle(out): return pickle.dumps(out)
def feather(out): return out.to_feather(io.BytesIO())
def parquet(out): return out.to_parquet(io.BytesIO())
warnings.filterwarnings("ignore")
for c in foocls.__dict__.values():
sbreak = True
try:
c(out)
print(c.__name__, "before serialization", sys.getsizeof(out))
print(c.__name__, sys.getsizeof(c(out)))
%timeit -n 50 c(out)
print(c.__name__, "zlib", sys.getsizeof(zlib.compress(c(out))))
%timeit -n 50 zlib.compress(c(out))
except TypeError as e:
if "not callable" in str(e): sbreak = False
else: raise
except (ValueError) as e: print(c.__name__, "ERROR", e)
finally:
if sbreak: print("=+=" * 30)
warnings.filterwarnings("default")
With following results for my data frame (in out
jupyter variable)
pyarrow before serialization 533366
pyarrow 120805
1.03 ms ± 43.9 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pyarrow zlib 20517
2.78 ms ± 81.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
msgpack before serialization 533366
msgpack 109039
1.74 ms ± 72.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
msgpack zlib 16639
3.05 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
pickle before serialization 533366
pickle 142121
733 µs ± 38.3 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pickle zlib 29477
3.81 ms ± 60.4 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
feather ERROR feather does not support serializing a non-default index for the index; you can .reset_index() to make the index into column(s)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
parquet ERROR Nested column branch had multiple children: struct<x: double, y: double>
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
feather and parquet do not work for my data frame. I'm going to continue using pyarrow. However I will supplement with pickle (no compression). When writing to cache store pyarrow and pickle serialised forms. When reading from cache fallback to pickle if pyarrow deserialisation fails.
Twitter bootstrap float div right
You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.
Bootstrap 3
v3 Text Alignment Docs
<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>
Bootstrap 4
v4 Text Alignment Docs
<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>
<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>
Rename package in Android Studio
3 Methods to change package name in Android Studio
I think this is a new one. I tried it and it's working. If above doesn't work for you. Try this. The site I mentioned above, there are 2 other methods too with image tutorial. I also checked.
First I am going to talk about changing the Package name. In this example, We will change the package name “com.androidride.myapplication” to “info.xyz.yourapplication”.
- Right Click on the package name you want to change and select Refactor - > Move.
- A new dialog appears, Choose Move package “com.androidride.myapplication” to another package and click on Ok.
- A warning dialog appears, click on yes.
- Enter new package name in the new dialog. But only “info.xyz” leave yourapplication.
- Now you will see a warning dialog says Package info.xyz does not exist. Do you want to create it? click on yes.
- Click on “Do Refactor”. Now your package name changed to info.xyz.myapplication.
- Right click on info.xyz.myapplication and Refactor -> Rename.
- Click on Rename package.
- Rename dialog: change myapplication to yourapplication.
- Click on Do refactor.
- Delete old package name directories and change application id in build.gradle, change it into info.xyz.yourapplication.
- That's all.
Changing EditText bottom line color with appcompat v7
Here is the solution for API < 21 and above
Drawable drawable = yourEditText.getBackground(); // get current EditText drawable
drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP); // change the drawable color
if(Build.VERSION.SDK_INT > 16) {
yourEditText.setBackground(drawable); // set the new drawable to EditText
}else{
yourEditText.setBackgroundDrawable(drawable); // use setBackgroundDrawable because setBackground required API 16
}
Hope it help