Python integer division yields float
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like +
, -
, *
and /
to special functions, such that e.g. a + b
is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only /
which maps to __div__
and the result is dependent on the input types (e.g. int
, float
).
Python 2.2 introduced the __future__
feature division
, which changed the division semantics the following way (TL;DR of PEP 238):
/
maps to __truediv__
which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)
//
maps to __floordiv__
, which should return the floored result of /
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__
in Python's object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of /
and //
.
"Actual or formal argument lists differs in length"
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
SQL Server Error : String or binary data would be truncated
You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.
In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.
How can I roll back my last delete command in MySQL?
I also had deleted some values from my development database, but I had the same copy in QA database, so I did a generate script and selected option "type of data to script" to "data only" and selected my table.
Then I got the insert statements with same data, and then I run the script on my development database.
Get the current URL with JavaScript?
Use window.location
for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL
, which should contain the same value as window.location.href
.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
How can I get all sequences in an Oracle database?
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Loop and get key/value pair for JSON array using jQuery
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.
Since the accepted answer requires IIS Manager, and IIS Express doesn't have IIS Manager or any UI, here's the solution for you IIS Express users (and should work for everyone else too):
When you open Visual Studio and get the error message, right-click the project Solution Explorer and choose "Edit {ProjectName}.csproj"
In the project file, change the following line:
<UseIIS>True</UseIIS>
to
<UseIIS>False</UseIIS>
Save the file.
Now reload your project.
Done.
You'll then be able to open your project. If at this point, you want to use IIS, simply go to your project properties, click the "Web" tab, and select the option to use IIS. There's the button there to "Create Virtual Directory". It may tell you that you need to run Visual Studio as an administrator to create that directory, so do that if needed.
pod has unbound PersistentVolumeClaims
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
To solve your issue:
- Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
- Remove the
storageClass
-line from the PersistentVolumeClaim
- Remove the StorageClass from your cluster
How do these pieces play together?
At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand.
In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
Example PersistentVolume
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Additional Resources:
How to affect other elements when one element is hovered
Using the sibling selector is the general solution for styling other elements when hovering over a given one, but it works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:
This can actually be done easily using the CSS flexbox model, by setting flex-direction
to reverse
, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.
Flexbox is very well supported by 95% of modern browsers.
_x000D_
_x000D_
.rating {_x000D_
display: flex;_x000D_
flex-direction: row-reverse;_x000D_
width: 9rem;_x000D_
}_x000D_
.rating div {_x000D_
flex: 1;_x000D_
align-self: flex-end;_x000D_
background-color: black;_x000D_
border: 0.1rem solid white;_x000D_
}_x000D_
.rating div:hover {_x000D_
background-color: lightblue;_x000D_
}_x000D_
.rating div[data-rating="1"] {_x000D_
height: 5rem;_x000D_
}_x000D_
.rating div[data-rating="2"] {_x000D_
height: 4rem;_x000D_
}_x000D_
.rating div[data-rating="3"] {_x000D_
height: 3rem;_x000D_
}_x000D_
.rating div[data-rating="4"] {_x000D_
height: 2rem;_x000D_
}_x000D_
.rating div[data-rating="5"] {_x000D_
height: 1rem;_x000D_
}_x000D_
.rating div:hover ~ div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div class="rating">_x000D_
<div data-rating="1"></div>_x000D_
<div data-rating="2"></div>_x000D_
<div data-rating="3"></div>_x000D_
<div data-rating="4"></div>_x000D_
<div data-rating="5"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Understanding events and event handlers in C#
C# knows two terms, delegate
and event
. Let's start with the first one.
Delegate
A delegate
is a reference to a method. Just like you can create a reference to an instance:
MyClass instance = myFactory.GetInstance();
You can use a delegate to create an reference to a method:
Action myMethod = myFactory.GetInstance;
Now that you have this reference to a method, you can call the method via the reference:
MyClass instance = myMethod();
But why would you? You can also just call myFactory.GetInstance()
directly. In this case you can. However, there are many cases to think about where you don't want the rest of the application to have knowledge of myFactory
or to call myFactory.GetInstance()
directly.
An obvious one is if you want to be able to replace myFactory.GetInstance()
into myOfflineFakeFactory.GetInstance()
from one central place (aka factory method pattern).
Factory method pattern
So, if you have a TheOtherClass
class and it needs to use the myFactory.GetInstance()
, this is how the code will look like without delegates (you'll need to let TheOtherClass
know about the type of your myFactory
):
TheOtherClass toc;
//...
toc.SetFactory(myFactory);
class TheOtherClass
{
public void SetFactory(MyFactory factory)
{
// set here
}
}
If you'd use delegates, you don't have to expose the type of my factory:
TheOtherClass toc;
//...
Action factoryMethod = myFactory.GetInstance;
toc.SetFactoryMethod(factoryMethod);
class TheOtherClass
{
public void SetFactoryMethod(Action factoryMethod)
{
// set here
}
}
Thus, you can give a delegate to some other class to use, without exposing your type to them. The only thing you're exposing is the signature of your method (how many parameters you have and such).
"Signature of my method", where did I hear that before? O yes, interfaces!!! interfaces describe the signature of a whole class. Think of delegates as describing the signature of only one method!
Another large difference between an interface and a delegate is that when you're writing your class, you don't have to say to C# "this method implements that type of delegate". With interfaces, you do need to say "this class implements that type of an interface".
Further, a delegate reference can (with some restrictions, see below) reference multiple methods (called MulticastDelegate
). This means that when you call the delegate, multiple explicitly-attached methods will be executed. An object reference can always only reference to one object.
The restrictions for a MulticastDelegate
are that the (method/delegate) signature should not have any return value (void
) and the keywords out
and ref
is not used in the signature. Obviously, you can't call two methods that return a number and expect them to return the same number. Once the signature complies, the delegate is automatically a MulticastDelegate
.
Event
Events are just properties (like the get;set; properties to instance fields) which expose subscription to the delegate from other objects. These properties, however, don't support get;set;. Instead, they support add; remove;
So you can have:
Action myField;
public event Action MyProperty
{
add { myField += value; }
remove { myField -= value; }
}
Usage in UI (WinForms,WPF,UWP So on)
So, now we know that a delegate is a reference to a method and that we can have an event to let the world know that they can give us their methods to be referenced from our delegate, and we are a UI button, then: we can ask anyone who is interested in whether I was clicked, to register their method with us (via the event we exposed). We can use all those methods that were given to us and reference them by our delegate. And then, we'll wait and wait.... until a user comes and clicks on that button, then we'll have enough reason to invoke the delegate. And because the delegate references all those methods given to us, all those methods will be invoked. We don't know what those methods do, nor we know which class implements those methods. All we do care about is that someone was interested in us being clicked, and gave us a reference to a method that complied with our desired signature.
Java
Languages like Java don't have delegates. They use interfaces instead. The way they do that is to ask anyone who is interested in 'us being clicked', to implement a certain interface (with a certain method we can call), then give us the whole instance that implements the interface. We keep a list of all objects implementing this interface and can call their 'certain method we can call' whenever we get clicked.
How to add a changed file to an older (not last) commit in Git
To "fix" an old commit with a small change, without changing the commit message of the old commit, where OLDCOMMIT
is something like 091b73a
:
git add <my fixed files>
git commit --fixup=OLDCOMMIT
git rebase --interactive --autosquash OLDCOMMIT^
You can also use git commit --squash=OLDCOMMIT
to edit the old commit message during rebase.
See documentation for git commit and git rebase. As always, when rewriting git history, you should only fixup or squash commits you have not yet published to anyone else (including random internet users and build servers).
Detailed explanation
git commit --fixup=OLDCOMMIT
copies the OLDCOMMIT
commit message and automatically prefixes fixup!
so it can be put in the correct order during interactive rebase. (--squash=OLDCOMMIT
does the same but prefixes squash!
.)
git rebase --interactive
will bring up a text editor (which can be configured) to confirm (or edit) the rebase instruction sequence. There is info for rebase instruction changes in the file; just save and quit the editor (:wq
in vim
) to continue with the rebase.
--autosquash
will automatically put any --fixup=OLDCOMMIT
commits in the correct order. Note that --autosquash
is only valid when the --interactive
option is used.
- The
^
in OLDCOMMIT^
means it's a reference to the commit just before OLDCOMMIT
. (OLDCOMMIT^
is the first parent of OLDCOMMIT
.)
Optional automation
The above steps are good for verification and/or modifying the rebase instruction sequence, but it's also possible to skip/automate the interactive rebase text editor by:
What is difference between mutable and immutable String in java
Case 1:
String str = "Good";
str = str + " Morning";
In the above code you create 3 String
Objects.
- "Good" it goes into the String Pool.
- " Morning" it goes into the String Pool as well.
- "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.
Note: Strings are always immutable. There is no, such thing as a mutable String. str
is just a reference which eventually points to "Good Morning". You are actually, not working on 1
object. you have 3
distinct String
Objects.
Case 2:
StringBuffer str = new StringBuffer("Good");
str.append(" Morning");
StringBuffer
contains an array of characters. It is not same as a String
.
The above code adds characters to the existing array. Effectively, StringBuffer
is mutable, its String
representation isn't.
How do I convert an integer to binary in JavaScript?
The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)
1. Number System
(123456).toString(2)
will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.
2. Internal Representation
The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.
3. Masks & Bitwise Operators
MDN has a good overview of how bitwise operators work. Importantly:
Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)
Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.
Here is the MDN example code for converting numbers into 32-bit strings.
function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
return sMask;
}
createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"
SyntaxError: multiple statements found while compiling a single statement
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
Input mask for numeric and decimal
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
Bootstrap full-width text-input within inline-form
With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.
_x000D_
_x000D_
.prop-label {_x000D_
margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="col-12">_x000D_
<div class="d-flex">_x000D_
<label class="flex-fill prop-label">Label:</label>_x000D_
<input type="text" class="flex-fill form-control prop-field">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Postgres could not connect to server
Had a similar problem; a pid file was blocking postgres from starting up. To fix it:
$ rm /usr/local/var/postgres/postmaster.pid
$ brew services restart postgresql
and then all is well.
Python Linked List
For some needs, a deque may also be useful. You can add and remove items on both ends of a deque at O(1) cost.
from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
How do I rename the android package name?
I found a good work around for this problem. Taking the example mentioned in the question, following are the steps for changing the package name from com.example.test
to com.example2.test
:
- create a temporary directory, say
temp
inside the directory example
(alongside directory test
).
- Go back to the Intellij project, select the folder
com.example
and Click Shift + F6
. Now it offers to rename the text example
. Here you can enter the new text you want and IntelliJ will do the rest for you.
- Delete the temporary directory
temp
from the file system.
This idea can be used to refactor any part of the package name.
Good luck!!
How can I change an element's class with JavaScript?
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
see jsfiddle
also see my answer here for creating a new class dynamically
Virtual Serial Port for Linux
Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example .
The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command.
And that's it. You have a bidirectional link between the two process.
Using this example you can test you the application by sending all kind of data, and see if it works correctly.
Also, you can always symlink the device, so you don't need to re-compile the application you are testing.
Explain __dict__ attribute
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
How to pull remote branch from somebody else's repo
GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:
- Scroll to the bottom of the PR to see the
Merge
or Squash and merge
button
- Click the link on the right:
view command line instructions
- Press the Copy icon to the right of Step 1
- Paste the commands in your terminal
How to remove trailing and leading whitespace for user-provided input in a batch file?
I've found that all solution introduced here are not complete enough for me and does not work in one or another case.
CAUTION:
Seems the stackoverflow incorrectly handles tabulation characters (and loses other characters like \x01
) in the copy-pasted code, so the below code might not work if you copy it directly by CTRL+C. Use the link at the end to directly download the scripts.
trim_var.bat:
@echo off
rem drop the output variable value
if not "%~2" == "" if not "%~1" == "%~2" set "%~2="
if not defined %~1 exit /b 0
setlocal DISABLEDELAYEDEXPANSION
rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"
:TRIM_LEFT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~0,1%/ == ^ / if not ^%RETURN_VALUE:~0,1%/ == ^ / goto TRIM_RIGHT_LOOP
set "RETURN_VALUE=%RETURN_VALUE:~1%"
if not defined RETURN_VALUE exit /b 0
goto TRIM_LEFT_LOOP
:TRIM_RIGHT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~-1%/ == ^ / if not ^%RETURN_VALUE:~-1%/ == ^ / goto TRIM_RIGHT_LOOP_END
set "RETURN_VALUE=%RETURN_VALUE:~0,-1%"
goto TRIM_RIGHT_LOOP
:TRIM_RIGHT_LOOP_END
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"
rem safe set
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
endlocal
endlocal
if not "%~2" == "" (
set "%~2=%%j"
) else (
set "%~1=%%j"
)
)
exit /b 0
echo_var.bat:
@echo off
if not defined %~1 (
echo.%~2%~3
exit /b 0
)
setlocal DISABLEDELAYEDEXPANSION
rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"
rem safe echo
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
endlocal
endlocal
echo.%~2%%j%~3
)
exit /b 0
test_trim_var.bat:
@echo off
setlocal DISABLEDELAYEDEXPANSION
set myvar1= 1 ! 2 ^| 3 ^& 4 ^^ 5 = 6 , 7 ; 8 * 9 # 0 %% 1 / 2 \ 3 ? 4 ^> 5 ^< 6 " 7
call "trim_var.bat" myvar1 myvar2
call "echo_var.bat" myvar1 - -
call "echo_var.bat" myvar2 - -
Output:
- 1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7 -
-1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7-
The latest implementation: https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/std/trim_var.bat
Pros:
- Safely handles almost all specific characters like
!
, %
, ^
, "
.
Cons:
- The
"
character replaces by the \x01
character and might be affected by current code page (not tested).
How do I enter a multi-line comment in Perl?
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
"UnboundLocalError: local variable referenced before assignment" after an if statement
Your if
statement is always false and T
gets initialized only if a condition is met, so the code doesn't reach the point where T
gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.
Try:
def temp_sky(lreq, breq):
T = <some_default_value> # None is often a good pick
for line in tfile:
data = line.split()
if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:
T = data[2]
return T
Generating Random Passwords
I created this method similar to the available in the membership provider. This is usefull if you don't want to add the web reference in some applications.
It works great.
public static string GeneratePassword(int Length, int NonAlphaNumericChars)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
string allowedNonAlphaNum = "!@#$%^&*()_-+=[{]};:<>|./?";
Random rd = new Random();
if (NonAlphaNumericChars > Length || Length <= 0 || NonAlphaNumericChars < 0)
throw new ArgumentOutOfRangeException();
char[] pass = new char[Length];
int[] pos = new int[Length];
int i = 0, j = 0, temp = 0;
bool flag = false;
//Random the position values of the pos array for the string Pass
while (i < Length - 1)
{
j = 0;
flag = false;
temp = rd.Next(0, Length);
for (j = 0; j < Length; j++)
if (temp == pos[j])
{
flag = true;
j = Length;
}
if (!flag)
{
pos[i] = temp;
i++;
}
}
//Random the AlphaNumericChars
for (i = 0; i < Length - NonAlphaNumericChars; i++)
pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];
//Random the NonAlphaNumericChars
for (i = Length - NonAlphaNumericChars; i < Length; i++)
pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];
//Set the sorted array values by the pos array for the rigth posistion
char[] sorted = new char[Length];
for (i = 0; i < Length; i++)
sorted[i] = pass[pos[i]];
string Pass = new String(sorted);
return Pass;
}
How to remove gaps between subplots in matplotlib?
The problem is the use of aspect='equal'
, which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.
Normally, this would work:
import matplotlib.pyplot as plt
ax = [plt.subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
plt.subplots_adjust(wspace=0, hspace=0)
The result is this:
However, with aspect='equal'
, as in the following code:
import matplotlib.pyplot as plt
ax = [plt.subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')
plt.subplots_adjust(wspace=0, hspace=0)
This is what we get:
The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal'
forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.
To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')
fig.subplots_adjust(wspace=0, hspace=0)
Here's the result:
How do I sum values in a column that match a given condition using pandas?
The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.
Boolean indexing
Arguably the most common way to select the values is to use Boolean indexing.
With this method, you find out where column 'a' is equal to 1
and then sum the corresponding rows of column 'b'. You can use loc
to handle the indexing of rows and columns:
>>> df.loc[df['a'] == 1, 'b'].sum()
15
The Boolean indexing can be extended to other columns. For example if df
also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:
df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()
Query
Another way to select the data is to use query
to filter the rows you're interested in, select column 'b' and then sum:
>>> df.query("a == 1")['b'].sum()
15
Again, the method can be extended to make more complicated selections of the data:
df.query("a == 1 and c == 2")['b'].sum()
Note this is a little more concise than the Boolean indexing approach.
Groupby
The alternative approach is to use groupby
to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:
>>> df.groupby('a')['b'].sum()[1]
15
This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a
:
>>> df.groupby('a')['b'].sum()
a
1 15
2 8
Logical Operators, || or OR?
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
How to debug a stored procedure in Toad?
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging:
Execute PL/SQL with debugger ()
Step over
Step into
Run to cursor
How to store custom objects in NSUserDefaults
On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.question forKey:@"question"];
[encoder encodeObject:self.categoryName forKey:@"category"];
[encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.question = [decoder decodeObjectForKey:@"question"];
self.categoryName = [decoder decodeObjectForKey:@"category"];
self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
}
return self;
}
Reading and writing from NSUserDefaults
:
- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:key];
[defaults synchronize];
}
- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
Code shamelessly borrowed from: saving class in nsuserdefaults
Multiple submit buttons in the same form calling different Servlets
There are several ways to achieve this.
Probably the easiest would be to use JavaScript to change the form's action.
<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">
But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).
Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.
<form action="FirstServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
<input type="submit"value="SecondServlet">
</form>
Note that a form would on submit only send the input data contained in the very same form, not in the other form.
Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name
):
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="action" value="FirstServlet">
<input type="submit" name="action" value="SecondServlet">
</form>
with the following in MainServlet
String action = request.getParameter("action");
if ("FirstServlet".equals(action)) {
// Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
// Invoke SecondServlet's job here.
}
This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?
A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="first" value="FirstServlet">
<input type="submit" name="second" value="SecondServlet">
</form>
with the following in MainServlet
if (request.getParameter("first") != null) {
// Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
// Invoke SecondServlet's job here.
}
Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.
<h:form>
Last Name: <h:inputText value="#{bean.lastName}" size="20" />
<br/><br/>
<h:commandButton value="First" action="#{bean.first}" />
<h:commandButton value="Second" action="#{bean.Second}" />
</h:form>
with just the following javabean instead of a servlet
@ManagedBean
@RequestScoped
public class Bean {
private String lastName; // +getter+setter
public void first() {
// Invoke original FirstServlet's job here.
}
public void second() {
// Invoke original SecondServlet's job here.
}
}
Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
JSLint says "missing radix parameter"
Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.
So Instead of :
var num = parseInt("071"); // 57
Do this:
var num = parseInt("071", 10); // 71
var num = parseInt("071", 8);
var num = parseFloat(someValue);
Reference
import an array in python
Another option is numpy.genfromtxt
, e.g:
import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")
This will make data
a numpy array with as many rows and columns as are in your file
How to output in CLI during execution of PHP Unit tests?
For some cases one could use something like that to output something to the console
class yourTests extends PHPUnit_Framework_TestCase
{
/* Add Warnings */
protected function addWarning($msg, Exception $previous = null)
{
$add_warning = $this->getTestResultObject();
$msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
$add_warning->addWarning($this, $msg, time());
$this->setTestResultObject($add_warning);
}
/* Add errors */
protected function addError($msg, Exception $previous = null)
{
$add_error = $this->getTestResultObject();
$msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
$add_error->addError($this, $msg, time());
$this->setTestResultObject($add_error);
}
/* Add failures */
protected function addFailure($msg, Exception $previous = null)
{
$add_failure = $this->getTestResultObject();
$msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
$add_failure->addFailure($this, $msg, time());
$this->setTestResultObject($add_failure);
}
public function test_messages()
{
$this->addWarning("Your warning message!");
$this->addError("Your error message!");
$this->addFailure("Your Failure message");
}
/* Or just mark test states! */
public function test_testMarking()
{
$this->markTestIncomplete();
$this->markTestSkipped();
}
}
pip or pip3 to install packages for Python 3?
By illustration:
pip --version
pip 19.0.3 from /usr/lib/python3.7/site-packages/pip (python 3.7)
pip3 --version
pip 19.0.3 from /usr/lib/python3.7/site-packages/pip (python 3.7)
python --version
Python 3.7.3
which python
/usr/bin/python
ls -l '/usr/bin/python'
lrwxrwxrwx 1 root root 7 Mar 26 14:43 /usr/bin/python -> python3
which python3
/usr/bin/python3
ls -l /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 26 14:43 /usr/bin/python3 -> python3.7
ls -l /usr/bin/python3.7
-rwxr-xr-x 2 root root 14120 Mar 26 14:43 /usr/bin/python3.7
Thus, my in my default system python (Python 3.7.3), pip
is pip3
.
How to disable the back button in the browser using JavaScript
Our approach is simple, but it works! :)
When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.
<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
function logOut() {
window.close = function () {
window.open('Default.aspx', '_blank');
};
}
</script>
Understanding .get() method in Python
To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.
Remember that we start off with an empty characters dictionary
characters = {}
I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{}['e'] = {}.get('e', 0) + 1
characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation).
After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}
The dictionary is now:
characters = {'e': 1}
Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{'e': 1}['e'] = {'e': 1}.get('e', 0) + 1
Here the get method finds a key entry for 'e' and finds its value which is 1.
We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.
When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:
characters['e'] = 2
It should be clear that the last equation assigns a new value 2 to the already present 'e' key.
Therefore the dictionary is now:
characters = {'e': 2}
How to check certificate name and alias in keystore files?
You can run the following command to list the content of your keystore file (and alias name):
keytool -v -list -keystore .keystore
If you are looking for a specific alias, you can also specify it in the command:
keytool -list -keystore .keystore -alias foo
If the alias is not found, it will display an exception:
keytool error: java.lang.Exception: Alias does not exist
Getting raw SQL query string from PDO prepared statements
You can use sprintf(str_replace('?', '"%s"', $sql), ...$params);
Here is an example:
function mysqli_prepared_query($link, $sql, $types='', $params=array()) {
echo sprintf(str_replace('?', '"%s"', $sql), ...$params);
//prepare, bind, execute
}
$link = new mysqli($server, $dbusername, $dbpassword, $database);
$sql = "SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?";
$types = "is"; //integer and string
$params = array(20, "Brown");
if(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){
echo "Failed";
} else {
echo "Success";
}
Note this only works for PHP >= 5.6
Pythonic way to find maximum value and its index in a list?
This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.
import random
from datetime import datetime
import operator
import numpy as np
def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val
def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val
def npmax(l):
max_idx = np.argmax(l)
max_val = l[max_idx]
return (max_idx, max_val)
if __name__ == "__main__":
from timeit import Timer
t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
"import random; import operator; import numpy as np;"
"l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
Results on my computer:
Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass
open a url on click of ok button in android
On Button
click event write this:
Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
that open the your URL.
update one table with data from another
Oracle 11g R2:
create table table1 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
create table table2 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');
insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');
merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;
select * from table1;
ID NAME DESC_
---------- ---------- ----------
1 x 123
2 y 456
3 c ghi
See also Oracle - Update statement with inner join.
How to set iframe size dynamically
If you use jquery, it can be done by using $(window).height();
<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>
<script type="text/javascript" language="javascript">
$('.myIframe').css('height', $(window).height()+'px');
</script>
Process escape sequences in a string in Python
unicode_escape
doesn't work in general
It turns out that the string_escape
or unicode_escape
solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.
If you can be sure that every non-ASCII character will be escaped (and remember, anything beyond the first 128 characters is non-ASCII), unicode_escape
will do the right thing for you. But if there are any literal non-ASCII characters already in your string, things will go wrong.
unicode_escape
is fundamentally designed to convert bytes into Unicode text. But in many places -- for example, Python source code -- the source data is already Unicode text.
The only way this can work correctly is if you encode the text into bytes first. UTF-8 is the sensible encoding for all text, so that should work, right?
The following examples are in Python 3, so that the string literals are cleaner, but the same problem exists with slightly different manifestations on both Python 2 and 3.
>>> s = 'naïve \\t test'
>>> print(s.encode('utf-8').decode('unicode_escape'))
naïve test
Well, that's wrong.
The new recommended way to use codecs that decode text into text is to call codecs.decode
directly. Does that help?
>>> import codecs
>>> print(codecs.decode(s, 'unicode_escape'))
naïve test
Not at all. (Also, the above is a UnicodeError on Python 2.)
The unicode_escape
codec, despite its name, turns out to assume that all non-ASCII bytes are in the Latin-1 (ISO-8859-1) encoding. So you would have to do it like this:
>>> print(s.encode('latin-1').decode('unicode_escape'))
naïve test
But that's terrible. This limits you to the 256 Latin-1 characters, as if Unicode had never been invented at all!
>>> print('Erno \\t Rubik'.encode('latin-1').decode('unicode_escape'))
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151'
in position 3: ordinal not in range(256)
Adding a regular expression to solve the problem
(Surprisingly, we do not now have two problems.)
What we need to do is only apply the unicode_escape
decoder to things that we are certain to be ASCII text. In particular, we can make sure only to apply it to valid Python escape sequences, which are guaranteed to be ASCII text.
The plan is, we'll find escape sequences using a regular expression, and use a function as the argument to re.sub
to replace them with their unescaped value.
import re
import codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U........ # 8-digit hex escapes
| \\u.... # 4-digit hex escapes
| \\x.. # 2-digit hex escapes
| \\[0-7]{1,3} # Octal escapes
| \\N\{[^}]+\} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
And with that:
>>> print(decode_escapes('Erno \\t Rubik'))
Erno Rubik
mssql '5 (Access is denied.)' error during restoring database
this happened to me earlier today, i was a member of the local server's admin group and have unimpeded access, or i thought so. I also ticked the "replace" option, even though there is no such DB in the instance.
Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can't ovewrwrite the existing files. Found out also that the files' owner is "unknown", i had to change ownership, to the 2 files above so that it is now owned by the local server's admin group, then renamed it.
Then finally, it worked.
How to convert a char to a String?
As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf
. Here is benchmark that proves that:
@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
public class CharToStringConversion {
private char c = 'c';
@Benchmark
public String stringValueOf() {
return String.valueOf(c);
}
@Benchmark
public String stringValueOfCharArray() {
return String.valueOf(new char[]{c});
}
@Benchmark
public String characterToString() {
return Character.toString(c);
}
@Benchmark
public String characterObjectToString() {
return new Character(c).toString();
}
@Benchmark
public String concatBlankStringPre() {
return c + "";
}
@Benchmark
public String concatBlankStringPost() {
return "" + c;
}
@Benchmark
public String fromCharArray() {
return new String(new char[]{c});
}
}
And result:
Benchmark Mode Cnt Score Error Units
CharToStringConversion.characterObjectToString thrpt 10 82132.021 ± 6841.497 ops/s
CharToStringConversion.characterToString thrpt 10 118232.069 ± 8242.847 ops/s
CharToStringConversion.concatBlankStringPost thrpt 10 136960.733 ± 9779.938 ops/s
CharToStringConversion.concatBlankStringPre thrpt 10 137244.446 ± 9113.373 ops/s
CharToStringConversion.fromCharArray thrpt 10 85464.842 ± 3127.211 ops/s
CharToStringConversion.stringValueOf thrpt 10 119281.976 ± 7053.832 ops/s
CharToStringConversion.stringValueOfCharArray thrpt 10 86563.837 ± 6436.527 ops/s
As you can see, the fastest one would be c + ""
or "" + c
;
VM version: JDK 1.8.0_131, VM 25.131-b11
This performance difference is due to -XX:+OptimizeStringConcat
optimization. You can read about it here.
What integer hash function are good that accepts an integer hash key?
For random hash values, some engineers said golden ratio prime number(2654435761) is a bad choice, with my testing results, I found that it's not true; instead, 2654435761 distributes the hash values pretty good.
#define MCR_HashTableSize 2^10
unsigned int
Hash_UInt_GRPrimeNumber(unsigned int key)
{
key = key*2654435761 & (MCR_HashTableSize - 1)
return key;
}
The hash table size must be a power of two.
I have written a test program to evaluate many hash functions for integers, the results show that GRPrimeNumber is a pretty good choice.
I have tried:
- total_data_entry_number / total_bucket_number = 2, 3, 4; where total_bucket_number = hash table size;
- map hash value domain into bucket index domain; that is, convert hash value into bucket index by Logical And Operation with (hash_table_size - 1), as shown in Hash_UInt_GRPrimeNumber();
- calculate the collision number of each bucket;
- record the bucket that has not been mapped, that is, an empty bucket;
- find out the max collision number of all buckets; that is, the longest chain length;
With my testing results, I found that Golden Ratio Prime Number always has the fewer empty buckets or zero empty bucket and the shortest collision chain length.
Some hash functions for integers are claimed to be good, but the testing results show that when the total_data_entry / total_bucket_number = 3, the longest chain length is bigger than 10(max collision number > 10), and many buckets are not mapped(empty buckets), which is very bad, compared with the result of zero empty bucket and longest chain length 3 by Golden Ratio Prime Number Hashing.
BTW, with my testing results, I found one version of shifting-xor hash functions is pretty good(It's shared by mikera).
unsigned int Hash_UInt_M3(unsigned int key)
{
key ^= (key << 13);
key ^= (key >> 17);
key ^= (key << 5);
return key;
}
Bootstrap 3 Navbar with Logo
I use the img-responsive class and then set a max-width on the a
element. Like this:
<nav class="navbar">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<img class="img-responsive" src="mylogo.png">
</a>
</div>
</nav>
and the CSS:
.navbar-brand {
max-width: 50%;
}
str.startswith with a list of strings to test for
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return True
if string starts with the prefix
, otherwise return False
. prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
CSS selector (id contains part of text)
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}
How to make a JFrame Modal in Swing java
just replace JFrame
to JDialog
in class
public class MyDialog extends JFrame // delete JFrame and write JDialog
and then write setModal(true);
in constructor
After that you will be able to construct your Form in netbeans
and the form becomes modal
How to list files using dos commands?
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
cursor.fetchall() vs list(cursor) in Python
list(cursor)
works because a cursor is an iterable; you can also use cursor
in a loop:
for row in cursor:
# ...
A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall()
has to return the full list instead.
There is little point in using list(cursor)
over cursor.fetchall()
; the end effect is then indeed the same, but you wasted an opportunity to stream results instead.
How do I bind to list of checkbox values with AngularJS?
You can combine AngularJS and jQuery. For example, you need to define an array, $scope.selected = [];
, in the controller.
<label ng-repeat="item in items">
<input type="checkbox" ng-model="selected[$index]" ng-true-value="'{{item}}'">{{item}}
</label>
You can get an array owning the selected items. Using method alert(JSON.stringify($scope.selected))
, you can check the selected items.
Passing parameters to click() & bind() event in jquery?
An alternative for the bind() method.
Use the click() method, do something like this:
commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);
function onClickCommentBtn(event)
{
alert("Id=" + event.data.id + ", Name = " + event.data.name);
}
Or, if you prefer:
commentbtn.click({id: 10, name: "João"}, function (event) {
alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});
It will show an alert box with the following infos:
Id = 10, Name = João
C++ Best way to get integer division and remainder
All else being equal, the best solution is one that clearly expresses your intent. So:
int totalSeconds = 453;
int minutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;
is probably the best of the three options you presented. As noted in other answers however, the div
method will calculate both values for you at once.
How to write a simple Html.DropDownListFor()?
Or if it's from a database context you can use
@Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
What is the ideal data type to use when storing latitude / longitude in a MySQL database?
Depends on the precision that you require.
Datatype Bytes resolution
------------------ ----- --------------------------------
Deg*100 (SMALLINT) 4 1570 m 1.0 mi Cities
DECIMAL(4,2)/(5,2) 5 1570 m 1.0 mi Cities
SMALLINT scaled 4 682 m 0.4 mi Cities
Deg*10000 (MEDIUMINT) 6 16 m 52 ft Houses/Businesses
DECIMAL(6,4)/(7,4) 7 16 m 52 ft Houses/Businesses
MEDIUMINT scaled 6 2.7 m 8.8 ft
FLOAT 8 1.7 m 5.6 ft
DECIMAL(8,6)/(9,6) 9 16cm 1/2 ft Friends in a mall
Deg*10000000 (INT) 8 16mm 5/8 in Marbles
DOUBLE 16 3.5nm ... Fleas on a dog
From: http://mysql.rjweb.org/doc.php/latlng
To summarise:
- The most precise available option is
DOUBLE
.
- The most common seen type used is
DECIMAL(8,6)/(9,6)
.
As of MySQL 5.7, consider using Spatial Data Types (SDT), specifically POINT
for storing a single coordinate. Prior to 5.7, SDT does not support indexes (with exception of 5.6 when table type is MyISAM).
Note:
- When using
POINT
class, the order of the arguments for storing coordinates must be POINT(latitude, longitude)
.
- There is a special syntax for creating a spatial index.
- The biggest benefit of using SDT is that you have access to Spatial Analyses Functions, e.g. calculating distance between two points (
ST_Distance
) and determining whether one point is contained within another area (ST_Contains
).
How to draw vectors (physical 2D/3D vectors) in MATLAB?
% draw simple vector from pt a to pt b
% wtr : with respect to
scale=0;%for drawin vectors with true scale
a = [10 20 30];% wrt origine O(0,0,0)
b = [10 10 20];% wrt origine O(0,0,0)
starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point a = to vector a
c = b-a;% c is the new coordinates of b wrt origine a
ends=c;%
plot3(a(1),a(2),a(3),'*b')
hold on
plot3(b(1),b(2),b(3),'*g')
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
% axis equal
hold off
How to use PHP string in mySQL LIKE query?
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
PHP: Split string into array, like explode with no delimiter
$array = str_split("$string");
will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use
do {
$array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters
SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/
On Windows you'll have to use HTTP
source to update gem
then change back to using HTTPS
.
gem sources -r https://rubygems.org/
gem sources -a http://rubygems.org/
gem update --system
gem sources -r http://rubygems.org/
gem sources -a https://rubygems.org/
Edit: Warning I'm not sure if this is safe. Does anyone know if ruby packages are signed? The accepted answer looks like a better solution.
Is there any boolean type in Oracle databases?
Not only is the boolean datatype missing in Oracle's SQL (not PL/SQL), but they also have no clear recommendation about what to use instead. See this thread on asktom. From recommending CHAR(1) 'Y'/'N'
they switch to NUMBER(1) 0/1
when someone points out that 'Y'/'N'
depends on the English language, while e.g. German programmers might use 'J'/'N'
instead.
The worst thing is that they defend this stupid decision just like they defend the ''=NULL
stupidity.
Wait until all jQuery Ajax requests are done?
My solution is as follows
var request;
...
'services': {
'GetAddressBookData': function() {
//This is the primary service that loads all addressbook records
request = $.ajax({
type: "POST",
url: "Default.aspx/GetAddressBook",
contentType: "application/json;",
dataType: "json"
});
},
...
'apps': {
'AddressBook': {
'data': "",
'Start': function() {
...services.GetAddressBookData();
request.done(function(response) {
trace("ajax successful");
..apps.AddressBook.data = response['d'];
...apps.AddressBook.Filter();
});
request.fail(function(xhr, textStatus, errorThrown) {
trace("ajax failed - " + errorThrown);
});
Worked quite nicely. I've tried a lot of different ways of doing this, but I found this to be the simplest and most reusable. Hope it helps
"And" and "Or" troubles within an IF statement
This is not an answer, but too long for a comment.
In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler
object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
).
Sub test()
Dim origNum As String
Dim creditOrDebit As String
Dim b As Boolean
Dim p As Profiler
Dim i As Long
Set p = New_Profiler
origNum = "30062600006"
creditOrDebit = "D"
p.startTimer ("nested_ifs")
For i = 1 To 1000000
If creditOrDebit = "D" Then
If origNum = "006260006" Then
b = True
ElseIf origNum = "30062600006" Then
b = True
End If
End If
Next i
p.stopTimer ("nested_ifs")
p.startTimer ("or_and")
For i = 1 To 1000000
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
b = True
End If
Next i
p.stopTimer ("or_and")
p.printReport
End Sub
The results of 5 runs (in ms for 1m loops):
20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125
20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125
20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125
20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141
20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125
Note
If creditOrDebit
is not "D"
, JP's code runs faster (around 60ms vs. 125ms for the or/and code).
remove table row with specific id
As bellow we can remove table rows with specific row id
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function remove(id)
{
$('table#test tr#'+id).remove();
// or you can use bellow line also
//$('#test tr#'+id).remove();
}
</script>
</head>
<body>
<table id="test">
<tr id="1"><td>bla</td><td><input type="button" onclick="remove(1)"value="Remove"></td></tr>
<tr id="2"><td>bla</td><td><input type="button" onclick="remove(2)" value="Remove"></td></tr>
<tr id="3"><td>bla</td><td><input type="button" onclick="remove(3)" value="Remove"></td></tr>
<tr id="4"><td>bla</td><td><input type="button" onclick="remove(4)" value="Remove"></td></tr>
</table>
</body></html>
Difference between Python's Generators and Iterators
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
In summary: Iterators are objects that have an __iter__
and a __next__
(next
in Python 2) method. Generators provide an easy, built-in way to create instances of Iterators.
A function with yield in it is still a function, that, when called, returns an instance of a generator object:
def a_function():
"when called, returns generator object"
yield
A generator expression also returns a generator:
a_generator = (i for i in range(0))
For a more in-depth exposition and examples, keep reading.
A Generator is an Iterator
Specifically, generator is a subtype of iterator.
>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True
We can create a generator several ways. A very common and simple way to do so is with a function.
Specifically, a function with yield in it is a function, that, when called, returns a generator:
>>> def a_function():
"just a function definition with yield in it"
yield
>>> type(a_function)
<class 'function'>
>>> a_generator = a_function() # when called
>>> type(a_generator) # returns a generator
<class 'generator'>
And a generator, again, is an Iterator:
>>> isinstance(a_generator, collections.Iterator)
True
An Iterator is an Iterable
An Iterator is an Iterable,
>>> issubclass(collections.Iterator, collections.Iterable)
True
which requires an __iter__
method that returns an Iterator:
>>> collections.Iterable()
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
collections.Iterable()
TypeError: Can't instantiate abstract class Iterable with abstract methods __iter__
Some examples of iterables are the built-in tuples, lists, dictionaries, sets, frozen sets, strings, byte strings, byte arrays, ranges and memoryviews:
>>> all(isinstance(element, collections.Iterable) for element in (
(), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True
Iterators require a next
or __next__
method
In Python 2:
>>> collections.Iterator()
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
collections.Iterator()
TypeError: Can't instantiate abstract class Iterator with abstract methods next
And in Python 3:
>>> collections.Iterator()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Iterator with abstract methods __next__
We can get the iterators from the built-in objects (or custom objects) with the iter
function:
>>> all(isinstance(iter(element), collections.Iterator) for element in (
(), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True
The __iter__
method is called when you attempt to use an object with a for-loop. Then the __next__
method is called on the iterator object to get each item out for the loop. The iterator raises StopIteration
when you have exhausted it, and it cannot be reused at that point.
From the documentation
From the Generator Types section of the Iterator Types section of the Built-in Types documentation:
Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__()
method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__()
and next()
[__next__()
in Python 3] methods. More information about generators can be found in the documentation for the yield expression.
(Emphasis added.)
So from this we learn that Generators are a (convenient) type of Iterator.
Example Iterator Objects
You might create object that implements the Iterator protocol by creating or extending your own object.
class Yes(collections.Iterator):
def __init__(self, stop):
self.x = 0
self.stop = stop
def __iter__(self):
return self
def next(self):
if self.x < self.stop:
self.x += 1
return 'yes'
else:
# Iterators must raise when done, else considered broken
raise StopIteration
__next__ = next # Python 3 compatibility
But it's easier to simply use a Generator to do this:
def yes(stop):
for _ in range(stop):
yield 'yes'
Or perhaps simpler, a Generator Expression (works similarly to list comprehensions):
yes_expr = ('yes' for _ in range(stop))
They can all be used in the same way:
>>> stop = 4
>>> for i, y1, y2, y3 in zip(range(stop), Yes(stop), yes(stop),
('yes' for _ in range(stop))):
... print('{0}: {1} == {2} == {3}'.format(i, y1, y2, y3))
...
0: yes == yes == yes
1: yes == yes == yes
2: yes == yes == yes
3: yes == yes == yes
Conclusion
You can use the Iterator protocol directly when you need to extend a Python object as an object that can be iterated over.
However, in the vast majority of cases, you are best suited to use yield
to define a function that returns a Generator Iterator or consider Generator Expressions.
Finally, note that generators provide even more functionality as coroutines. I explain Generators, along with the yield
statement, in depth on my answer to "What does the “yield” keyword do?".
Installing jQuery?
Install JQuery with only JavaScript. This is not a very good solution if you are developing a website but it's great if you want JQuery in the JavaScript console of a random website that does not use JQuery already.
function loadScript(url, callback)
{
// adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// then bind the event to the callback function
// there are several events for cross browser compatibility
script.onreadystatechange = callback;
script.onload = callback;
// fire the loading
head.appendChild(script);
}
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js")
loadScript function thanks to e-satis's answer to Include JavaScript file inside JavaScript file?
json.net has key method?
JObject
implements IDictionary<string, JToken>
, so you can use:
IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))
... or you could use TryGetValue
. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken>
though.
Correct way of looping through C++ arrays
Add a stopping value to the array:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange", ""};
for( unsigned int a = 0; texts[a].length(); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
How to call execl() in C with the proper arguments?
If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:
system("The same thing you type into console");
Can you delete data from influxdb?
It appears that you can do this in influxdb 0.9. For instance, here's a query that just succeeded for me:
DROP SERIES FROM temperature WHERE machine='zagbar'
(Per generous comment by @MuratCorlu, I'm reposting my earlier comment as an answer...)
How to check whether the user uploaded a file in PHP?
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
How to set proxy for wget?
In Debian Linux wget can be configured to use a proxy both via environment variables and via wgetrc. In both cases the variable names to be used for HTTP and HTTPS connections are
http_proxy=hostname_or_IP:portNumber
https_proxy=hostname_or_IP:portNumber
Note that the file /etc/wgetrc takes precedence over the environment variables, hence if your system has a proxy configured there and you try to use the environment variables, they would seem to have no effect!
How do you attach and detach from Docker's process?
If you only need the docker process to go in the background you can use
Ctrl + Z
Be aware that it is not a real detach and it comes with a performance penalty.
(You can return it to foreground with the bg
command).
Another option is to just close your terminal, if you don't need it any longer.
How to dynamically add elements to String array?
Arrays
in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).
Instead, use a List
:
ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:
String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.
VBA procedure to import csv file into access
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
Null or empty check for a string variable
Yes, it works. Check the below example. Assuming @value is not int
WITH CTE
AS
(
SELECT NULL AS test
UNION
SELECT '' AS test
UNION
SELECT '123' AS test
)
SELECT
CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY
FROM CTE
Result :
IS_EMPTY
--------
empty
empty
123
bash assign default value
The default value parameter expansion is often useful in build scripts like the example one below. If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL
to a value other than "no" to have it built in.
$ cat defvar.sh
#!/bin/bash
WITH_PERL=${WITH_PERL:-no}
if [[ "$WITH_PERL" != no ]]; then
echo "building with perl"
# ./configure --enable=perl
else
echo "not building with perl"
# ./configure
fi
Build without Perl
$ ./defvar.sh
not building with perl
Build with Perl
$ WITH_PERL=yes ./defvar.sh
building with perl
Generating a random password in php
Your best bet is the RandomLib library by ircmaxell.
Usage example:
$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
$passwordLength = 8; // Or more
$randomPassword = $generator->generateString($passwordLength);
It produces strings which are more strongly random than the normal randomness functions like shuffle()
and rand()
(which is what you generally want for sensitive information like passwords, salts and keys).
Find which rows have different values for a given column in Teradata SQL
Join the table with itself and give it two different aliases (A
and B
in the following example). This allows to compare different rows of the same table.
SELECT DISTINCT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
A.Address <> B.Address
The "less than" comparison <
ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <>
instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A
alias and the B
alias in turn.
The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.
The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to
SELECT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id
WHERE
A.[Adress Code] = 1 AND
B.[Adress Code] = 2 AND
A.Address <> B.Address
I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
Sequelize.js delete query?
In new version, you can try something like this
function (req,res) {
model.destroy({
where: {
id: req.params.id
}
})
.then(function (deletedRecord) {
if(deletedRecord === 1){
res.status(200).json({message:"Deleted successfully"});
}
else
{
res.status(404).json({message:"record not found"})
}
})
.catch(function (error){
res.status(500).json(error);
});
php is null or empty?
As is shown in the following table, empty($foo)
is equivalent to $foo==null
and is_null($foo)
has the same function of $foo===null
. The table also shows some tricky values regarding the null
comparison. (? denotes an uninitialized variables. )
empty is_null
==null ===null isset array_key_exists
? | T | T | F | F
null | T | T | F | T
"" | T | F | T | T
[] | T | F | T | T
0 | T | F | T | T
false | T | F | T | T
true | F | F | T | T
1 | F | F | T | T
\0 | F | F | T | T
Java: Add elements to arraylist with FOR loop where element name has increasing number
I assume Answer
as an Integer data type so in this case, you can easily use Scanner
class for adding the multiple elements(say 50).
private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
/*Using Scanner class object to take input.*/
arrayList.add(obj.nextInt());
}
/*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
/*Using get function for fetching the value present at index 'i'.*/
System.out.print(arrayList.get(i)+" ");
}}
This is a simple and easy method for adding multiple values in an ArrayList using for loop.
As in the above code, I presume the Answer
as Integer it could be String
, Double
, Long
et Cetra. So, in that case, you can use next()
, nextDouble()
, and nextLong()
respectively.
using extern template (C++11)
Wikipedia has the best description
In C++03, the compiler must instantiate a template whenever a fully specified template is
encountered in a translation unit. If the template is instantiated with the same types in
many translation units, this can dramatically increase compile times. There is no way to
prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern
data declarations.
C++03 has this syntax to oblige the compiler to instantiate a template:
template class std::vector<MyClass>;
C++11 now provides this syntax:
extern template class std::vector<MyClass>;
which tells the compiler not to instantiate the template in this translation unit.
The warning: nonstandard extension used...
Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.
Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.
HTML text input field with currency symbol
If you only need to support Safari, you can do it like this:
input.currency:before {
content: attr(data-symbol);
float: left;
color: #aaa;
}
and an input field like
<input class="currency" data-symbol="€" type="number" value="12.9">
This way you don't need an extra tag and keep the symbol information in the markup.
How to get the date from jQuery UI datepicker
Use
var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
jsDate instanceof Date; // -> true
jsDate.getDate();
jsDate.getMonth();
jsDate.getFullYear();
}
Converting serial port data to TCP/IP in a Linux environment
I stumbled upon this question via a Google search for a very similar one (using the serial port on a server from a Linux client over TCP/IP), so, even though this is not an answer to exact original question, some of the code might be useful to the original poster, I think:
- Making a Linux box with a serial port listen on the TCP port to share the modem: ser2net
- Using this "shared" modem from another Linux workstation: remtty
Scanf/Printf double variable C
As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.
As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic
a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
So you may want to doublecheck if your standard supports the syntax.
To conclude, I would say that you read with '%lf' and you print with '%f'.
Can I dynamically add HTML within a div tag from C# on load event?
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.
How to set scope property with ng-init?
I had some trouble with $scope.$watch
but after a lot of testing I found out that my data-ng-model="User.UserName"
was badly named and after I changed it to data-ng-model="UserName"
everything worked fine. I expect it to be the .
in the name causing the issue.
An unhandled exception was generated during the execution of the current web request
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
How can I transform string to UTF-8 in C#?
As you know the string is coming in as Encoding.Default
you could simply use:
byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
Another thing you may have to remember: If you are using Console.WriteLine to output some strings, then you should also write Console.OutputEncoding = System.Text.Encoding.UTF8;
!!! Or all utf8 strings will be outputed as gbk...
Can PHP cURL retrieve response headers AND body in a single request?
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = explode("\r\n\r\nHTTP/", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = explode("\r\n\r\n", $parts, 2);
Works with HTTP/1.1 100 Continue
before other headers.
If you need work with buggy servers which sends only LF instead of CRLF as line breaks you can use preg_split
as follows:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = preg_split("@\r?\n\r?\nHTTP/@u", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = preg_split("@\r?\n\r?\n@u", $parts, 2);
How do I run a file on localhost?
Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system
or exec
for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.
How to export query result to csv in Oracle SQL Developer?
Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.
The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.
Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.
Assign result of dynamic sql to variable
You can use sp_executesql with output parameter.
declare @S nvarchar(max) = 'select @x = 1'
declare @xx int
set @xx = 0
exec sp_executesql @S, N'@x int out', @xx out
select @xx
Result:
(No column name)
1
Edit
In my sample @S
is instead of your @template
. As you can see I assign a value to @x
so you need to modify @template
so it internally assigns the comma separated string to the variable you define in your second argument to sp_executesql
. In my sample N'@x int out'
. You probably want a varchar(max)
output parameter. Something like N'@Result varchar(max) out'
Here is another example building a comma separated string from master..spt_values
declare @template nvarchar(max)
set @template =
'select @Result += cast(number as varchar(10))+'',''
from master..spt_values
where type = ''P''
'
declare @CommaString varchar(max)
set @CommaString = ''
exec sp_executesql @template, N'@Result varchar(max) out', @CommaString out
select @CommaString
PowerShell Connect to FTP server and get files
Invoke-WebRequest can download HTTP, HTTPS, and FTP links.
$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password
# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing
Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.
NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream
In your case it helps a little optimization in proxy, or you can use "# time out settings"
location /
{
# time out settings
proxy_connect_timeout 159s;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_buffer_size 64k;
proxy_buffers 16 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_pass_header Set-Cookie;
proxy_redirect off;
proxy_hide_header Vary;
proxy_set_header Accept-Encoding '';
proxy_ignore_headers Cache-Control Expires;
proxy_set_header Referer $http_referer;
proxy_set_header Host $host;
proxy_set_header Cookie $http_cookie;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Can you center a Button in RelativeLayout?
Arcadia, just try the code below. There are several ways to get the result you're looking for, this is one of the easier ways.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"/>
</RelativeLayout>
Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).
You could also use this code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"
android:layout_centerInParent="true"/>
</RelativeLayout>
How to do select from where x is equal to multiple values?
Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
Converting binary to decimal integer output
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
- Train an AI algorithm to convert 32-binary number to decimal based.
- Predict a decimal representation from 32-binary.
See example and time comparison below:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
y = np.random.randint(0, 2**32, size=10_000)
def gen_x(y):
_x = bin(y)[2:]
n = 32 - len(_x)
return [int(sym) for sym in '0'*n + _x]
X = np.array([gen_x(x) for x in y])
model = LinearRegression()
model.fit(X, y)
def convert_bin_to_dec_ai(array):
return model.predict(array)
y_pred = convert_bin_to_dec_ai(X)
Time comparison:
This AI solution converts numbers almost x10 times faster than conventional way!
Where to find the complete definition of off_t type?
If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)
Nexus 5 USB driver
Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.
Solution:
- Open Android SDK Manager (in console get to sdk directory then run tools\android)
- Download/install latest USB drivers (under Extras).
- In Windows Device Manager (devmgmt.msc), right click the Nexus 5 device and select Update Driver Software.
- Browse My Computer for driver software > Android SDK Dir > Extras > usb_driver
Turn a number into star rating display using jQuery and CSS
If you only have to support modern browsers, you can get away with:
- No images;
- Mostly static css;
- Nearly no jQuery or Javascript;
You only need to convert the number to a class
, e.g. class='stars-score-50'
.
First a demo of "rendered" markup:
_x000D_
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: gold;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
_x000D_
_x000D_
Then a demo that uses a wee bit of code:
_x000D_
_x000D_
$(function() {_x000D_
function addScore(score, $domElement) {_x000D_
$("<span class='stars-container'>")_x000D_
.addClass("stars-" + score.toString())_x000D_
.text("?????")_x000D_
.appendTo($domElement);_x000D_
}_x000D_
_x000D_
addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: gold;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
_x000D_
_x000D_
The biggest downsides of this solution are:
- You need the stars inside the element to generate correct width;
- There's no semantic markup, e.g. you'd prefer the score as text inside the element;
- It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise
width
on a pseudo-element).
To fix this the solution above can be easily tweaked. The :before
and :after
bits need to become actual elements in the DOM (so we need some JS for that).
The latter is left as an excercise for the reader.
How do I show my global Git configuration?
You can use:
git config --list
or look at your ~/.gitconfig
file. The local configuration will be in your repository's .git/config
file.
Use:
git config --list --show-origin
to see where that setting is defined (global, user, repo, etc...)
Which comment style should I use in batch files?
There are a number of ways to comment in a batch file
1)Using rem
This is the official way. It apparently takes longer to execute than ::
, although it apparently stops parsing early, before the carets are processed. Percent expansion happens before rem and ::
are identified, so incorrect percent usage i.e. %~
will cause errors if percents are present. Safe to use anywhere in code blocks.
2)Using labels :
, ::
or :;
etc.
For :: comment
, ': comment' is an invalid label name because it begins with an invalid character. It is okay to use a colon in the middle of a label though. If a space begins at the start of label, it is removed : label
becomes :label
. If a space or a colon appears in the middle of the label, the rest of the name is not interpreted meaning that if there are two labels :f:oo
and :f rr
, both will be interpreted as :f
and only the later defined label in the file will be jumped to. The rest of the label is effectively a comment. There are multiple alternatives to ::
, listed here. You can never goto
or call
a ::foo
label. goto :foo
and goto ::foo
will not work.
They work fine outside of code blocks but after a label in a code block, invalid or not, there has to be a valid command line. :: comment
is indeed another valid command. It interprets it as a command and not a label; the command has precedence. Which is the command to cd to the ::
volume, which will work if you have executed subst :: C:\
, otherwise you get a cannot find the volume error. That's why :;
is arguably better because it cannot be interpreted in this way, and therefore is interpreted as a label instead, which serves as the valid command. This is not recursive, i.e, the next label does not need a command after it. That's why they come in twos.
You need to provide a valid command after the label e.g. echo something
. A label in a code block has to come with at least one valid command, so the lines come in pairs of two. You will get an unexpected )
error if there is a space or a closing parenthesis on the next line. If there is a space between the two ::
lines you will get an invalid syntax error.
You can also use the caret operator in the ::
comment like so:
@echo off
echo hello
(
:;(^
this^
is^
a^
comment^
)
:;
)
:;^
this^
is^
a^
comment
:;
)
But you need the trailing :;
for the reason stated above.
@echo off
(
echo hello
:;
:; comment
:; comment
:;
)
echo hello
It is fine as long as there is an even number. This is undoubtedly the best way to comment -- with 4 lines and :;
. With :;
you don't get any errors that need to be suppressed using 2> nul
or subst :: C:\
. You could use subst :: C:\
to make the volume not found error go away but it means you will have to also put C: in the code to prevent your working directory from becoming ::\
.
To comment at the end of a line you can do
command &::
or command & rem comment
, but there still has to be an even number, like so:
@echo off
(
echo hello & :;yes
echo hello & :;yes
:;
)
echo hello
The first echo hello & :;yes
has a valid command on the next line but the second & :;yes
does not, so it needs one i.e. the :;
.
3)Using an invalid environment variable
%= comment =%
. In a batch file, environment variables that are not defined are removed from the script. This makes it possible to use them at the end of a line without using &
. It is custom to use an invalid environment variable i.e. one that contains an equals sign. The extra equals is not required but makes it look symmetrical. Also, variable names starting with "=" are reserved for undocumented dynamic variables. Those dynamic variables never end with "=", so by using an "=" at both the start and end of the comment, there is no possibility of a name clash. The comment cannot contain %
or :
.
@echo off
echo This is an example of an %= Inline Comment =% in the middle of a line.
4)As a command, redirecting stderr to nul
@echo off
(
echo hello
;this is a comment 2> nul
;this is another comment 2> nul
)
5)At the end of a file, everything after an unclosed parenthesis is a comment
@echo off
(
echo hello
)
(this is a comment
this is a comment
this is a comment
AngularJS For Loop with Numbers & Ranges
Late to the party. But i ended up just doing this:
In your controller:
$scope.repeater = function (range) {
var arr = [];
for (var i = 0; i < range; i++) {
arr.push(i);
}
return arr;
}
Html:
<select ng-model="myRange">
<option>3</option>
<option>5</option>
</select>
<div ng-repeat="i in repeater(myRange)"></div>
Which characters need to be escaped when using Bash?
To save someone else from having to RTFM... in bash:
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $
, `
, \
, and, when history expansion is enabled, !
.
...so if you escape those (and the quote itself, of course) you're probably okay.
If you take a more conservative 'when in doubt, escape it' approach, it should be possible to avoid getting instead characters with special meaning by not escaping identifier characters (i.e. ASCII letters, numbers, or '_'). It's very unlikely these would ever (i.e. in some weird POSIX-ish shell) have special meaning and thus need to be escaped.
How to install .MSI using PowerShell
#Variables
$computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
$sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\download\LanSchool"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
}
I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!
How to change the link color in a specific class for a div CSS
If you want to add CSS on a:hover
to not all the tag, but the some of the tag, best way to do that is by using class. Give the class to all the tags which you want to give style - see the example below.
<style>
a.change_hover_color:hover {
color: white !important;
}
</style>
<a class="change_hover_color">FACEBOOK</a>
<a class="change_hover_color">GOOGLE</a>
What does the term "Tuple" Mean in Relational Databases?
A tuple is used to define a slice of data from a cube; it is composed of an ordered collection of one member from one or more dimensions. A tuple is used to identify specific sections of multidimensional data from a cube; a tuple composed of one member from each dimension in a cube completely describes a cell value.
How to analyze a JMeter summary report?
Short explanation looks like:
- Sample - number of requests sent
- Avg - an Arithmetic mean for all responses (sum of all times / count)
- Minimal response time (ms)
- Maximum response time (ms)
- Deviation - see Standard Deviation article
- Error rate - percentage of failed tests
- Throughput - how many requests per second does your server handle. Larger is better.
- KB/Sec - self expalanatory
- Avg. Bytes - average response size
If you having troubles with interpreting results you could try BM.Sense results analysis service
How can I get the value of a registry key from within a batch script?
Based on tryingToBeClever solution (which I happened to also stumble upon and fixed myself by trial-and-error before finding it), I also suggest passing the result output of reg query
through find
in order to filter undesired lines due to the ! REG.EXE VERSION x.y
inconsistency. The find
filtering and tokens
tweaking also allows to pick exactly what we want (typically the value). Also added quotes to avoid unexpected results with key/value names containing spaces.
Final result proposed when we are only interested in fetching the value:
@echo off
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKCU\Software\Microsoft\Command Processor
set VALUE_NAME=DefaultColor
for /F "usebackq tokens=1,2,*" %%A IN (`reg query "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul ^| find "%VALUE_NAME%"`) do (
echo %%C
)
A potential caveat of using find
is that the errorlevel set by reg
when errors occur is now obfuscated so one should only use this approach for keys known to be there and/or after a previous validation.
A tiny additional optimization (add skip=1
to avoid processing the first line of output) can be done in cases when the key name also contains the value name (as it is the case with HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
and CurrentVersion
) but removes most flexibility so should only be used in particular use-cases.
Check if something is (not) in a list in Python
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators in
and not in
test for membership. x in s
evaluates to
True
if x
is a member of s
, and False
otherwise. x not in s
returns
the negation of x in s
.
Additionally,
The operator not in
is defined to have the inverse true value of in
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
... in
and not in
,
are supported by types that are iterable or implement the
__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.
list.count
can be used if you want to count the occurrences.
The XY Problem: Have you considered set
s?
Ask yourself these questions:
- do you need to check whether an item is in a list more than once?
- Is this check done inside a loop, or a function called repeatedly?
- Are the items you're storing on your list hashable? IOW, can you call
hash
on them?
If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
How to see remote tags?
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
Running Jupyter via command line on Windows
I got Jupyter notebook running in Windows 10. I found the easiest way to accomplish this task without relying upon a distro like Anaconda was to use Cygwin.
In Cygwin install python2, python2-devel, python2-numpy, python2-pip, tcl, tcl-devel, (I have included a image below of all packages I installed) and any other python packages you want that are available. This is by far the easiest option.
Then run this command to just install jupyter notebook:
python -m pip install jupyter
Below is the actual commands I ran to add more libraries just in case others need this list too:
python -m pip install scipy
python -m pip install scikit-learn
python -m pip install sklearn
python -m pip install pandas
python -m pip install matplotlib
python -m pip install jupyter
If any of the above commands fail do not worry the solution is pretty simple most of the time. What you do is look at the build failure for whatever missing package / library.
Say it is showing a missing pyzmq then close Cygwin, re-open the installer, get to the package list screen, show "full" for all, then search for the name like zmq and install those libraries and re-try the above commands.
Using this approach it was fairly simple to eventually work through all the missing dependencies successfully.
Cygwin package list
Once everything is installed then run in Cygwin goto the folder you want to be the "root" for the notebook ui tree and type:
jupyter notebook
This will start up the notebook and show some output like below:
$ jupyter notebook
[I 19:05:30.459 NotebookApp] Serving notebooks from local directory:
[I 19:05:30.459 NotebookApp] 0 active kernels
[I 19:05:30.459 NotebookApp] The Jupyter Notebook is running at:
[I 19:05:30.459 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
Copy/paste this URL into your browser when you connect for the first time, to login with a token:
http://localhost:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How do I UPDATE from a SELECT in SQL Server?
The other way to update from a select statement:
UPDATE A
SET A.col = A.col,B.col1 = B.col1
FROM first_Table AS A
INNER JOIN second_Table AS B ON A.id = B.id WHERE A.col2 = 'cool'
How to return an array from a function?
It is not possible to return an array from a C++ function. 8.3.5[dcl.fct]/6:
Functions shall not have a return type of type array or function[...]
Most commonly chosen alternatives are to return a value of class type where that class contains an array, e.g.
struct ArrayHolder
{
int array[10];
};
ArrayHolder test();
Or to return a pointer to the first element of a statically or dynamically allocated array, the documentation must indicate to the user whether he needs to (and if so how he should) deallocate the array that the returned pointer points to.
E.g.
int* test2()
{
return new int[10];
}
int* test3()
{
static int array[10];
return array;
}
While it is possible to return a reference or a pointer to an array, it's exceedingly rare as it is a more complex syntax with no practical advantage over any of the above methods.
int (&test4())[10]
{
static int array[10];
return array;
}
int (*test5())[10]
{
static int array[10];
return &array;
}
Stop MySQL service windows
The Top Voted Answer is out of date. I just installed MySQL 5.7 and the service name is now MySQL57
so the new command is
net stop MySQL57
How do I merge two dictionaries in a single expression (taking union of dictionaries)?
I think my ugly one-liners are just necessary here.
z = next(z.update(y) or z for z in [x.copy()])
# or
z = (lambda z: z.update(y) or z)(x.copy())
- Dicts are merged.
- Single expression.
- Don't ever dare to use it.
P.S. This is a solution working in both versions of Python. I know that Python 3 has this {**x, **y}
thing and it is the right thing to use (as well as moving to Python 3 if you still have Python 2 is the right thing to do).
How to compare two dates?
For calculating days in two dates difference, can be done like below:
import datetime
import math
issuedate = datetime(2019,5,9) #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine #you want change
if diff_date.total_seconds() > 0.0: #its matching your condition
days = math.ceil(diff_date.total_seconds()/86400) #calculate days (in
one day 86400 seconds)
deductable_amount = round(amount,2)*days #calclulated fine for all days
Becuase if one second is more with the due date then we have to charge
Calculate date from week number
Personally I'd take advantage of the culture info to get the day of the week and loop down to the culture's first day of the week. I'm not sure if I'm explaining it properly, here's an example:
public DateTime GetFirstDayOfWeek(int year, int weekNumber)
{
return GetFirstDayOfWeek(year, weekNumber, Application.CurrentCulture);
}
public DateTime GetFirstDayOfWeek(int year, int weekNumber,
System.Globalization.CultureInfo culture)
{
System.Globalization.Calendar calendar = culture.Calendar;
DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
DateTime targetDay = calendar.AddWeeks(firstOfYear, weekNumber);
DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
while (targetDay.DayOfWeek != firstDayOfWeek)
{
targetDay = targetDay.AddDays(-1);
}
return targetDay;
}
Rounded corner for textview in android
- Right Click on Drawable Folder and Create new File
- Name the file according to you and add the extension as .xml.
- Add the following code in the file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<stroke android:width="1dp" />
<solid android:color="#1e90ff" />
</shape>
- Add the line where you want the rounded edge
android:background="@drawable/corner"
installation app blocked by play protect
I solved this problem by changing my application package name according to signature certificate details. At first I created application with com.foo.xyz
but my certificate organization was 'bar'. So I change my package name to com.bar.xyz and now there is no google play protect warning!
Export javascript data to CSV file without server interaction
@adeneo answer works for Firefox and chrome... For IE the below can be used.
_x000D_
_x000D_
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
_x000D_
_x000D_
Sending and Parsing JSON Objects in Android
Although there are already excellent answers are provided by users such as encouraging use of GSON etc. I would like to suggest use of org.json. It includes most of GSON functionalities. It also allows you to pass json string as an argument to it's JSONObject and it will take care of rest e.g:
JSONObject json = new JSONObject("some random json string");
This functionality make it my personal favorite.
d3 add text to circle
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
_x000D_
_x000D_
var width = 960,_x000D_
height = 500,_x000D_
json = {_x000D_
"nodes": [{_x000D_
"x": 100,_x000D_
"r": 20,_x000D_
"label": "Node 1",_x000D_
"color": "red"_x000D_
}, {_x000D_
"x": 200,_x000D_
"r": 25,_x000D_
"label": "Node 2",_x000D_
"color": "blue"_x000D_
}, {_x000D_
"x": 300,_x000D_
"r": 30,_x000D_
"label": "Node 3",_x000D_
"color": "green"_x000D_
}]_x000D_
};_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
.attr("width", width)_x000D_
.attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
.append("pattern")_x000D_
.attr({_x000D_
"id": "stripes",_x000D_
"width": "8",_x000D_
"height": "8",_x000D_
"fill": "red",_x000D_
"patternUnits": "userSpaceOnUse",_x000D_
"patternTransform": "rotate(60)"_x000D_
})_x000D_
.append("rect")_x000D_
.attr({_x000D_
"width": "4",_x000D_
"height": "8",_x000D_
"transform": "translate(0,0)",_x000D_
"fill": "grey"_x000D_
});_x000D_
_x000D_
function plotChart(json) {_x000D_
/* Define the data for the circles */_x000D_
var elem = svg.selectAll("g myCircleText")_x000D_
.data(json.nodes)_x000D_
_x000D_
/*Create and place the "blocks" containing the circle and the text */_x000D_
var elemEnter = elem.enter()_x000D_
.append("g")_x000D_
.attr("class", "node-group")_x000D_
.attr("transform", function(d) {_x000D_
return "translate(" + d.x + ",80)"_x000D_
})_x000D_
_x000D_
/*Create the circle for each block */_x000D_
var circleInner = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", function(d) {_x000D_
return d.color;_x000D_
});_x000D_
_x000D_
var circleOuter = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", "url(#stripes)");_x000D_
_x000D_
/* Create the text for each block */_x000D_
elemEnter.append("text")_x000D_
.text(function(d) {_x000D_
return d.label_x000D_
})_x000D_
.attr({_x000D_
"text-anchor": "middle",_x000D_
"font-size": function(d) {_x000D_
return d.r / ((d.r * 10) / 100);_x000D_
},_x000D_
"dy": function(d) {_x000D_
return d.r / ((d.r * 25) / 100);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_
Output:
Below is the link to codepen
also:
See the Pen
D3-Circle-Pattern-Text by Manish Kumar (
@mkdudeja) on
CodePen.
Thanks,
Manish Kumar
Read all contacts' phone numbers in android
Load contacts in background using CursorLoader:
CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor managedCursor = cursor.loadInBackground();
int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int index = 0;
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String phName = managedCursor.getString(name);
}