Moving all files from one directory to another using Python
def copy_myfile_dirOne_to_dirSec(src, dest, ext):
if not os.path.exists(dest): # if dest dir is not there then we create here
os.makedirs(dest);
for item in os.listdir(src):
if item.endswith(ext):
s = os.path.join(src, item);
fd = open(s, 'r');
data = fd.read();
fd.close();
fname = str(item); #just taking file name to make this name file is destination dir
d = os.path.join(dest, fname);
fd = open(d, 'w');
fd.write(data);
fd.close();
print("Files are copyed successfully")
Superscript in markdown (Github flavored)?
<sup>
and <sub>
tags work and are your only good solution for arbitrary text. Other solutions include:
Unicode
If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.
I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:
°
SUPERSCRIPT ZERO (U+2070)
¹
SUPERSCRIPT ONE (U+00B9)
²
SUPERSCRIPT TWO (U+00B2)
³
SUPERSCRIPT THREE (U+00B3)
n
SUPERSCRIPT LATIN SMALL LETTER N (U+207F)
People also often reach for <sup>
and <sub>
tags in an attempt to render specific symbols like these:
™
TRADE MARK SIGN (U+2122)
®
REGISTERED SIGN (U+00AE)
?
SERVICE MARK (U+2120)
Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.
Alternatively, you could use the hex values above in an HTML character escape. Eg, ²
instead of ²
. This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.
Images
If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:
![Alt text goes here, if you'd like](path/to/image.png)
You can use a full path (eg. starting with https://
or http://
) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.
If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.
Text on image mouseover?
And if you come from even further in the future you can use the title property on div tags now to provide tooltips:
<div title="Tooltip text">Hover over me</div>
Let's just hope you're not using a browser from the past.
_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_
Why doesn't height: 100% work to expand divs to the screen height?
if you want, for example, a left column (height 100%) and the content (height auto)
you can use absolute :
#left_column {
float:left;
position: absolute;
max-height:100%;
height:auto !important;
height: 100%;
overflow: hidden;
width : 180px; /* for example */
}
#left_column div {
height: 2000px;
}
#right_column {
float:left;
height:100%;
margin-left : 180px; /* left column's width */
}
in html :
<div id="content">
<div id="left_column">
my navigation content
<div></div>
</div>
<div id="right_column">
my content
</div>
</div>
Search all of Git history for a string?
Try the following commands to search the string inside all previous tracked files:
git log --patch | less +/searching_string
or
git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'
which needs to be run from the parent directory where you'd like to do the searching.
Use grep to report back only line numbers
All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:
sed -n '/pattern/=' filename
New to unit testing, how to write great tests?
For unit testing, I found both Test Driven (tests first, code second) and code first, test second to be extremely useful.
Instead of writing code, then writing test. Write code then look at what you THINK the code should be doing. Think about all the intended uses of it and then write a test for each. I find writing tests to be faster but more involved than the coding itself. The tests should test the intention. Also thinking about the intentions you wind up finding corner cases in the test writing phase. And of course while writing tests you might find one of the few uses causes a bug (something I often find, and I am very glad this bug did not corrupt data and go unchecked).
Yet testing is almost like coding twice. In fact I had applications where there was more test code (quantity) than application code. One example was a very complex state machine. I had to make sure that after adding more logic to it, the entire thing always worked on all previous use cases. And since those cases were quite hard to follow by looking at the code, I wound up having such a good test suite for this machine that I was confident that it would not break even after making changes, and the tests saved my ass a few times. And as users or testers were finding bugs with the flow or corner cases unaccounted for, guess what, added to tests and never happened again. This really gave users confidence in my work in addition to making the whole thing super stable. And when it had to be re-written for performance reasons, guess what, it worked as expected on all inputs thanks to the tests.
All the simple examples like function square(number)
is great and all, and are probably bad candidates to spend lots of time testing. The ones that do important business logic, thats where the testing is important. Test the requirements. Don't just test the plumbing. If the requirements change then guess what, the tests must too.
Testing should not be literally testing that function foo invoked function bar 3 times. That is wrong. Check if the result and side-effects are correct, not the inner mechanics.
php delete a single file in directory
If you want to delete a single file, you must, as you found out, use the unlink()
function.
That function will delete what you pass it as a parameter : so, it's up to you to pass it the path to the file that it must delete.
For example, you'll use something like this :
unlink('/path/to/dir/filename');
jQuery select change event get selected option
Delegated Alternative
In case anyone is using the delegated approach for their listener, use e.target
(it will refer to the select element).
$('#myform').on('change', 'select', function (e) {
var val = $(e.target).val();
var text = $(e.target).find("option:selected").text(); //only time the find is required
var name = $(e.target).attr('name');
}
JSFiddle Demo
Getting reference to the top-most view/window in iOS application
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
keyWindow = window;
break;
}
}
}
ASP.NET MVC 5 - Identity. How to get current ApplicationUser
Right now the asp.mvc project template creates an account controller that gets the usermanager this way:
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()
The following works for me:
ApplicationUser user = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());
How do I remove leading whitespace in Python?
The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:
s = """
line 1 has 4 leading spaces
line 2 has 4 leading spaces
line 3 has 4 leading spaces
"""
if we print(s)
we would get output like:
>>> print(s)
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
and if we used textwrap.dedent
:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
How to play only the audio of a Youtube video using HTML 5?
_x000D_
_x000D_
var vid = "bpt84ceWAY0",_x000D_
audio_streams = {},_x000D_
audio_tag = document.getElementById('youtube');_x000D_
_x000D_
fetch("https://"+vid+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => {_x000D_
if (response.ok) {_x000D_
response.text().then(data => {_x000D_
_x000D_
var data = parse_str(data),_x000D_
streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');_x000D_
_x000D_
streams.forEach(function(s, n) {_x000D_
var stream = parse_str(s),_x000D_
itag = stream.itag * 1,_x000D_
quality = false;_x000D_
console.log(stream);_x000D_
switch (itag) {_x000D_
case 139:_x000D_
quality = "48kbps";_x000D_
break;_x000D_
case 140:_x000D_
quality = "128kbps";_x000D_
break;_x000D_
case 141:_x000D_
quality = "256kbps";_x000D_
break;_x000D_
}_x000D_
if (quality) audio_streams[quality] = stream.url;_x000D_
});_x000D_
_x000D_
console.log(audio_streams);_x000D_
_x000D_
audio_tag.src = audio_streams['128kbps'];_x000D_
audio_tag.play();_x000D_
})_x000D_
}_x000D_
});_x000D_
_x000D_
function parse_str(str) {_x000D_
return str.split('&').reduce(function(params, param) {_x000D_
var paramSplit = param.split('=').map(function(value) {_x000D_
return decodeURIComponent(value.replace('+', ' '));_x000D_
});_x000D_
params[paramSplit[0]] = paramSplit[1];_x000D_
return params;_x000D_
}, {});_x000D_
}
_x000D_
<audio id="youtube" autoplay controls loop></audio>
_x000D_
_x000D_
_x000D_
Git status ignore line endings / identical files / windows & linux environment / dropbox / mled
Use .gitattributes instead, with the following setting:
# Ignore all differences in line endings
* -crlf
.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.
How to add column to numpy array
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
The shortest possible output from git log containing author and date
To show the commits I have staged that are ready to push I do
git log remotes/trunk~4..HEAD --pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s" --date=short | awk -F'\t' '{gsub(/[, ]/,"",$2);gsub(/HEAD/, "\033[1;36mH\033[00m",$2);gsub(/master/, "\033[1;32mm\033[00m",$2);gsub(/trunk/, "\033[1;31mt\033[00m",$2);print $1 "\t" gensub(/([\(\)])/, "\033[0;33m\\1\033[00m","g",$2) $3}' | less -eiFRXS
The output looks something like:
ef87da7 2013-01-17 haslers (Hm)Fix NPE in Frobble
8f6d80f 2013-01-17 haslers Refactor Frobble
815813b 2013-01-17 haslers (t)Add Wibble to Frobble
3616373 2013-01-17 haslers Add Foo to Frobble
3b5ccf0 2013-01-17 haslers Add Bar to Frobble
a1db9ef 2013-01-17 haslers Add Frobble Widget
Where the first column appears in yellow, and the 'H' 'm' and 't' in parentesis show the HEAD, master and trunk and appear in their usual "--decorate" colors
Here it is with line breaks so you can see what it's doing:
git log remotes/trunk~4..HEAD --date=short
--pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s"
| awk -F'\t' '{
gsub(/[, ]/,"",$2);
gsub(/HEAD/, "\033[1;36mH\033[00m",$2);
gsub(/master/, "\033[1;32mm\033[00m",$2);
gsub(/trunk/, "\033[1;31mt\033[00m",$2);
print $1 "\t" gensub(/([\(\)])/, "\033[0;33m\\1\033[00m","g",$2) $3}'
I have aliased to "staged" with:
git config alias.staged '!git log remotes/trunk~4..HEAD --date=short --pretty=format:"%C(yellow)%h%C(white) %ad %aN%x09%d%x09%s" | awk -F"\t" "{gsub(/[, ]/,\"\",\$2);gsub(/HEAD/, \"\033[1;36mH\033[00m\",\$2);gsub(/master/, \"\033[1;32mm\033[00m\",\$2);gsub(/trunk/, \"\033[1;31mt\033[00m\",\$2);print \$1 \"\t\" gensub(/([\(\)])/, \"\033[0;33m\\\\\1\033[00m\",\"g\",\$2) \$3}"'
(Is there an easier way to escape that? it was a bit tricky to work out what needed escaping)
How to model type-safe enum types?
I must say that the example copied out of the Scala documentation by skaffman above is of limited utility in practice (you might as well use case object
s).
In order to get something most closely resembling a Java Enum
(i.e. with sensible toString
and valueOf
methods -- perhaps you are persisting the enum values to a database) you need to modify it a bit. If you had used skaffman's code:
WeekDay.valueOf("Sun") //returns None
WeekDay.Tue.toString //returns Weekday(2)
Whereas using the following declaration:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon = Value("Mon")
val Tue = Value("Tue")
... etc
}
You get more sensible results:
WeekDay.valueOf("Sun") //returns Some(Sun)
WeekDay.Tue.toString //returns Tue
File to import not found or unreadable: compass
If you're like me and came here looking for a way to make sass --watch work with compass, the answer is to use Compass' version of watch, simply:
compass watch
If you're on a Mac and don't yet have the gem installed, you might run into errors when you try to install the Compass gem, due to permission problems that arise on OSX versions later than 10.11. Install ruby with Homebrew to get around this. See this answer for how to do that.
Alternatively you could just use CodeKit, but if you're stubborn like me and want to use Sublime Text and command line, this is the route to go.
How to update record using Entity Framework Core?
Microsoft Docs gives us two approaches.
Recommended HttpPost Edit code: Read and update
This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.
Advantages
- Prevents overposting
- EFs automatic change tracking sets the
Modified
flag on the fields that are changed by form input.
Alternative HttpPost Edit code: Create and attach
an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.
As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.
How to define custom sort function in javascript?
It could be that the plugin is case-sensitive. Try inputting Te
instead of te
. You can probably have your results setup to not be case-sensitive. This question might help.
For a custom sort function on an Array
, you can use any JavaScript function and pass it as parameter to an Array
's sort()
method like this:
_x000D_
_x000D_
var array = ['White 023', 'White', 'White flower', 'Teatr'];_x000D_
_x000D_
array.sort(function(x, y) {_x000D_
if (x < y) {_x000D_
return -1;_x000D_
}_x000D_
if (x > y) {_x000D_
return 1;_x000D_
}_x000D_
return 0;_x000D_
});_x000D_
_x000D_
// Teatr White White 023 White flower_x000D_
document.write(array);
_x000D_
_x000D_
_x000D_
More Info here on
Array.sort.
Using Python Requests: Sessions, Cookies, and POST
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
How to check if an object is a list or tuple (but not string)?
in python >3.6
import collections
isinstance(set(),collections.abc.Container)
True
isinstance([],collections.abc.Container)
True
isinstance({},collections.abc.Container)
True
isinstance((),collections.abc.Container)
True
isinstance(str,collections.abc.Container)
False
The name 'InitializeComponent' does not exist in the current context
I've encountered this a couple times and keep forgetting what causes it.
I ran into this when I renamed the namespace on my code behind file but not in my XAML.
So check if you've done the same.
The namespace and class names need to match since they are both part of a partial class
namespace ZZZ
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
//...
}
}
<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">
How to specify the download location with wget?
"-P" is the right option, please read on for more related information:
wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2
Relevant snippets from man pages for convenience:
-P prefix
--directory-prefix=prefix
Set directory prefix to prefix. The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree. The default is . (the current directory).
-nd
--no-directories
Do not create a hierarchy of directories when retrieving recursively. With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
filenames will get extensions .n).
-np
--no-parent
Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
Psql could not connect to server: No such file or directory, 5432 error?
Does the /etc/postgresql/9.6/main/postgresql.conf
show that port being assigned? On my default Xubuntu Linux install, mine showed port = 5433 for some reason as best as I can remember, but I did comment out the line in that same file that said listen_addresses = 'localhost'
and uncommented the line listen_addresses = '*'
. So maybe start and check there. Hope that helps.
W3WP.EXE using 100% CPU - where to start?
This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.
So, it would be simple enough to ensure that they are building and deploying in release mode.
Array.push() and unique items
try .includes()
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
so something like
const array = [1, 3];
if (!array.includes(2))
array.push(2);
note the browser compatibility at the bottom of the page, however.
NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>
Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }
as attribute on your property containing the enumerable/list/collection.
This will target only that list, and only append type information for the contained objects, like this:
{
"Items": [
{
"$type": "Namespace.ClassA, Assembly",
"Property": "Value"
},
{
"$type": "Namespace.ClassB, Assembly",
"Property": "Value",
"Additional_ClassB_Property": 3
}
]
}
Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.
Difference between DTO, VO, POJO, JavaBeans?
POJO :
It is a java file(class) which doesn't extend or implement any other java file(class).
Bean:
It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class:
It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button
I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.
Basically the solution is to use CSS to hide the <input>
element and style a <label>
around it to look like a button. Click the 'Run code snippet' button to see the results.
I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.
_x000D_
_x000D_
label.cameraButton {_x000D_
display: inline-block;_x000D_
margin: 1em 0;_x000D_
_x000D_
/* Styles to make it look like a button */_x000D_
padding: 0.5em;_x000D_
border: 2px solid #666;_x000D_
border-color: #EEE #CCC #CCC #EEE;_x000D_
background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label class="cameraButton">Take a picture_x000D_
<input type="file" accept="image/*;capture=camera">_x000D_
</label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_
Python os.path.join on Windows
Windows has a concept of current directory for each drive. Because of that, "c:sourcedir"
means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.
Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:
"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")
Delete sql rows where IDs do not have a match from another table
Using LEFT JOIN/IS NULL:
DELETE b FROM BLOB b
LEFT JOIN FILES f ON f.id = b.fileid
WHERE f.id IS NULL
Using NOT EXISTS:
DELETE FROM BLOB
WHERE NOT EXISTS(SELECT NULL
FROM FILES f
WHERE f.id = fileid)
Using NOT IN:
DELETE FROM BLOB
WHERE fileid NOT IN (SELECT f.id
FROM FILES f)
Warning
Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.
How to get the previous page URL using JavaScript?
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer
serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
Python, how to check if a result set is empty?
MySQLdb will not raise an exception if the result set is empty. Additionally cursor.execute() function will return a long value which is number of rows in the fetched result set. So if you want to check for empty results, your code can be re-written as
rows_count = cursor.execute(query_sql)
if rows_count > 0:
rs = cursor.fetchall()
else:
// handle empty result set
jQuery If DIV Doesn't Have Class "x"
How about instead of using an if inside the event, you unbind the event when the select class is applied?
I'm guessing you add the class inside your code somewhere, so unbinding the event there would look like this:
$(element).addClass( 'selected' ).unbind( 'hover' );
The only downside is that if you ever remove the selected class from the element, you have to subscribe it to the hover event again.
Iterating through a List Object in JSP
<c:forEach items="${sessionScope.empL}" var="emp">
<tr>
<td>Employee ID: <c:out value="${emp.eid}"/></td>
<td>Employee Pass: <c:out value="${emp.ename}"/></td>
</tr>
</c:forEach>
How to convert list data into json in java
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?
What I have done in the past is declare my inner class collections using IList<Class>
, ICollection<Class>
or IEnumerable<Class>
(if static list) depending on whether or not I will have to do any number of the following in a method in my repository: enumerate, sort/order or modify. When I just need to enumerate (and maybe sort) over objects then I create a temp List<Class>
to work with the collection within an IEnumerable method. I think this practice would only be effective if the collection is relatively small, but it may be good practice in general, idk. Please correct me if there is evidence as to why this would not good practice.
Django DoesNotExist
The solution that i believe is best and optimized is:
try:
#your code
except "ModelName".DoesNotExist:
#your code
Fastest way to check if a string is JSON in PHP?
I don't know about performance or elegance of my solution, but it's what I'm using:
if (preg_match('/^[\[\{]\"/', $string)) {
$aJson = json_decode($string, true);
if (!is_null($aJson)) {
... do stuff here ...
}
}
Since all my JSON encoded strings start with {" it suffices to test for this with a RegEx. I'm not at all fluent with RegEx, so there might be a better way to do this. Also: strpos() might be quicker.
Just trying to give in my tuppence worth.
P.S. Just updated the RegEx string to /^[\[\{]\"/
to also find JSON array strings. So it now looks for either [" or {" at the beginning of the string.
Using Jquery AJAX function with datatype HTML
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
Adding up BigDecimals using Streams
This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.filter(Objects::nonNull)
.filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
.reduce(BigDecimal.ZERO, BigDecimal::add);
This prevents null values from attempting to be summed as we reduce.
How to get relative path of a file in visual studio?
I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.
Suppose this is your file structure:
/BulutDepoProject
/bin
Main.exe
/FolderIcon
Folder.ico
Main.cs
You need to write your path relative to the Main.exe
file. So, you want to access Folder.ico
, in your Main.cs
you can use:
String path = "..\\FolderIcon\\Folder.ico"
That seemed to work for me!
java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of
I had the same exception in the simulator (Android Studio on OSX) but connecting to the same URL on the iOS simulator worked fine... Looks like it all stemmed from the fact I'd be running the simulator whilst connected to a personal hotspot for my internet connection and then came back later while connected to wifi and the simulator didn't like the new internet connection for some reason, seems like it thought the old hotspot was the current connection, which was no longer working..
Closing and relaunching the simulator worked!
Assigning a function to a variable
You simply don't call the function.
>>>def x():
>>> print(20)
>>>y = x
>>>y()
20
The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y
the value returned by x
(which in this case is None
).
What is a MIME type?
Explanation by analogy
Imagine that you wrote a letter to your pen pal but that you wrote it in different languages each time.
For example, you might have chosen to write your first letter in Tamil, and the second in German etc.
In order for your friend to translate those letters, your friend would need to:
- (i) identify the language type, and
- (ii) and then translate it accordingly.
But identifying a language is not that easy - it's going to take a lot of computational energy.
It would be much easier if you wrote the language you are sending across on the top of your letter - that would make life a lot easier for your friend.
So then, in order to highlight the language you are writing in, you simple annotate the language (e.g. "French") on the top of your letter.
How would your friend know or be able to read or distinguish between the different language types you are specifying at the top of your letter?
That's easy: you agree upon this beforehand.
Tying the analogy back in with HTML
Because there are different types of data formats which need to be sent over the internet, specifying the data type up front would allow the corresponding client to properly interpret and render the data accordingly to the user.
Why do we have different data formats?
Principally because they serve different purposes and have different abilities.
For example, a PDF format is very different from a picture format - which is also different from a sound format - both serve very different purposes and accordingly are written different prior to being sent over the internet.
How to loop over a Class attributes in Java?
There is no linguistic support to do what you're asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields()
to get an array of Field
), but depending on what you're trying to do, this may not be the best solution.
See also
Related questions
Example
Here's a simple example to show only some of what reflection is capable of doing.
import java.lang.reflect.*;
public class DumpFields {
public static void main(String[] args) {
inspect(String.class);
}
static <T> void inspect(Class<T> klazz) {
Field[] fields = klazz.getDeclaredFields();
System.out.printf("%d fields:%n", fields.length);
for (Field field : fields) {
System.out.printf("%s %s %s%n",
Modifier.toString(field.getModifiers()),
field.getType().getSimpleName(),
field.getName()
);
}
}
}
The above snippet uses reflection to inspect all the declared fields of class String
; it produces the following output:
7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER
Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection
These are excerpts from the book:
Given a Class
object, you can obtain Constructor
, Method
, and Field
instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:
- You lose all the benefits of compile-time checking.
- The code required to perform reflective access is clumsy and verbose.
- Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at runtime.
There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.
Round integers to the nearest 10
round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:
>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000
What does string::npos mean in this code?
we have to use string::size_type
for the return type of the find function otherwise the comparison with string::npos
might not work.
size_type
, which is defined by the allocator of the string, must be an unsigned
integral type. The default allocator, allocator, uses type size_t
as size_type
. Because -1
is
converted into an unsigned integral type, npos is the maximum unsigned value of its type. However,
the exact value depends on the exact definition of type size_type
. Unfortunately, these maximum
values differ. In fact, (unsigned long)-1
differs from (unsigned short)-
1 if the size of the
types differs. Thus, the comparison
idx == std::string::npos
might yield false if idx has the value -1
and idx and string::npos
have different types:
std::string s;
...
int idx = s.find("not found"); // assume it returns npos
if (idx == std::string::npos) { // ERROR: comparison might not work
...
}
One way to avoid this error is to check whether the search fails directly:
if (s.find("hi") == std::string::npos) {
...
}
However, often you need the index of the matching character position. Thus, another simple solution
is to define your own signed value for npos:
const int NPOS = -1;
Now the comparison looks a bit different and even more convenient:
if (idx == NPOS) { // works almost always
...
}
What do the python file extensions, .pyc .pyd .pyo stand for?
.py
: This is normally the input source code that you've written.
.pyc
: This is the compiled bytecode. If you import a module, python will build a *.pyc
file that contains the bytecode to make importing it again later easier (and faster).
.pyo
: This was a file format used before Python 3.5 for *.pyc
files that were created with optimizations (-O
) flag. (see the note below)
.pyd
: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll
Also for some further discussion on .pyc
vs .pyo
, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
- When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only
__doc__
strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
Note:
On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo
files.
This means that .pyc
files represent both unoptimized and optimized bytecode.
Angular-Material DateTime Picker Component?
Angular Material 10 now includes a new date range picker.
To use the new date range picker, you can use the mat-date-range-input
and mat-date-range-picker
components.
Example
HTML
<mat-form-field>
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate matInput placeholder="Start date">
<input matEndDate matInput placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
You can read and learn more about this in their official documentation.
Unfortunately, they still haven't build a timepicker
on this release.
Carriage Return\Line feed in Java
Encapsulate your writer to provide char replacement, like this:
public class WindowsFileWriter extends Writer {
private Writer writer;
public WindowsFileWriter(File file) throws IOException {
try {
writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
} catch (UnsupportedEncodingException e) {
writer = new FileWriter(logfile);
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
}
@Override
public void flush() throws IOException {
writer.flush();
}
@Override
public void close() throws IOException {
writer.close();
}
}
How to git-svn clone the last n revisions from a Subversion repository?
I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).
# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase
And a good way to find out where a branch started is to do a svn log
it and find the first one on the branch (the last one listed when doing):
svn log --stop-on-copy svn://some/repo/branch/some-branch
So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.
Markdown open a new window link
It is very dependent of the engine that you use for generating html files.
If you are using Hugo for generating htmls you have to write down like this:
<a href="https://example.com" target="_blank" rel="noopener"><span>Example Text</span> </a>.
PHP: How to check if a date is today, yesterday or tomorrow
There is no built-in functions to do that in Php (shame ^^). You want to compare a date string to today, you could use a simple substr
to achieve it:
if (substr($timestamp, 0, 10) === date('Y.m.d')) { today }
elseif (substr($timestamp, 0, 10) === date('Y.m.d', strtotime('-1 day')) { yesterday }
No date conversion, simple.
Google.com and clients1.google.com/generate_204
The generate 204 might be dynamically loading the suggestions of search criteria. AS i can see from my load test script, this is seemingly responsible for every server call each time the user types into the text box
7-Zip command to create and extract a password-protected ZIP file on Windows?
From http://www.dotnetperls.com:
7z a secure.7z * -pSECRET
Where:
7z : name and path of 7-Zip executable
a : add to archive
secure.7z : name of destination archive
* : add all files from current directory to destination archive
-pSECRET : specify the password "SECRET"
To open :
7z x secure.7z
Then provide the SECRET password
Note:
If the password contains spaces or special characters, then enclose it with single quotes
7z a secure.7z * -p"pa$$word @|"
How to load a UIView using a nib file created with Interface Builder
This is something that ought to be easier. I ended up extending UIViewController
and adding a loadNib:inPlaceholder:
selector. Now I can say
self.mySubview = (MyView *)[self loadNib:@"MyView" inPlaceholder:mySubview];
Here's the code for the category (it does the same rigamarole as described by Gonso):
@interface UIViewController (nibSubviews)
- (UIView *)viewFromNib:(NSString *)nibName;
- (UIView *)loadNib:(NSString *)nibName inPlaceholder:(UIView *)placeholder;
@end
@implementation UIViewController (nibSubviews)
- (UIView *)viewFromNib:(NSString *)nibName
{
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
for (id view in xib) { // have to iterate; index varies
if ([view isKindOfClass:[UIView class]]) return view;
}
return nil;
}
- (UIView *)loadNib:(NSString *)nibName inPlaceholder:(UIView *)placeholder
{
UIView *nibView = [self viewFromNib:nibName];
[nibView setFrame:placeholder.frame];
[self.view insertSubview:nibView aboveSubview:placeholder];
[placeholder removeFromSuperview];
return nibView;
}
@end
Handling the null value from a resultset in JAVA
Since the column may be null in the
database, the rs.getString() will
throw a NullPointerException()
No.
rs.getString
will not throw NullPointer
if the column is present in the selected result set (SELECT query columns)
For a particular record if value for the 'comumn is null in db, you must do something like this -
String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
myValue = ""; // set it to empty string as you desire.
}
You may want to refer to wasNull()
documentation -
From java.sql.ResultSet
boolean wasNull() throws SQLException;
* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* @return <code>true</code> if the last column value read was SQL
* <code>NULL</code> and <code>false</code> otherwise
* @exception SQLException if a database access error occurs or this method is
* called on a closed result set
*/
Creating a list of objects in Python
Create a new instance each time, where each new instance has the correct state, rather than continually modifying the state of the same instance.
Alternately, store an explicitly-made copy of the object (using the hint at this page) at each step, rather than the original.
Android Error - Open Failed ENOENT
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
How to detect input type=file "change" for the same file?
The simplest way would be to set the input value to an empty string directly in the change or input event, which one mostly listens to anyways.
onFileInputChanged(event) {
// todo: read the filenames and do the work
// reset the value directly using the srcElement property from the event
event.srcElement.value = ""
}
How to create a string with format?
No NSString
required!
String(format: "Value: %3.2f\tResult: %3.2f", arguments: [2.7, 99.8])
or
String(format:"Value: %3.2f\tResult: %3.2f", 2.7, 99.8)
Mocking methods of local scope objects with Mockito
You can do this by creating a factory method in MyObject:
class MyObject {
public static MyObject create() {
return new MyObject();
}
}
then mock that with PowerMock.
However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.
In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:
void method1(MyObject obj1) {
obj1.method1();
}
passing in the dependency, which you can easily mock for the unit test.
What is a PDB file?
A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.
You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug
switch.
ActivityCompat.requestPermissions not showing dialog box
I had the same issue and it turned out to be due to the manifest merger tool pulling in an android:maxSdkVersion
attribute from a dependency.
To view the actual permissions you're requesting in your APK you can use the aapt
tool, like this:
/path/to/android-sdk/build-tools/version/aapt d permissions /path/to/your-apk.apk
in my case, it printed:
uses-permission: name='android.permission.WRITE_EXTERNAL_STORAGE' maxSdkVersion='18'
even though I hadn't specified a maxSdkVersion
in my manifest. I fixed this issue by changing <uses-permission>
in my manifest to:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:remove="android:maxSdkVersion"/>
(where the tools namespace is http://schemas.android.com/tools
)
How to redirect single url in nginx?
Put this in your server directive:
location /issue {
rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
}
Or duplicate it:
location /issue1 {
rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
...
C fopen vs open
open()
is a low-level os call. fdopen()
converts an os-level file descriptor to the higher-level FILE-abstraction of the C language. fopen()
calls open()
in the background and gives you a FILE-pointer directly.
There are several advantages to using FILE-objects rather raw file descriptors, which includes greater ease of usage but also other technical advantages such as built-in buffering. Especially the buffering generally results in a sizeable performance advantage.
Java Compare Two Lists
I found a very basic example of List comparison at List Compare
This example verifies the size first and then checks the availability of the particular element of one list in another.
Check whether a string contains a substring
Another possibility is to use regular expressions which is what Perl is famous for:
if ($mystring =~ /s1\.domain\.com/) {
print qq("$mystring" contains "s1.domain.com"\n);
}
The backslashes are needed because a .
can match any character. You can get around this by using the \Q
and \E
operators.
my $substring = "s1.domain.com";
if ($mystring =~ /\Q$substring\E/) {
print qq("$mystring" contains "$substring"\n);
}
Or, you can do as eugene y stated and use the index function.
Just a word of warning: Index returns a -1
when it can't find a match instead of an undef
or 0
.
Thus, this is an error:
my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
print qq("$mystring" doesn't contains "$substring"\n";
}
This will be wrong if s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.
DateTime group by date and hour
SQL Server :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);
Oracle :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');
MySQL :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )
Unit tests vs Functional tests
TLDR:
To answer the question: Unit Testing is a subtype of Functional Testing.
There are two big groups: Functional and Non-Functional Testing. The best (non-exhaustive) illustration that I found is this one (source: www.inflectra.com):
(1) Unit Testing: testing of small snippets of code (functions/methods). It may be considered as (white-box) functional testing.
When functions are put together, you create a module = a standalone piece, possibly with a User Interface that can be tested (Module Testing). Once you have at least two separate modules, then you glue them together and then comes:
(2) Integration Testing: when you put two or more pieces of (sub)modules or (sub)systems together and see if they play nicely together.
Then you integrate the 3rd module, then the 4th and 5th in whatever order you or your team see fit, and once all the jigsaw pieces are placed together, comes
(3) System Testing: testing SW as a whole. This is pretty much "Integration testing of all pieces together".
If that's OK, then comes
(4) Acceptance Testing: did we build what the customer asked for actually? Of course, Acceptance Testing should be done throughout the lifecycle, not just at the last stage, where you realise that the customer wanted a sportscar and you built a van.
How do I measure separate CPU core usage for a process?
I thought perf stat
is what you need.
It shows a specific usage of a process when you specify a --cpu=list
option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j
command. The output is:
CPU0 119254.719293 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU1 119254.724776 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU2 119254.724179 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU3 119254.720833 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU4 119254.714109 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU5 119254.727721 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU6 119254.723447 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU7 119254.722418 task-clock (msec) # 1.000 CPUs utilized (100.00%)
CPU0 8,108 context-switches # 0.068 K/sec (100.00%)
CPU1 26,494 context-switches (100.00%)
CPU2 10,193 context-switches (100.00%)
CPU3 12,298 context-switches (100.00%)
CPU4 16,179 context-switches (100.00%)
CPU5 57,389 context-switches (100.00%)
CPU6 8,485 context-switches (100.00%)
CPU7 10,845 context-switches (100.00%)
CPU0 167 cpu-migrations # 0.001 K/sec (100.00%)
CPU1 80 cpu-migrations (100.00%)
CPU2 165 cpu-migrations (100.00%)
CPU3 139 cpu-migrations (100.00%)
CPU4 136 cpu-migrations (100.00%)
CPU5 175 cpu-migrations (100.00%)
CPU6 256 cpu-migrations (100.00%)
CPU7 195 cpu-migrations (100.00%)
The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr
option, the result will aggregated together. The --pid=pid
option will help if you want to monitor a running process.
Try -a --per-core
or -a perf-socket
too, which will present more classified information.
More about usage of perf stat
can be seen in this tutorial: perf cpu statistic, also perf help stat
will help on the meaning of the options.
What are all the user accounts for IIS/ASP.NET and how do they differ?
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
Understanding Built-In User and Group Accounts in IIS 7
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
Application Pool Identities
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LocalService Account
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
LocalSystem Account
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
How to enable loglevel debug on Apache2 server
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf:
Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
Batch files: List all files in a directory with relative paths
This answer will not work correctly with root paths containing equal signs (=
). (Thanks @dbenham for pointing that out.)
EDITED: Fixed the issue with paths containing !
, again spotted by @dbenham (thanks!).
Alternatively to calculating the length and extracting substrings you could use a different approach:
Here's my attempt (which worked for me):
@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
SET "p=%%F"
SETLOCAL EnableDelayedExpansion
ECHO(!p:%r%=!
ENDLOCAL
)
The r
variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \
, which we amend by appending the character. (No longer the case, as the script now reads the __CD__
variable, whose value always ends with \
(thanks @jeb!), instead of CD
.)
In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.
Which MIME type to use for a binary file that's specific to my program?
I'd recommend application/octet-stream
as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".
I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.
function is not defined error in Python
In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:
def pyth_test (x1, x2):
print x1 + x2
pyth_test(1, 2)
But this won't:
pyth_test(1, 2)
def pyth_test (x1, x2):
print x1 + x2
Can't push to remote branch, cannot be resolved to branch
I was having this issue as well, and it was driving me crazy. I had something like feature/name
but git branch -a
showed me FEATURE/name
. Renaming the branch, deleting and recreating it, nothing worked. What finally fixed it:
Go into .git/refs/heads
You'll see a FEATURE
folder. Rename it to feature
.
Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL
There's a bit of confusion in your question:
- a
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.
- When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the
TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.
- Reciprocally, you would use
TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.
- You use
FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).
- In Oracle,
CST
is a time zone but CDT
is not. CDT
is a daylight saving information.
- To complicate things further,
CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.
So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
How to list installed packages from a given repo using yum
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output).
However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
JavaScript or jQuery browser back button click detector
there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.
Detect if user pressed "Back" button on current page:
Detect if current page is visited after pressing "Back" button on previous("Forward") page:
Show red border for all invalid fields after submitting form angularjs
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
Adding a guideline to the editor in Visual Studio
If you are a user of the free Visual Studio Express edition the right key is in
HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor
{note the VCExpress instead of VisualStudio) but it works! :)
Hbase quickly count number of rows
To count the Hbase table record count on a proper YARN cluster you have to set the map reduce job queue name as well:
hbase org.apache.hadoop.hbase.mapreduce.RowCounter -Dmapreduce.job.queuename= < Your Q Name which you have SUBMIT access>
< TABLE_NAME>
How can I "disable" zoom on a mobile web page?
You can accomplish the task by simply adding the following 'meta' element into your 'head':
<meta name="viewport" content="user-scalable=no">
Adding all the attributes like 'width','initial-scale', 'maximum-width', 'maximum-scale' might not work. Therefore, just add the above element.
MySQL - Cannot add or update a child row: a foreign key constraint fails
Since you haven't given table definitions, it's hard to guess. But it looks like you are attempting to modify the foreign key in the child table. AFAIK, this is illegal, you can modify it from the parent, but not the child table.
Consider this example:
CREATE TABLE parent (
parent_id INT NOT NULL,
parent_data int,
PRIMARY KEY (parent_id)
) ENGINE=INNODB;
CREATE TABLE child1 (
child1_id INT,
child1_data INT,
fk_parent_id INT,
INDEX par_ind1 (fk_parent_id),
FOREIGN KEY (fk_parent_id)
REFERENCES parent(parent_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
CREATE TABLE child2 (
child2_id INT,
child2_data INT,
fk_parent_id INT,
INDEX par_ind2 (fk_parent_id),
FOREIGN KEY (fk_parent_id)
REFERENCES parent(parent_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
INSERT INTO parent
(parent_id, parent_data)
VALUES
(1, 11),
(2, 12);
INSERT INTO child1
(child1_id, child1_data, fk_parent_id)
VALUES
(101, 1001, 1),
(102, 1002, 1),
(103, 1003, 1),
(104, 1004, 2),
(105, 1005, 2);
INSERT INTO child2
(child2_id, child2_data, fk_parent_id)
VALUES
(106, 1006, 1),
(107, 1007, 1),
(108, 1008, 1),
(109, 1009, 2),
(110, 1010, 2);
Then this is allowed:
UPDATE parent
SET parent_id = 3 WHERE parent_id = 2;
SELECT * FROM parent;
SELECT * FROM child1;
SELECT * FROM child2;
But this is not, because it modifies the parent fk from the child table:
UPDATE child1
SET fk_parent_id = 4 WHERE fk_parent_id = 1;
It gets an error very similar to your error:
Cannot add or update a child row: a foreign key constraint fails (`db_2_b43a7`.`child1`, CONSTRAINT `child1_ibfk_1` FOREIGN KEY (`fk_parent_id`) REFERENCES `parent` (`parent_id`) ON DELETE CASCADE ON UPDATE CASCADE):
Is there a color code for transparent in HTML?
All you need is this:
#ffffff00
Here the ffffff
is the color and 00
is the transparency
Also, if you want 50% transparent color, then sure you can do...
#ffffff80
Where 80
is the hexadecimal equivalent of 50%
.
Since the scale is 0-255 in RGB Colors, the half would be 255/2 = 128
, which when converted to hex becomes 80
And since in transparent we want 0 opacity, we write 00
Get ID of element that called a function
I'm surprised that nobody has mentioned the use of this
in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener
or attachEvent
to install your event handler, then you can make the value of this
automatically be assigned to the object the created the event.
Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.
Here's how you would do that in your code in plain javascript:
Remove the onmouseover="zoom()"
from your HTML and install the event handler in your javascript like this:
// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}
function zoom() {
// you can use "this" here to refer to the object that caused the event
// this here will refer to the calling object (which in this case is the <map>)
console.log(this.id);
document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}
// register your event handler
setEventHandler("nose", "mouseover", zoom);
How can I rollback an UPDATE query in SQL server 2005?
in this example we run 2 line insert into query and if all of them true it run but if not no run anything and ROLLBACK
DECLARE @rowcount int set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
insert into [database].[dbo].[tbl1] (fld1) values('1') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
insert into [database].[dbo].[tbl2] (fld1) values('2') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
IF @rowcount = 2
COMMIT TRANSACTION[Tran1]
ELSE
ROLLBACK TRANSACTION[Tran1]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION[Tran1]
END CATCH
How to read numbers from file in Python?
Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
List all files in one directory PHP
Check this out : readdir()
This bit of code should list all entries in a certain directory:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
Edit: miah's solution is much more elegant than mine, you should use his solution instead.
Aligning two divs side-by-side
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy...
Please Note: This works in Higher version of CSS (>3.0).
TortoiseGit-git did not exit cleanly (exit code 1)
I ran into the same issue after upgrading Git. Turns out I switched from 32-bit to 64-bit Git and I didn't realize it. TortoiseGit was still looking for "C:\Program Files (x86)\Git\bin", which didn't exist. Right-click the folder, go to Tortoise Git > Settings > General and update the Git.exe path.
What is a classpath and how do I set it?
Static member of a class can be called directly without creating object instance.
Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method, which is start point of program.
PHP 5.4 Call-time pass-by-reference - Easy fix available?
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
From the documentation:
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use &
in foo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
MVC pattern on Android
Description:
- When we have to main large projects in the software development, MVC
is generally used because it’s a universal way of organizing the
projects.
- New developers can quickly adapt to the project
- Helps in development of big projects and cross platform too.
The MVC pattern is essentially this:
- Model: What to display. This can be the data source (Ex: Server, Raw
data in the app)
- View: How it’s displayed. This can be the xml. It is thus acting as a
presentation filter. A view is attached to its model (or model part)
and gets the data necessary for the presentation.
- Controller: Handling events like user input. This be the activity
Important feature of MVC: We can modify Either the Model or View or Controller still not affecting the other ones
- Say we change the color in the view, size of the view or the position
of the view. By doing so it won’t affect the model or the controller
- Say we change the model (instead of data fetched from the server
fetch data from assets ) still it won’t affect the view and
controller
- Say we change the Controller(Logic in the activity) it won’t affect
the model and the view
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Does Python have a string 'contains' substring method?
If it's just a substring search you can use string.find("substring")
.
You do have to be a little careful with find
, index
, and in
though, as they are substring searches. In other words, this:
s = "This be a string"
if s.find("is") == -1:
print("No 'is' here!")
else:
print("Found 'is' in the string.")
It would print Found 'is' in the string.
Similarly, if "is" in s:
would evaluate to True
. This may or may not be what you want.
Loop through all nested dictionary values?
Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it
def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield (key, value)
yield from recursive_items(value)
else:
yield (key, value)
a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
for key, value in recursive_items(a):
print(key, value)
Prints
a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6
IE prompts to open or save json result from server
Even though it's not supposedly the correct way, setting the content type to text/html made IE deal with this correctly for me:
return Json(result, "text/html");
Works in all the version that F12 tools gives you in IE9.
Switch to another branch without changing the workspace files
It sounds like you made changes, committing them to master along the way, and now you want to combine them into a single commit.
If so, you want to rebase your commits, squashing them into a single commit.
I'm not entirely sure of what exactly you want, so I'm not going to tempt you with a script. But I suggest you read up on git rebase
and the options for "squash"ing, and try a few things out.
Linux - Install redis-cli only
There are many way to install radis-cli
. It comes with redis-tools
and redis-server
. Installing any of them will install redis-cli
too. But it will also install other tools too. As you have redis-server
installed somewhere and only interested to install redis-cli
. To install install only redis-cli
without other unnecessary tools follow below command
cd /tmp
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
cp src/redis-cli /usr/local/bin/
chmod 755 /usr/local/bin/redis-cli
Count how many rows have the same value
If you want to have the result for all values of NUM
:
SELECT `NUM`, COUNT(*) AS `count`
FROM yourTable
GROUP BY `NUM`
Or just for one specific:
SELECT `NUM`, COUNT(*) AS `count`
FROM yourTable
WHERE `NUM`=1
"No such file or directory" error when executing a binary
Well another possible cause of this can be simple line break at end of each line and shebang line
If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems
Is there an onSelect event or equivalent for HTML <select>?
Just an idea, but is it possible to put an onclick on each of the <option>
elements?
<select>
<option onclick="doSomething(this);">A</option>
<option onclick="doSomething(this);">B</option>
<option onclick="doSomething(this);">C</option>
</select>
Another option could be to use onblur on the select. This will fire anytime the user clicks away from the select. At this point you could determine what option was selected. To have this even trigger at the correct time, the onclick of the option's could blur the field (make something else active or just .blur() in jQuery).
Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
How I can filter a Datatable?
Hi we can use ToLower Method sometimes it is not filter.
EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
(row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());
if (rows.Any())
{
tblFiltered = rows.CopyToDataTable<DataRow>();
}
WPF Application that only has a tray icon
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
Outline effect to text
_x000D_
_x000D_
h1 {_x000D_
color: black;_x000D_
-webkit-text-fill-color: white; /* Will override color (regardless of order) */_x000D_
-webkit-text-stroke-width: 1px;_x000D_
-webkit-text-stroke-color: black;_x000D_
}
_x000D_
<h1>Properly stroked!</h1>
_x000D_
_x000D_
_x000D_
How to locate the git config file in Mac
The solution to the problem is:
Find the .gitconfig file
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url ""]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
there would be a blank url=""
replace it with url="https://"
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url "https://"]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
This will work :)
Happy Bower-ing
How can I get an int from stdio in C?
The typical way is with scanf
:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf
returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf
family (sscanf
, fscanf
and so on).
Is there a way to delete all the data from a topic or delete the topic before every run?
As a dirty workaround, you can adjust per-topic runtime retention settings, e.g. bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic my_topic --config retention.bytes=1
(retention.bytes=0 might also work)
After a short while kafka should free the space. Not sure if this has any implications compared to re-creating the topic.
ps. Better bring retention settings back, once kafka done with cleaning.
You can also use retention.ms
to persist historical data
Find files in a folder using Java
What you want is File.listFiles(FileNameFilter filter)
.
That will give you a list of the files in the directory you want that match a certain filter.
The code will look similar to:
// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("temp") && name.endsWith("txt");
}
});
Select Pandas rows based on list index
you can also use iloc:
df.iloc[[1,3],:]
This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:
df.index.isin([1,3])
... as suggested in other responses.
Best practices for SQL varchar column length
The best value is the one that is right for the data as defined in the underlying domain.
For some domains, VARCHAR(10)
is right for the Name
attribute, for other domains VARCHAR(255)
might be the best choice.
How to construct a REST API that takes an array of id's for the resources
I find another way of doing the same thing by using @PathParam
. Here is the code sample.
@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
Multiprocessing: How to use Pool.map on a function defined in a class?
I know that this question was asked 8 years and 10 months ago but I want to present you my solution:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@staticmethod
def methodForMultiprocessing(x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
You just need to make your class function into a static method. But it's also possible with a class method:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@classmethod
def methodForMultiprocessing(cls, x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
Tested in Python 3.7.3
How to replace item in array?
My suggested solution would be:
items.splice(1, 1, 1010);
The splice operation will remove 1 item, starting at position 1 in the array (i.e. 3452
), and will replace it with the new item 1010
.
Why is null an object and what's the difference between null and undefined?
TLDR
undefined
is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return
statement, return undefined
.
null
is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null
in JavaScript was designed to enable interoperability with Java.
typeof null
returns "object"
because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null
is an instance of an object. It means: given the tree of primitive types in JavaScript, null
is part of the "object-type primitive" subtree. This is explained more fully below.
Details
undefined
is a primitive value that represents the implicit absence of a value. Note that undefined
was not directly accessible until JavaScript 1.3 in 1998. This tells us that null
was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined
. undefined
is a one-of-a-kind type in the ECMAScript specification.
null
is a primitive value that represents the intentional absence of an object value. null
is also a one-of-a-kind type in the ECMAScript specification.
null
in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".
Brendan Eich:
If I didn't have "Make it look like Java" as an order from management,
and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object"
approach: no Boolean, Number, String wrappers. No undefined and null.
Sigh.
In order to accommodate Java's concept of null
which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null
value at the top of the object prototype chain (ie. the top of the reference types), and to include the null
type as part of the set of "object-type primitives".
The typeof
operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.
From the V8 blog:
typeof null
returns object
, and not null
, despite null
being a
type of its own. To understand why, consider that the set of all
JavaScript types is divided into two groups:
- objects (i.e. the Object type)
- primitives (i.e. any non-object value)
As such, null
means “no object value”, whereas undefined
means “no
value”.
Following this line of thought, Brendan Eich designed JavaScript to
make typeof
return 'object' for all values on the right-hand side,
i.e. all objects and null values, in the spirit of Java. That’s why
typeof null === 'object'
despite the spec having a separate null
type.
So Eich designed the heirarchy of primitive types to enable interoperability with Java. This led to him positioning null
along with the "object-type primitives" on the heirarchy. To refelct this, when typeof
was added to the language shortly thereafter, he chose typeof null
to return "object"
.
The surprise expressed by JavaScript developers at typeof null === "object"
is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null
and undefined
, and another, strongly-typed language (Java) that only has null
, and in which null
is strictly defined to refer to a reference type (not a primitive type).
Note that this is all logical, reasonable and defensible. typeof null === "object"
is not a bug, but a second-order effect of having to accommodate Java interoperability.
A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined
indicates implicit absence of a value, and that null
indicates intentional absence of a value; or that undefined
is the absence of a value, and null
is specifically the absence of an object value.
A relevant conversation with Brendan Eich, screenshotted for posterity:
How to unapply a migration in ASP.NET Core with EF Core
To unapply a specific migration(s):
dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName
To unapply all migrations:
dotnet ef database update 0
or
PM> Update-Database -Migration 0
To remove last migration:
dotnet ef migrations remove
or
PM> Remove-Migration
To remove all migrations:
just remove Migrations
folder.
To remove last few migrations (not all):
There is no a command to remove a bunch of migrations and we can't just remove these few migrations
and their *.designer.cs
files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration
above).
To unapply and remove last migration:
dotnet ef migrations remove --force
or
PM> Remove-Migration -Force
Python TypeError: not enough arguments for format string
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
What does -save-dev mean in npm install grunt --save-dev
For me the first answer appears a bit confusing, so to make it short and clean:
npm install <package_name>
saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:
npm install <package_name> --no-save
Prevents saving to dependencies.
npm install <package_name> ---save-dev
updates the devDependencies
in your package. These are only used for local testing and development.
You can read more at in the dcu
JUnit test for System.out.println()
You can set the System.out print stream via setOut() (and for in
and err
). Can you redirect this to a print stream that records to a string, and then inspect that ? That would appear to be the simplest mechanism.
(I would advocate, at some stage, convert the app to some logging framework - but I suspect you already are aware of this!)
How do I merge a specific commit from one branch into another in Git?
If BranchA has not been pushed to a remote then you can reorder the commits using rebase
and then simply merge
. It's preferable to use merge
over rebase
when possible because it doesn't create duplicate commits.
git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
How to paginate with Mongoose in Node.js?
The best approach (IMO) is to use skip and limit BUT within a limited collections or documents.
To make the query within limited documents, we can use specific index like index on a DATE type field. See that below
let page = ctx.request.body.page || 1
let size = ctx.request.body.size || 10
let DATE_FROM = ctx.request.body.date_from
let DATE_TO = ctx.request.body.date_to
var start = (parseInt(page) - 1) * parseInt(size)
let result = await Model.find({ created_at: { $lte: DATE_FROM, $gte: DATE_TO } })
.sort({ _id: -1 })
.select('<fields>')
.skip( start )
.limit( size )
.exec(callback)
Java: Convert String to TimeStamp
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Util {
public static Timestamp convertStringToTimestamp(String strDate) {
try {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// you can change format of date
Date date = formatter.parse(strDate);
Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
}
VBA: Conditional - Is Nothing
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
How to declare a global variable in C++
In addition to other answers here, if the value is an integral constant, a public enum in a class or struct will work. A variable - constant or otherwise - at the root of a namespace is another option, or a static public member of a class or struct is a third option.
MyClass::eSomeConst (enum)
MyNamespace::nSomeValue
MyStruct::nSomeValue (static)
Check if number is decimal
i use this:
function is_decimal ($price){
$value= trim($price); // trim space keys
$value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
$value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
$value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12
return $value;
}
Python not working in command prompt?
Just go with the command py
. I'm running python 3.6.2 on windows 7 and it works just fine.
I removed all the python paths from the system directory and the paths don't show up when I run the command echo %path%
in cmd. Python is still working fine.
I ran into this by accidentally pressing enter while typing python
...
EDIT: I didn't mention that I installed python to a custom folder C:\Python\
sys.stdin.readline() reads without prompt, returning 'nothing in between'
stdin.read(1)
reads one character from stdin
. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read()
or readline()
.
As an example, given rd.py
:
from sys import stdin
x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)
... if I run this script as follows (I've typed in the 234
):
C:\>python rd.py
234
x= 2
userinput= 34
betAmount= 34
... so the 2
is being picked up first, leaving the 34
and the trailing newline character to be picked up by the readline()
.
I'd suggest fixing the problem by using readline()
rather than read()
under most circumstances.
For each row in an R dataframe
First, Jonathan's point about vectorizing is correct. If your getWellID() function is vectorized, then you can skip the loop and just use cat or write.csv:
write.csv(data.frame(wellid=getWellID(well$name, well$plate),
value1=well$value1, value2=well$value2), file=outputFile)
If getWellID() isn't vectorized, then Jonathan's recommendation of using by
or knguyen's suggestion of apply
should work.
Otherwise, if you really want to use for
, you can do something like this:
for(i in 1:nrow(dataFrame)) {
row <- dataFrame[i,]
# do stuff with row
}
You can also try to use the foreach
package, although it requires you to become familiar with that syntax. Here's a simple example:
library(foreach)
d <- data.frame(x=1:10, y=rnorm(10))
s <- foreach(d=iter(d, by='row'), .combine=rbind) %dopar% d
A final option is to use a function out of the plyr
package, in which case the convention will be very similar to the apply function.
library(plyr)
ddply(dataFrame, .(x), function(x) { # do stuff })