How can I invert color using CSS?
Add the same color of the background to the paragraph and then invert with CSS:
_x000D_
_x000D_
div {_x000D_
background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
color: #f00;_x000D_
-webkit-filter: invert(100%);_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
<p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Getting data from selected datagridview row and which event?
You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
I hope it helps.
php hide ALL errors
To hide errors only from users
but displaying logs errors in apache log
error_reporting(E_ALL);
ini_set('display_errors', 0);
1 - Displaying error only in log
2 - hide from users
C# catch a stack overflow exception
As mentioned above several times, it's not possible to catch a StackOverflowException that was raised by the System due to corrupted process-state. But there's a way to notice the exception as an event:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
Starting with the .NET Framework version 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
Nevertheless your application will terminate after exiting the event-function (a VERY dirty workaround, was to restart the app within this event haha, havn't done so and never will do). But it's good enough for logging!
In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.
How to exit from Python without traceback?
Perhaps you're trying to catch all exceptions and this is catching the SystemExit
exception raised by sys.exit()
?
import sys
try:
sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
# (Insert your cleanup code here.)
raise
In general, using except:
without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like SystemExit
-- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:
import sys
sys.exit(1) # Or something that calls sys.exit().
If you need to exit without raising SystemExit
:
import os
os._exit(1)
I do this, in code that runs under unittest and calls fork()
. Unittest gets when the forked process raises SystemExit
. This is definitely a corner case!
Counting the number of files in a directory using Java
public void shouldGetTotalFilesCount() {
Integer reduce = of(listRoots()).parallel().map(this::getFilesCount).reduce(0, ((a, b) -> a + b));
}
private int getFilesCount(File directory) {
File[] files = directory.listFiles();
return Objects.isNull(files) ? 1 : Stream.of(files)
.parallel()
.reduce(0, (Integer acc, File p) -> acc + getFilesCount(p), (a, b) -> a + b);
}
How to get a product's image in Magento?
I recently needed to do this as well... here's how I got to it:
$_product->getMediaGalleryImages()->getItemByColumnValue('label', 'LABEL_NAME')->getUrl();
Hope that helps you!
Reverse a comparator in Java 8
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
Replacing Spaces with Underscores
This is part of my code which makes spaces into underscores for naming my files:
$file = basename($_FILES['upload']['name']);
$file = str_replace(' ','_',$file);
Using variables in Nginx location rules
You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:
"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html
You should either write or download a little tool that will allow you to generate config files from placeholder config files.
Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.
e.g. my nginx source config file looks like this:
location / {
try_files $uri /routing.php?$args;
fastcgi_pass unix:%phpfpm.socket%/php-fpm-www.sock;
include %mysite.root.directory%/conf/fastcgi.conf;
}
And then I have a config file with the variables defined:
phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite
And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:
<?php
require_once('path.php');
$filesToGenerate = array(
'conf/nginx.conf' => 'autogen/nginx.conf',
'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
'conf/my.cnf' => 'autogen/my.cnf',
);
$environment = 'amazonec2';
if ($argc >= 2){
$environmentRequired = $argv[1];
$allowedVars = array(
'amazonec2',
'macports',
);
if (in_array($environmentRequired, $allowedVars) == true){
$environment = $environmentRequired;
}
}
else{
echo "Defaulting to [".$environment."] environment";
}
$config = getConfigForEnvironment($environment);
foreach($filesToGenerate as $inputFilename => $outputFilename){
generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}
function getConfigForEnvironment($environment){
$config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
$configWithMarkers = array();
foreach($config[$environment] as $key => $value){
$configWithMarkers['%'.$key.'%'] = $value;
}
return $configWithMarkers;
}
function generateConfigFile($inputFilename, $outputFilename, $config){
$lines = file($inputFilename);
if($lines === FALSE){
echo "Failed to read [".$inputFilename."] for reading.";
exit(-1);
}
$fileHandle = fopen($outputFilename, "w");
if($fileHandle === FALSE){
echo "Failed to read [".$outputFilename."] for writing.";
exit(-1);
}
$search = array_keys($config);
$replace = array_values($config);
foreach($lines as $line){
$line = str_replace($search, $replace, $line);
fwrite($fileHandle, $line);
}
fclose($fileHandle);
}
?>
And then deployConfig.ini looks something like:
[global]
;global variables go here.
[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory = /var/run
nginx.user = nginx
[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory = /opt/local/var/run
nginx.user = _www
What is a 'workspace' in Visual Studio Code?
The title and subsequent question in the OP seem to boil down to:
- What is a workspace in VS Code?
- How do workspace settings work?
Short answer:
A workspace is a virtual collection of folders opened simultaneously in VSCode and defined in a .code-workspace
file. Opening this file will open the collection of folders automatically. This is called a "multi-root" workspace.
The .code-workspace
file also defines workspace settings that are used by the instance of VSCode where the workspace is opened.
When a workspace is not defined, i.e. you open a folder on its own, you can create "workspace settings" that are saved in a .vscode\settings.json
file in the root of that folder structure.
In more detail:
VSCode uses the word "workspace" a little ambiguously in places. The first use to consider is in what is calls a multi-root workspace.
A multi-root workspace is a set of folders (the "roots") that are opened collectively in an instance of VSCode. There is no need for these folders to share parent folders; indeed that is the point since VSCode normally uses a single folder in the Explorer side-bar.
A multi-root workspace is defined by a .code-workspace
(JSON) file which contains both the list of folders to be included in the workspace and VSCode settings.
Regarding those workspace settings...
When you open File > Preferences > Settings the settings editor is shown. At the very least you should see a USER SETTINGS tab. These are the VSCode settings that are universal for your user account on your local machine. In Windows these are saved in %APPDATA%\Code\User\settings.json
.
Individual folders (often each of the "root" folders in a workspace) might have a .vscode
folder with their own settings.json
file. When opened individually, i.e. not as part of a workspace, the content of these settings.json
files is presented under the WORKSPACE SETTINGS tab, and ALL the settings in that file are used by the running VSCode instance.
When opening a multi-root workspace things behave differently. Firstly, the WORKSPACE SETTINGS tab shows the options set in the .code-workspace
file. Secondly, any folder with a settings.json
file will appear under a new FOLDER SETTINGS tab. Be aware that, when in a multi-root workspace, only a limited number of settings from each folder's settings.json
are used. I suggest you open the link above to read further.
Twitter Bootstrap vs jQuery UI?
Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,
- Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
- Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
- Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
- Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
- Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.
Other notes,
- It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.
Fastest method to escape HTML tags as HTML entities?
All-in-one script:
// HTML entities Encode/Decode
function htmlspecialchars(str) {
var map = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'" // ' -> ' for XML only
};
return str.replace(/[&<>"']/g, function(m) { return map[m]; });
}
function htmlspecialchars_decode(str) {
var map = {
"&": "&",
"<": "<",
">": ">",
""": "\"",
"'": "'"
};
return str.replace(/(&|<|>|"|')/g, function(m) { return map[m]; });
}
function htmlentities(str) {
var textarea = document.createElement("textarea");
textarea.innerHTML = str;
return textarea.innerHTML;
}
function htmlentities_decode(str) {
var textarea = document.createElement("textarea");
textarea.innerHTML = str;
return textarea.value;
}
http://pastebin.com/JGCVs0Ts
How to remove illegal characters from path and filenames?
If you have to use the method in many places in a project, you could also make an extension method and call it anywhere in the project for strings.
public static class StringExtension
{
public static string RemoveInvalidChars(this string originalString)
{
string finalString=string.Empty;
if (!string.IsNullOrEmpty(originalString))
{
return string.Concat(originalString.Split(Path.GetInvalidFileNameChars()));
}
return finalString;
}
}
You can call the above extension method as:
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
string afterIllegalChars = illegal.RemoveInvalidChars();
Aggregate function in SQL WHERE-Clause
You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.
You can use a sub-query which contains an aggregate in the WHERE clause.
<button> background image
For some odd reason, the width and height of the button have been reset. You need to specify them in the ID selector as well:
#rock {
width: 150px;
height: 150px;
background-image: url(http://th07.deviantart.net/fs70/150/i/2013/012/c/6/rock_01_png___by_alzstock-d5r84up.png);
background-repeat: no-repeat;
}
Live test case.
UML diagram shapes missing on Visio 2013
If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.
- Search for UML Sequence in the search box -> Select all shapes and add to My shapes (user defined name).
You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.
Getting value from a cell from a gridview on RowDataBound event
The above are good suggestions, but you can get at the text value of a cell in a grid view without wrapping it in a literal or label control. You just have to know what event to wire up. In this case, use the DataBound event instead, like so:
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text.Contains("sometext"))
{
e.Row.Cells[0].Font.Bold = true;
}
}
}
When running a debugger, you will see the text appear in this method.
How to calculate md5 hash of a file using javascript
Assuming your'e using a modern browser (that supports HTML5 File API), here's how you calculate the MD5 Hash of a large file (it will calculate the hash on variable chunks)
_x000D_
_x000D_
function calculateMD5Hash(file, bufferSize) {
var def = Q.defer();
var fileReader = new FileReader();
var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var hashAlgorithm = new SparkMD5();
var totalParts = Math.ceil(file.size / bufferSize);
var currentPart = 0;
var startTime = new Date().getTime();
fileReader.onload = function(e) {
currentPart += 1;
def.notify({
currentPart: currentPart,
totalParts: totalParts
});
var buffer = e.target.result;
hashAlgorithm.appendBinary(buffer);
if (currentPart < totalParts) {
processNextPart();
return;
}
def.resolve({
hashResult: hashAlgorithm.end(),
duration: new Date().getTime() - startTime
});
};
fileReader.onerror = function(e) {
def.reject(e);
};
function processNextPart() {
var start = currentPart * bufferSize;
var end = Math.min(start + bufferSize, file.size);
fileReader.readAsBinaryString(fileSlicer.call(file, start, end));
}
processNextPart();
return def.promise;
}
function calculate() {
var input = document.getElementById('file');
if (!input.files.length) {
return;
}
var file = input.files[0];
var bufferSize = Math.pow(1024, 2) * 10; // 10MB
calculateMD5Hash(file, bufferSize).then(
function(result) {
// Success
console.log(result);
},
function(err) {
// There was an error,
},
function(progress) {
// We get notified of the progress as it is executed
console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize);
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script>
<div>
<input type="file" id="file"/>
<input type="button" onclick="calculate();" value="Calculate" class="btn primary" />
</div>
_x000D_
_x000D_
_x000D_
How to create war files
Another option would be to build it automatically using Eclipse. Of course if you have continuous integration environment Ant or Maven is recommended. The export alternative is not very convenient because you have to configure every time the export properties.
STEPS:
Enable "Project Archives" support; this might depend on your project (I used it on Java EE/Web project). Right-click project root directory; Configure -> Add Project Archives Support.
Go and create a new archive in the "Project Archives" top dir. You have only jar option, but name you archive *.war.
Configure Fileset-s, i.e what files to be included. Typical is to configure two filesets similar how the Web Deployment Assembly (project property) is configured.
- copy /WebContent to /
- copy /build/classes to WEB-INF/classes (create this fileset after you define the WEB-INF/classes directory in the archive)
You might need to tweek the fileset exclude property depending where you placed some of the config files or you might need more filesets, but the idea is that once you configured this you don't need to change it.
Build the archive manually or publish directly to server; but is also automatically built for you by Eclipse
How to read a file line-by-line into a list?
f = open("your_file.txt",'r')
out = f.readlines() # will append in the list out
Now variable out is a list (array) of what you want. You could either do:
for line in out:
print (line)
Or:
for line in f:
print (line)
You'll get the same results.
Command to delete all pods in all kubernetes namespaces
There is no command to do exactly what you asked.
Here are some close matches.
You can delete all the pods in a single namespace with this command:
kubectl delete --all pods --namespace=foo
You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace
kubectl delete --all deployments --namespace=foo
You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command:
kubectl delete --all namespaces
However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable.
This command will delete all the namespaces except kube-system, which might be useful:
for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
kubectl delete ns $each
done
How to measure the a time-span in seconds using System.currentTimeMillis()?
// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
.18 * (Math.toRadians(m)/Math.PI),
Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );
Evenly distributing n points on a sphere
The golden spiral method
You said you couldn’t get the golden spiral method to work and that’s a shame because it’s really, really good. I would like to give you a complete understanding of it so that maybe you can understand how to keep this away from being “bunched up.”
So here’s a fast, non-random way to create a lattice that is approximately correct; as discussed above, no lattice will be perfect, but this may be good enough. It is compared to other methods e.g. at BendWavy.org but it just has a nice and pretty look as well as a guarantee about even spacing in the limit.
Primer: sunflower spirals on the unit disk
To understand this algorithm, I first invite you to look at the 2D sunflower spiral algorithm. This is based on the fact that the most irrational number is the golden ratio (1 + sqrt(5))/2
and if one emits points by the approach “stand at the center, turn a golden ratio of whole turns, then emit another point in that direction,” one naturally constructs a spiral which, as you get to higher and higher numbers of points, nevertheless refuses to have well-defined ‘bars’ that the points line up on.(Note 1.)
The algorithm for even spacing on a disk is,
from numpy import pi, cos, sin, sqrt, arange
import matplotlib.pyplot as pp
num_pts = 100
indices = arange(0, num_pts, dtype=float) + 0.5
r = sqrt(indices/num_pts)
theta = pi * (1 + 5**0.5) * indices
pp.scatter(r*cos(theta), r*sin(theta))
pp.show()
and it produces results that look like (n=100 and n=1000):
Spacing the points radially
The key strange thing is the formula r = sqrt(indices / num_pts)
; how did I come to that one? (Note 2.)
Well, I am using the square root here because I want these to have even-area spacing around the disk. That is the same as saying that in the limit of large N I want a little region R ? (r, r + dr), T ? (?, ? + d?) to contain a number of points proportional to its area, which is r dr d?. Now if we pretend that we are talking about a random variable here, this has a straightforward interpretation as saying that the joint probability density for (R, T) is just c r for some constant c. Normalization on the unit disk would then force c = 1/p.
Now let me introduce a trick. It comes from probability theory where it’s known as sampling the inverse CDF: suppose you wanted to generate a random variable with a probability density f(z) and you have a random variable U ~ Uniform(0, 1), just like comes out of random()
in most programming languages. How do you do this?
- First, turn your density into a cumulative distribution function or CDF, which we will call F(z). A CDF, remember, increases monotonically from 0 to 1 with derivative f(z).
- Then calculate the CDF’s inverse function F-1(z).
- You will find that Z = F-1(U) is distributed according to the target density. (Note 3).
Now the golden-ratio spiral trick spaces the points out in a nicely even pattern for ? so let’s integrate that out; for the unit disk we are left with F(r) = r2. So the inverse function is F-1(u) = u1/2, and therefore we would generate random points on the disk in polar coordinates with r = sqrt(random()); theta = 2 * pi * random()
.
Now instead of randomly sampling this inverse function we’re uniformly sampling it, and the nice thing about uniform sampling is that our results about how points are spread out in the limit of large N will behave as if we had randomly sampled it. This combination is the trick. Instead of random()
we use (arange(0, num_pts, dtype=float) + 0.5)/num_pts
, so that, say, if we want to sample 10 points they are r = 0.05, 0.15, 0.25, ... 0.95
. We uniformly sample r to get equal-area spacing, and we use the sunflower increment to avoid awful “bars” of points in the output.
Now doing the sunflower on a sphere
The changes that we need to make to dot the sphere with points merely involve switching out the polar coordinates for spherical coordinates. The radial coordinate of course doesn't enter into this because we're on a unit sphere. To keep things a little more consistent here, even though I was trained as a physicist I'll use mathematicians' coordinates where 0 = f = p is latitude coming down from the pole and 0 = ? = 2p is longitude. So the difference from above is that we are basically replacing the variable r with f.
Our area element, which was r dr d?, now becomes the not-much-more-complicated sin(f) df d?. So our joint density for uniform spacing is sin(f)/4p. Integrating out ?, we find f(f) = sin(f)/2, thus F(f) = (1 - cos(f))/2. Inverting this we can see that a uniform random variable would look like acos(1 - 2 u), but we sample uniformly instead of randomly, so we instead use fk = acos(1 - 2 (k + 0.5)/N). And the rest of the algorithm is just projecting this onto the x, y, and z coordinates:
from numpy import pi, cos, sin, arccos, arange
import mpl_toolkits.mplot3d
import matplotlib.pyplot as pp
num_pts = 1000
indices = arange(0, num_pts, dtype=float) + 0.5
phi = arccos(1 - 2*indices/num_pts)
theta = pi * (1 + 5**0.5) * indices
x, y, z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi);
pp.figure().add_subplot(111, projection='3d').scatter(x, y, z);
pp.show()
Again for n=100 and n=1000 the results look like:
Further research
I wanted to give a shout out to Martin Roberts’s blog. Note that above I created an offset of my indices by adding 0.5 to each index. This was just visually appealing to me, but it turns out that the choice of offset matters a lot and is not constant over the interval and can mean getting as much as 8% better accuracy in packing if chosen correctly. There should also be a way to get his R2 sequence to cover a sphere and it would be interesting to see if this also produced a nice even covering, perhaps as-is but perhaps needing to be, say, taken from only a half of the unit square cut diagonally or so and stretched around to get a circle.
Notes
Those “bars” are formed by rational approximations to a number, and the best rational approximations to a number come from its continued fraction expression, z + 1/(n_1 + 1/(n_2 + 1/(n_3 + ...)))
where z
is an integer and n_1, n_2, n_3, ...
is either a finite or infinite sequence of positive integers:
def continued_fraction(r):
while r != 0:
n = floor(r)
yield n
r = 1/(r - n)
Since the fraction part 1/(...)
is always between zero and one, a large integer in the continued fraction allows for a particularly good rational approximation: “one divided by something between 100 and 101” is better than “one divided by something between 1 and 2.” The most irrational number is therefore the one which is 1 + 1/(1 + 1/(1 + ...))
and has no particularly good rational approximations; one can solve f = 1 + 1/f by multiplying through by f to get the formula for the golden ratio.
For folks who are not so familiar with NumPy -- all of the functions are “vectorized,” so that sqrt(array)
is the same as what other languages might write map(sqrt, array)
. So this is a component-by-component sqrt
application. The same also holds for division by a scalar or addition with scalars -- those apply to all components in parallel.
The proof is simple once you know that this is the result. If you ask what's the probability that z < Z < z + dz, this is the same as asking what's the probability that z < F-1(U) < z + dz, apply F to all three expressions noting that it is a monotonically increasing function, hence F(z) < U < F(z + dz), expand the right hand side out to find F(z) + f(z) dz, and since U is uniform this probability is just f(z) dz as promised.
Why am I getting tree conflicts in Subversion?
Until today, for since at least 3 months ago, I regularly encountered hundreds of tree conflicts when attempting to merge a branch back into the trunk (using TortoiseSVN 1.11). Whether rebased or not, BTW.
I've been using TortoiseSVN since its v1, back in 2004, and I used to reintegrate branches all the time. Something must have happened recently I suppose?
So today I ran this simple experiment, and I found what was creating these crazy conflicts:
- I forked off the trunk @393;
- I modified tens of files randomly, as well as creating new ones;
- I committed. Now @395 (a colleague forked off at 394 to perform his own stuff).
- Then I tried to reintegrate the branch back into the trunk, test only;
following TortoiseSVN's recommendation in the wizard: "to merge all revisions (reintegrate), leave that box empty". To achieve this, I right-clicked onto the trunk folder, and chose "TortoiseSVN > Merge, from /path/to/branch", and I left the rev range empty, as advised on the dialog.
Discussion: (see attachment)
all revisions... of what? Little did I know that the client must have been referring to "all revisions of the target! (trunk)", as, in the process of reintegrating that branch, I saw the mention "Merging revisions 1-HEAD"! OMG. Poor Devil, you're falling to your death here. That branch was born @393, can't you read its birth certificate, for God's sake?
Resolution:
- Contrarily to what's advised by the wiz, do specify a range, that covers ALL revisions of...the branch's life! therefore, 394-HEAD;
- now run that merge test again, and get a cigar. ().
Moral:
I can't comprehend why they still haven't fixed that bug, because it is one, I'm sorry.
I should take the time to report this with them.
Convert Data URI to File then append to FormData
Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
Getting "TypeError: failed to fetch" when the request hasn't actually failed
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.
To append a name/value name/value pair to a Headers object (headers), run these steps:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headers’s guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
To fill a Headers object headers with a given object object, run these steps:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
The delete(name) method steps are:
- If name is not a name, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
The get(name) method steps are:
- If name is not a name, then throw a TypeError.
- Return the result of getting name from this’s header list.
The has(name) method steps are:
- If name is not a name, then throw a TypeError.
The set(name, value) method steps are:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
To extract a body and a Content-Type
value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.
In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET
or HEAD
, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...
The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.
In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.
Webdriver Screenshot
TakeScreenShot screenshot=new TakeScreenShot();
screenshot.screenShot("screenshots//TestScreenshot//password.png");
it will work , please try.
Rendering raw html with reactjs
Here's a little less opinionated version of the RawHTML function posted before. It lets you:
- configure the tag
- optionally replace newlines to
<br />
's
- pass extra props that RawHTML will pass to the created element
- supply an empty string (
RawHTML></RawHTML>
)
Here's the component:
const RawHTML = ({ children, tag = 'div', nl2br = true, ...rest }) =>
React.createElement(tag, {
dangerouslySetInnerHTML: {
__html: nl2br
? children && children.replace(/\n/g, '<br />')
: children,
},
...rest,
});
RawHTML.propTypes = {
children: PropTypes.string,
nl2br: PropTypes.bool,
tag: PropTypes.string,
};
Usage:
<RawHTML>{'First · Second'}</RawHTML>
<RawHTML tag="h2">{'First · Second'}</RawHTML>
<RawHTML tag="h2" className="test">{'First · Second'}</RawHTML>
<RawHTML>{'first line\nsecond line'}</RawHTML>
<RawHTML nl2br={false}>{'first line\nsecond line'}</RawHTML>
<RawHTML></RawHTML>
Output:
<div>First · Second</div>
<h2>First · Second</h2>
<h2 class="test">First · Second</h2>
<div>first line<br>second line</div>
<div>first line
second line</div>
<div></div>
It will break on:
<RawHTML><h1>First · Second</h1></RawHTML>
What does the shrink-to-fit viewport meta attribute do?
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using "width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Example
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
Without shrink-to-fit specified
With shrink-to-fit=no
Detect whether Office is 32bit or 64bit via the registry
From TechNet article on 64-bit editions of Office 2010:
If you have installed Office 2010
including Microsoft Outlook 2010,
Outlook sets a registry key named
Bitness of type REG_SZ on the computer on which it is installed. The
Bitness registry key indicates whether the Outlook 2010 installation
is 32-bit or 64-bit. This may be
useful to administrators who are
interested in auditing computers to
determine the installed versions of
Office 2010 in their organization.
- Registry path: HKEY_LOCAL_MACHINE\Software\Microsoft\Office\14.0\Outlook
- if you have installed Office 2013 then use this
Registry path: HKEY_LOCAL_MACHINE\Software\Microsoft\Office\15.0\Outlook
- Registry key: Bitness
- Value: either x86 or x64
and elsewhere in the same article:
Starting with Office 2010, Outlook is
available as a 32-bit application and
a 64-bit application. The version
(bitness) of Outlook that you choose
depends on the edition of the Windows
operating system (32-bit or 64-bit)
and the edition of Office 2010 (32- or
64-bit) that is installed on the
computer, if Office is already
installed on that computer.
Factors that determine the feasibility
of installing a 32-bit or a 64-bit
version of Outlook include the
following:
- You can install 32-bit Office 2010 and 32-bit Microsoft Outlook 2010 on a supported 32-bit or 64-bit edition of the Windows operating system. You can install the 64-bit version of Office 2010 and 64-bit Outlook 2010 only on a supported 64-bit operating system.
- The default installation of Office 2010 on a 64-bit edition of the Windows operating system is 32-bit Office 2010.
- The bitness of an installed version of Outlook is always the same as the bitness of Office 2010, if Office is installed on the same computer. That is, a 32-bit version of Outlook 2010 cannot be installed on the same computer on which 64-bit versions of other Office 2010 applications are already installed, such as 64-bit Microsoft Word 2010 or 64-bit Microsoft Excel 2010. Similarly, a 64-bit version of Outlook 2010 cannot be installed on the same computer on which 32-bit versions of other Office applications are already installed.
2D arrays in Python
Please consider the follwing codes:
from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)
Dockerfile if else condition with external arguments
Exactly as others told, shell script would help.
Just an additional case, IMHO it's worth mentioning (for someone else who stumble upon here, looking for an easier case), that is Environment replacement.
Environment variables (declared with the ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile
.
The ${variable_name}
syntax also supports a few of the standard bash modifiers as specified below:
${variable:-word}
indicates that if variable
is set then the result will be that value. If variable
is not set then word
will be the result.
${variable:+word}
indicates that if variable
is set then word
will be the result, otherwise the result is the empty string.
Query based on multiple where clauses in Firebase
Using Firebase's Query API, you might be tempted to try this:
// !!! THIS WILL NOT WORK !!!
ref
.orderBy('genre')
.startAt('comedy').endAt('comedy')
.orderBy('lead') // !!! THIS LINE WILL RAISE AN ERROR !!!
.startAt('Jack Nicholson').endAt('Jack Nicholson')
.on('value', function(snapshot) {
console.log(snapshot.val());
});
But as @RobDiMarco from Firebase says in the comments:
multiple orderBy()
calls will throw an error
So my code above will not work.
I know of three approaches that will work.
1. filter most on the server, do the rest on the client
What you can do is execute one orderBy().startAt()./endAt()
on the server, pull down the remaining data and filter that in JavaScript code on your client.
ref
.orderBy('genre')
.equalTo('comedy')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
if (movie.lead == 'Jack Nicholson') {
console.log(movie);
}
});
2. add a property that combines the values that you want to filter on
If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_lead": "comedy_Jack Nicholson"
}, //...
You're essentially building your own multi-column index that way and can query it with:
ref
.orderBy('genre_lead')
.equalTo('comedy_Jack Nicholson')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
David East has written a library called QueryBase that helps with generating such properties.
You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_year": "comedy_1997"
}, //...
And then query for comedies of the 90s with:
ref
.orderBy('genre_year')
.startAt('comedy_1990')
.endAt('comedy_2000')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25"
. This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.
This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.
A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.
3. create a custom index programmatically
Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:
"movies"
// the same structure you have today
"by_genre"
"comedy"
"by_lead"
"Jack Nicholson"
"movie1"
"Jim Carrey"
"movie3"
"Horror"
"by_lead"
"Jack Nicholson"
"movie2"
There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063
If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.
Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.
ng-options with simple array init
You actually had it correct in your third attempt.
<select ng-model="myselect" ng-options="o as o for o in options"></select>
See a working example here:
http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=preview
The trick is that AngularJS writes the keys as numbers from 0 to n anyway, and translates back when updating the model.
As a result, the HTML will look incorrect but the model will still be set properly when choosing a value. (i.e. AngularJS will translate '0' back to 'var1')
The solution by Epokk also works, however if you're loading data asynchronously you might find it doesn't always update correctly. Using ngOptions will correctly refresh when the scope changes.
Swift days between two NSDates
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
Eclipse JPA Project Change Event Handler (waiting)
I still have the same issue in Neon.2
My solution is to disable the JPA Configurator.
Open the Eclipse Preferences (not the project prefs!). Go to Maven --> Java EE Integration and disable the JPA Configurator. I also disabled the JAX-RS Configurator and the JSF Configurator.
From that point on the JPA Project Change Event Handler doesn't show up anymore.
Restart Eclipse if the change does not take effect immediately.
Redirecting to a page after submitting form in HTML
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
_x000D_
_x000D_
Change color of PNG image via CSS?
You can use filters with -webkit-filter
and filter
:
Filters are relatively new to browsers but supported in over 90% of browsers according to the following CanIUse table: https://caniuse.com/#feat=css-filters
You can change an image to grayscale, sepia and lot more (look at the example).
So you can now change the color of a PNG file with filters.
_x000D_
_x000D_
body {
background-color:#03030a;
min-width: 800px;
min-height: 400px
}
img {
width:20%;
float:left;
margin:0;
}
/*Filter styles*/
.saturate { filter: saturate(3); }
.grayscale { filter: grayscale(100%); }
.contrast { filter: contrast(160%); }
.brightness { filter: brightness(0.25); }
.blur { filter: blur(3px); }
.invert { filter: invert(100%); }
.sepia { filter: sepia(100%); }
.huerotate { filter: hue-rotate(180deg); }
.rss.opacity { filter: opacity(50%); }
_x000D_
<!--- img src http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/500px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg -->
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="original">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="saturate" class="saturate">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="grayscale" class="grayscale">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="contrast" class="contrast">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="brightness" class="brightness">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="blur" class="blur">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="invert" class="invert">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="sepia" class="sepia">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="huerotate" class="huerotate">
<img alt="Mona Lisa" src="https://images.pexels.com/photos/40997/mona-lisa-leonardo-da-vinci-la-gioconda-oil-painting-40997.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" title="opacity" class="rss opacity">
_x000D_
_x000D_
_x000D_
Source
Is an empty href valid?
The current HTML5 draft also allows ommitting the href attribute completely.
If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.
To answer your question: Yes it's valid.
Are the days of passing const std::string & as a parameter over?
See “Herb Sutter "Back to the Basics! Essentials of Modern C++ Style”. Among other topics, he reviews the parameter passing advice that’s been given in the past, and new ideas that come in with C++11 and specifically looks at the idea of passing strings by value.
The benchmarks show that passing std::string
s by value, in cases where the function will copy it in anyway, can be significantly slower!
This is because you are forcing it to always make a full copy (and then move into place), while the const&
version will update the old string which may reuse the already-allocated buffer.
See his slide 27: For “set” functions, option 1 is the same as it always was. Option 2 adds an overload for rvalue reference, but this gives a combinatorial explosion if there are multiple parameters.
It is only for “sink” parameters where a string must be created (not have its existing value changed) that the pass-by-value trick is valid. That is, constructors in which the parameter directly initializes the member of the matching type.
If you want to see how deep you can go in worrying about this, watch Nicolai Josuttis’s presentation and good luck with that (“Perfect — Done!” n times after finding fault with the previous version. Ever been there?)
This is also summarized as ?F.15 in the Standard Guidelines.
What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?
FragmentStatePagerAdapter:
with FragmentStatePagerAdapter
,your unneeded fragment is
destroyed.A transaction is committed to completely remove the
fragment from your activity's FragmentManager
.
The state in FragmentStatePagerAdapter
comes from the fact that it
will save out your fragment's Bundle
from savedInstanceState
when
it is destroyed.When the user navigates back,the new fragment will be
restored using the fragment's state.
FragmentPagerAdapter:
By comparision FragmentPagerAdapter
does nothing of the kind.When
the fragment is no longer needed.FragmentPagerAdapter
calls
detach(Fragment)
on the transaction instead of remove(Fragment)
.
This destroy's the fragment's view but leaves the fragment's instance
alive in the FragmentManager
.so the fragments created in the
FragmentPagerAdapter
are never destroyed.
Wordpress - Images not showing up in the Media Library
I had a same problem just now, with missing media library images for my blog. The images appeared to be right there in the media library and were definitely on the actual web server (checked via FTP).
As Allen Z advised I did "check Settings ? Media and make sure that Uploading Files folder is set to wp-content/uploads"
Mine were set to the default blank. I altered this to an absolute path http://www.example.com/wp-content/uploads
THIS DIDNT SOLVE THE PROBLEM when I refreshed the site in browser. However, I immediately changed the path back to blank (the default setting again) and everything came back! Woop
Everyone having this problem might want to try this before getting into the more technical fixes!
Using SSIS BIDS with Visual Studio 2012 / 2013
Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.
The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843
HTML table headers always visible at top of window when viewing a large table
If you use a full screen table you are maybe interested in setting th to display:fixed; and top:0; or try a very similar approach via css.
Update
Just quickly build up a working solution with iframes (html4.0). This example IS NOT standard conform, however you will easily be able to fix it:
outer.html
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Outer</title>
<body>
<iframe src="test.html" width="200" height="100"></iframe>
</body>
</html>
test.html
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Floating</title>
<style type="text/css">
.content{
position:relative;
}
thead{
background-color:red;
position:fixed;
top:0;
}
</style>
<body>
<div class="content">
<table>
<thead>
<tr class="top"><td>Title</td></tr>
</head>
<tbody>
<tr><td>a</td></tr>
<tr><td>b</td></tr>
<tr><td>c</td></tr>
<tr><td>d</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
</tbody>
</table>
</div>
</body>
</html>
php: how to get associative array key from numeric index?
You might do it this way:
function asoccArrayValueWithNumKey(&$arr, $key) {
if (!(count($arr) > $key)) return false;
reset($array);
$aux = -1;
$found = false;
while (($auxKey = key($array)) && !$found) {
$aux++;
$found = ($aux == $key);
}
if ($found) return $array[$auxKey];
else return false;
}
$val = asoccArrayValueWithNumKey($array, 0);
$val = asoccArrayValueWithNumKey($array, 1);
etc...
Haven't tryed the code, but i'm pretty sure it will work.
Good luck!
TCP vs UDP on video stream
This is the thing, it is more a matter of content than it is a time issue. The TCP protocol requires that a packet that was not delivered must be check, verified and redelivered. UDP does not use this requirement. So if you sent a file which contains millions of packets using UDP, like a video, if some of the packets are missing upon delivery, they will most likely go unmissed.
Pure Javascript listen to input value change
Another approach in 2020 could be using document.querySelector()
:
const myInput = document.querySelector('input[name="exampleInput"]');
myInput.addEventListener("change", (e) => {
// here we do something
});
Replacing instances of a character in a string
You cannot simply assign value to a character in the string.
Use this method to replace value of a particular character:
name = "India"
result=name .replace("d",'*')
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character,
eg. string = babble output = ba**le
Code:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
MySQL Calculate Percentage
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
DEMO HERE
Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
You need to add JAX-B dependencies when using JDK 9+. For Android Studio user, you'll need to add this to your build.gradle
's dependencies {}
block:
// Add missing dependencies for JDK 9+
if (JavaVersion.current().ordinal() >= JavaVersion.VERSION_1_9.ordinal()) {
// If you're using @AutoValue or any libs that requires javax.annotation (like Dagger)
compileOnly 'com.github.pengrad:jdk9-deps:1.0'
compileOnly 'javax.annotation:javax.annotation-api:1.3.2'
// If you're using Kotlin
kapt "com.sun.xml.bind:jaxb-core:2.3.0.1"
kapt "javax.xml.bind:jaxb-api:2.3.1"
kapt "com.sun.xml.bind:jaxb-impl:2.3.2"
// If you're using Java
annotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
annotationProcessor "javax.xml.bind:jaxb-api:2.3.1"
testAnnotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
testAnnotationProcessor "javax.xml.bind:jaxb-api:2.3.1"
}
How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
When you need to create a lot of REST API endpoints on Symfony,
the best way is to use following stack of bundles:
- JMSSerializerBundle for the serialization of Doctrine entities
- FOSRestBundle bundle for response view listener. Also it can generate definition of routes based on controller/action name.
- NelmioApiDocBundle to auto-generate online documentation and Sandbox(which allows to test endpoint without any external tool).
When you configure everything properly, you entity code will look like:
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
/**
* @ORM\Table(name="company")
*/
class Company
{
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*
* @JMS\Expose()
* @JMS\SerializedName("name")
* @JMS\Groups({"company_overview"})
*/
private $name;
/**
* @var Campaign[]
*
* @ORM\OneToMany(targetEntity="Campaign", mappedBy="company")
*
* @JMS\Expose()
* @JMS\SerializedName("campaigns")
* @JMS\Groups({"campaign_overview"})
*/
private $campaigns;
}
Then, code in controller:
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\View;
class CompanyController extends Controller
{
/**
* Retrieve all companies
*
* @View(serializerGroups={"company_overview"})
* @ApiDoc()
*
* @return Company[]
*/
public function cgetAction()
{
return $this->getDoctrine()->getRepository(Company::class)->findAll();
}
}
The benefits of such set up are:
- @JMS\Expose() annotations in entity can be added to simple fields, and to any types of relations. Also there is possibility to expose result of some method execution (use annotation @JMS\VirtualProperty() for that)
- With serialization groups we can control exposed fields in different situations.
- Controllers are very simple. Action method can directly return an entity or array of entities, and they will be automatically serialized.
- And @ApiDoc() allows to test the endpoint directly from browser, without any REST client or JavaScript code
What is an optional value in Swift?
From https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html:
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
To understand deeper, read the link above.
Javascript: getFullyear() is not a function
You are overwriting the start
date object with the value
of a DOM Element with an id of Startdate
.
This should work:
var start = new Date(document.getElementById('Stardate').value);
var y = start.getFullYear();
Code coverage for Jest built on top of Jasmine
Check the latest Jest (v 0.22): https://github.com/facebook/jest
The Facebook team adds the Istanbul code coverage output as part of the coverage report and you can use it directly.
After executing Jest, you can get a coverage report in the console and under the root folder set by Jest, you will find the coverage report in JSON and HTML format.
FYI, if you install from npm, you might not get the latest version; so try the GitHub first and make sure the coverage is what you need.
How to read connection string in .NET Core?
There is another approach. In my example you see some business logic in repository class that I use with dependency injection in ASP .NET MVC Core 3.1.
And here I want to get connectiongString
for that business logic because probably another repository will have access to another database at all.
This pattern allows you in the same business logic repository have access to different databases.
C#
public interface IStatsRepository
{
IEnumerable<FederalDistrict> FederalDistricts();
}
class StatsRepository : IStatsRepository
{
private readonly DbContextOptionsBuilder<EFCoreTestContext>
optionsBuilder = new DbContextOptionsBuilder<EFCoreTestContext>();
private readonly IConfigurationRoot configurationRoot;
public StatsRepository()
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationRoot = configurationBuilder.Build();
}
public IEnumerable<FederalDistrict> FederalDistricts()
{
var conn = configurationRoot.GetConnectionString("EFCoreTestContext");
optionsBuilder.UseSqlServer(conn);
using (var ctx = new EFCoreTestContext(optionsBuilder.Options))
{
return ctx.FederalDistricts.Include(x => x.FederalSubjects).ToList();
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"EFCoreTestContext": "Data Source=DESKTOP-GNJKL2V\\MSSQLSERVER2014;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Illegal mix of collations error in MySql
Here's how to check which columns are the wrong collation:
SELECT table_schema, table_name, column_name, character_set_name, collation_name
FROM information_schema.columns
WHERE collation_name = 'latin1_general_ci'
ORDER BY table_schema, table_name,ordinal_position;
And here's the query to fix it:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin1 COLLATE 'latin1_swedish_ci';
Link
How to have Java method return generic list of any type?
private Object actuallyT;
public <T> List<T> magicalListGetter(Class<T> klazz) {
List<T> list = new ArrayList<>();
list.add(klazz.cast(actuallyT));
try {
list.add(klazz.getConstructor().newInstance()); // If default constructor
} ...
return list;
}
One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()
).
How to format column to number format in Excel sheet?
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
Serializing PHP object to JSON
edit: it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project. If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer, and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface
You would define a function, for instance named getJsonData();
, which would return either an array, stdClass
object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData());
. In essence, implement the function from 5.4, but call it by hand.
Something like this would work, as get_object_vars()
is called from inside the class, having access to private/protected variables:
function getJsonData(){
$var = get_object_vars($this);
foreach ($var as &$value) {
if (is_object($value) && method_exists($value,'getJsonData')) {
$value = $value->getJsonData();
}
}
return $var;
}
asynchronous vs non-blocking
A nonblocking call returns immediately with whatever data are available: the full number of bytes requested, fewer, or none at all.
An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.
Send data from javascript to a mysql database
The other posters are correct you cannot connect to MySQL directly from javascript.
This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
http://api.jquery.com/jQuery.ajax/
AngularJs: Reload page
window
object is made available through $window
service for easier testing and mocking, you can go with something like:
$scope.reloadPage = function(){$window.location.reload();}
And :
<a ng-click="reloadPage" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
As a side note, i don't think $route.reload() actually reloads the page, but only the route.
Java regex capturing groups indexes
For The Rest Of Us
Here is a simple and clear example of how this works
Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
String: "!* UserName10 John Smith 01123 *!"
group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):
group(3): John Smith
group(4):
group(5): 01123
As you can see, I have created FIVE groups which are each enclosed in parentheses.
I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.
Hope this makes sense.
Open Excel file for reading with VBA without display
Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.
OTHERWISE, possibly GetObject(<filename with path>)
is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.
Dim wb As Workbook
Set wb = GetObject("C:\MyData.xlsx") 'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False
If you want to read a particular sheet, need not even define a Workbook variable
Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook
jQuery DataTable overflow and text-wrapping issues
I faced the same problem of text wrapping, solved it by changing the css of table class in DT_bootstrap.css.
I introduced last two css lines table-layout and word-break.
table.table {
clear: both;
margin-bottom: 6px !important;
max-width: none !important;
table-layout: fixed;
word-break: break-all;
}
Get real path from URI, Android KitKat new storage access framework
This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
These are taken from my open source library, aFileChooser.
How to set Meld as git mergetool
meld 3.14.0
[merge]
tool = meld
[mergetool "meld"]
path = C:/Program Files (x86)/Meld/Meld.exe
cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" --diff \"$BASE\" \"$LOCAL\" \"$REMOTE\" --output \"$MERGED\"
Aggregate a dataframe on a given column and display another column
A late answer, but and approach using data.table
library(data.table)
DT <- data.table(dat)
DT[, .SD[which.max(Score),], by = Group]
Or, if it is possible to have more than one equally highest score
DT[, .SD[which(Score == max(Score)),], by = Group]
Noting that (from ?data.table
.SD
is a data.table containing the Subset of x's Data for each group, excluding the group column(s)
How to programmatically send a 404 response with Express/Node?
According to the site I'll post below, it's all how you set up your server. One example they show is this:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
and their route function:
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
This is one way.
http://www.nodebeginner.org/
From another site, they create a page and then load it. This might be more of what you're looking for.
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
http://blog.poweredbyalt.net/?p=81
How is using OnClickListener interface different via XML and Java code?
These are exactly the same. android:onClick
was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener
on the Button, which calls your DoIt
method.
Here is what using a android:onClick="DoIt"
does internally:
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoIt(v);
}
});
The only thing you trade off by using android:onClick
, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt
method.
How can I print literal curly-brace characters in a string and also use .format on it?
I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:
Lets say you want to print out a product of mulitple variables with indices such as
, which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$
The following code does the job with named fields so that for many indices it stays readable:
idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))
Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs
Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.
Why does the static
change the performance?
The line in question:
uint64_t size = atol(argv[1])<<20;
Short Answer
I would look at the assembly generated for accessing size
and see if there are extra steps of pointer indirection involved for the non-static version.
Long Answer
Since there is only one copy of the variable whether it was declared static
or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.
Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static
? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.
When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.
How do you split a list into evenly sized chunks?
At this point, I think we need the obligatory anonymous-recursive function.
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
chunks = Y(lambda f: lambda n: [n[0][:n[1]]] + f((n[0][n[1]:], n[1])) if len(n[0]) > 0 else [])
Write HTML to string
I know you asked about C#, but if you're willing to use any .Net language then I highly recommend Visual Basic for this exact problem. Visual Basic has a feature called XML Literals that will allow you to write code like this.
Module Module1
Sub Main()
Dim myTitle = "Hello HTML"
Dim myHTML = <html>
<head>
<title><%= myTitle %></title>
</head>
<body>
<h1>Welcome</h1>
<table>
<tr><th>ID</th><th>Name</th></tr>
<tr><td>1</td><td>CouldBeAVariable</td></tr>
</table>
</body>
</html>
Console.WriteLine(myHTML)
End Sub
End Module
This allows you to write straight HTML with expression holes in the old ASP style and makes your code super readable. Unfortunately this feature is not in C#, but you could write a single module in VB and add it as a reference to your C# project.
Writing in Visual Studio also allows proper indentation for most XML Literals and expression wholes. Indentation for the expression holes is better in VS2010.
Is there a pretty print for PHP?
How about a single standalone function named as debug from https://github.com/hazardland/debug.php.
Typical debug() html output looks like this:
But you can output data as a plain text with same function also (with 4 space indented tabs) like this (and even log it in file if needed):
string : "Test string"
boolean : true
integer : 17
float : 9.99
array (array)
bob : "alice"
1 : 5
2 : 1.4
object (test2)
another (test3)
string1 : "3d level"
string2 : "123"
complicated (test4)
enough : "Level 4"
How to register ASP.NET 2.0 to web server(IIS7)?
If anyone like me is still unable to register ASP.NET with IIS.
You just need to run these three commands one by one in command prompt
cd c:\windows\Microsoft.Net\Framework\v2.0.50727
after that, Run
aspnet_regiis.exe -i -enable
and Finally Reset IIS
iisreset
Hope it helps the person in need... cheers!
C-like structures in Python
Here is a solution which uses a class (never instantiated) to hold data. I like that this way involves very little typing and does not require any additional packages etc.
class myStruct:
field1 = "one"
field2 = "2"
You can add more fields later, as needed:
myStruct.field3 = 3
To get the values, the fields are accessed as usual:
>>> myStruct.field1
'one'
What's the best way to iterate an Android Cursor?
The best looking way I've found to go through a cursor is the following:
Cursor cursor;
... //fill the cursor here
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// do what you need with the cursor here
}
Don't forget to close the cursor afterwards
EDIT: The given solution is great if you ever need to iterate a cursor that you are not responsible of. A good example would be, if you are taking a cursor as argument in a method, and you need to scan the cursor for a given value, without having to worry about the cursor's current position.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
What is the difference between instanceof and Class.isAssignableFrom(...)?
Talking in terms of performance :
TL;DR
Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.
Sorted by performance:
- isInstance
- instanceof (+ 0.5%)
- isAssignableFrom (+ 2.7%)
Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.
In theory
Using a soft like bytecode viewer we can translate each operator into bytecode.
In the context of:
package foo;
public class Benchmark
{
public static final Object a = new A();
public static final Object b = new B();
...
}
JAVA:
b instanceof A;
Bytecode:
getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A
JAVA:
A.class.isInstance(b);
Bytecode:
ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);
JAVA:
A.class.isAssignableFrom(b.getClass());
Bytecode:
ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);
Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.
The benchmark
Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):
class A {}
class B extends A {}
public class Benchmark {
public static final Object a = new A();
public static final Object b = new B();
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testInstanceOf()
{
return b instanceof A;
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testIsInstance()
{
return A.class.isInstance(b);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testIsAssignableFrom()
{
return A.class.isAssignableFrom(b.getClass());
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(TestPerf2.class.getSimpleName())
.warmupIterations(20)
.measurementIterations(2000)
.forks(1)
.build();
new Runner(opt).run();
}
}
Gave the following results (score is a number of operations in a time unit, so the higher the score the better):
Benchmark Mode Cnt Score Error Units
Benchmark.testIsInstance thrpt 2000 373,061 ± 0,115 ops/us
Benchmark.testInstanceOf thrpt 2000 371,047 ± 0,131 ops/us
Benchmark.testIsAssignableFrom thrpt 2000 363,648 ± 0,289 ops/us
Warning
- the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
- the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
- it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
- in relation to the previous point,
instanceof
in the context of your code might get optimized more easily than an isInstance
for example...
To give you an example, take the following loop:
class A{}
class B extends A{}
A b = new B();
boolean execute(){
return A.class.isAssignableFrom(b.getClass());
// return A.class.isInstance(b);
// return b instanceof A;
}
// Warmup the code
for (int i = 0; i < 100; ++i)
execute();
// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
execute();
}
final long elapsed = System.nanoTime() - start;
Thanks to the JIT, the code is optimized at some point and we get:
- instanceof: 6ms
- isInstance: 12ms
- isAssignableFrom : 15ms
Note
Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details
Related questions
Get the second largest number in a list in linear time
def SecondLargest(x):
largest = max(x[0],x[1])
largest2 = min(x[0],x[1])
for item in x:
if item > largest:
largest2 = largest
largest = item
elif largest2 < item and item < largest:
largest2 = item
return largest2
SecondLargest([20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7])
Laravel assets url
You have to put all your assets in app/public
folder, and to access them from your views you can use asset()
helper method.
Ex. you can retrieve assets/images/image.png
in your view as following:
<img src="{{asset('assets/images/image.png')}}">
JSP tricks to make templating easier?
As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.
Let's take your simple example.
Put the following in WEB-INF/tags/wrapper.tag
<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
<jsp:doBody/>
</body></html>
Now in your example.jsp
page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:wrapper>
<h1>Welcome</h1>
</t:wrapper>
That does exactly what you think it does.
So, lets expand upon that to something a bit more general.
WEB-INF/tags/genericpage.tag
<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
<body>
<div id="pageheader">
<jsp:invoke fragment="header"/>
</div>
<div id="body">
<jsp:doBody/>
</div>
<div id="pagefooter">
<jsp:invoke fragment="footer"/>
</div>
</body>
</html>
To use this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:genericpage>
<jsp:attribute name="header">
<h1>Welcome</h1>
</jsp:attribute>
<jsp:attribute name="footer">
<p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
</jsp:attribute>
<jsp:body>
<p>Hi I'm the heart of the message</p>
</jsp:body>
</t:genericpage>
What does that buy you? A lot really, but it gets even better...
WEB-INF/tags/userpage.tag
<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>
<t:genericpage>
<jsp:attribute name="header">
<h1>Welcome ${userName}</h1>
</jsp:attribute>
<jsp:attribute name="footer">
<p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
</jsp:attribute>
<jsp:body>
<jsp:doBody/>
</jsp:body>
</t:genericpage>
To use this:
(assume we have a user variable in the request)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:userpage userName="${user.fullName}">
<p>
First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>
</p>
</t:userpage>
But it turns you like to use that user detail block in other places. So, we'll refactor it.
WEB-INF/tags/userdetail.tag
<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>
First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>
Now the previous example becomes:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:userpage userName="${user.fullName}">
<p>
<t:userdetail user="${user}"/>
</p>
</t:userpage>
The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.
JSP Tag Files
have pretty much usurped things like Tiles
etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).
Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes
framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:
<t:table items="${actionBean.customerList}" var="obj" css_class="display">
<t:col css_class="checkboxcol">
<s:checkbox name="customerIds" value="${obj.customerId}"
onclick="handleCheckboxRangeSelection(this, event);"/>
</t:col>
<t:col name="customerId" title="ID"/>
<t:col name="firstName" title="First Name"/>
<t:col name="lastName" title="Last Name"/>
<t:col>
<s:link href="/Customer.action" event="preEdit">
Edit
<s:param name="customer.customerId" value="${obj.customerId}"/>
<s:param name="page" value="${actionBean.page}"/>
</s:link>
</t:col>
</t:table>
Of course the tags work with the JSTL tags
(like c:if
, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.
So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.
At a higher level, you can do sophisticated things like this table tag I have here.
Roblox Admin Command Script
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Confused about __str__ on list in Python
Python has two different ways to convert an object to a string: str()
and repr()
. Printing an object uses str()
; printing a list containing an object uses str()
for the list itself, but the implementation of list.__str__()
calls repr()
for the individual items.
So you should also overwrite __repr__()
. A simple
__repr__ = __str__
at the end of the class body will do the trick.
What is the difference between a 'closure' and a 'lambda'?
This question is old and got many answers.
Now with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.
The answer in Java context (via Lambdas and closures — what’s the difference?):
"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."
Change some value inside the List<T>
I know this is an old post but, I've always used an updater extension method:
public static void Update<TSource>(this IEnumerable<TSource> outer, Action<TSource> updator)
{
foreach (var item in outer)
{
updator(item);
}
}
list.Where(w => w.Name == "height").ToList().Update(u => u.height = 30);
HTTP POST using JSON in Java
You can use the following code with Apache HTTP:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
response = client.execute(request);
Additionally you can create a json object and put in fields into the object like this
HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?
Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.
1. Windows -->Preferences-->General -->Network Connection
2. Select Active Provider : Manual
3. Proxy entries select HTTP--> Click on Edit button
4. Then add Host as a proxy IP and port left Required Authentication blank.
5. Restart eclipse
6. Now Eclipse Marketplace... working.
How to get week numbers from dates?
Using only base, I wrote the following function.
Note:
- Assumes Mon is day number 1 in the week
- First week is week 1
- Returns 0 if week is 52 from last year
Fine-tune to suit your needs.
findWeekNo <- function(myDate){
# Find out the start day of week 1; that is the date of first Mon in the year
weekday <- switch(weekdays(as.Date(paste(format(as.Date(myDate),"%Y"),"01-01", sep = "-"))),
"Monday"={1},
"Tuesday"={2},
"Wednesday"={3},
"Thursday"={4},
"Friday"={5},
"Saturday"={6},
"Sunday"={7}
)
firstMon <- ifelse(weekday==1,1, 9 - weekday )
weekNo <- floor((as.POSIXlt(myDate)$yday - (firstMon-1))/7)+1
return(weekNo)
}
findWeekNo("2017-01-15") # 2
sql try/catch rollback/commit - preventing erroneous commit after rollback
In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.
In your second example, I agree with other commenters. Using the success flag is unnecessary.
I consider the following approach to be, essentially, a light weight best practice approach.
If you want to see how it handles an exception, change the value on the second insert from 255 to 256.
CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT INTO #TEMP( ID ) VALUES ( 1 )
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO #TEMP( ID ) VALUES ( 2 )
INSERT INTO #TEMP( ID ) VALUES ( 255 )
COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE
@ErrorMessage NVARCHAR(4000),
@ErrorSeverity INT,
@ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (
@ErrorMessage,
@ErrorSeverity,
@ErrorState
);
ROLLBACK TRANSACTION
END CATCH
SET NOCOUNT ON
SELECT ID
FROM #TEMP
DROP TABLE #TEMP
BAT file to map to network drive without running as admin
@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass
net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
Plotting histograms from grouped data in a pandas DataFrame
I write this answer because I was looking for a way to plot together the histograms of different groups. What follows is not very smart, but it works fine for me. I use Numpy to compute the histogram and Bokeh for plotting. I think it is self-explanatory, but feel free to ask for clarifications and I'll be happy to add details (and write it better).
figures = {
'Transit': figure(title='Transit', x_axis_label='speed [km/h]', y_axis_label='frequency'),
'Driving': figure(title='Driving', x_axis_label='speed [km/h]', y_axis_label='frequency')
}
cols = {'Vienna': 'red', 'Turin': 'blue', 'Rome': 'Orange'}
for gr in df_trips.groupby(['locality', 'means']):
locality = gr[0][0]
means = gr[0][1]
fig = figures[means]
h, b = np.histogram(pd.DataFrame(gr[1]).speed.values)
fig.vbar(x=b[1:], top=h, width=(b[1]-b[0]), legend_label=locality, fill_color=cols[locality], alpha=0.5)
show(gridplot([
[figures['Transit']],
[figures['Driving']],
]))
Fine control over the font size in Seaborn plots for academic papers
It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:
axs.set_ylabel('mylabel',size=6)
you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.
def set_pubfig:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.
Note: If you specify these numbers, specifying font_scale
in sns.set_context
is ignored for all specified font elements, even if you set it.
How do I add a delay in a JavaScript loop?
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async
/await
/Promise()
or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert()
- or finishing the task at hand)
Using async
/await
/Promise()
:
_x000D_
_x000D_
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
_x000D_
_x000D_
_x000D_
Using a generator function:
_x000D_
_x000D_
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
_x000D_
_x000D_
_x000D_
Visual Studio: Relative Assembly References Paths
Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.
I've done this plenty of times in VS 2005 without any problems.
How to find largest objects in a SQL Server database?
I've found this query also very helpful in SqlServerCentral, here is the link to original post
Sql Server largest tables
select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case
when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count
else lob_used_page_count + row_overflow_used_page_count
end )
, index_kb=8*(sum(used_page_count)
- sum( case
when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count
else lob_used_page_count + row_overflow_used_page_count
end )
)
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by
rows desc
In my database they gave different results between this query and the 1st answer.
Hope somebody finds useful
Get next element in foreach loop
You could probably use while loop instead of foreach:
while ($current = current($array) )
{
$next = next($array);
if (false !== $next && $next == $current)
{
//do something with $current
}
}
Convert a PHP script into a stand-alone windows executable
Peachpie
http://www.peachpie.io
https://github.com/iolevel/peachpie
Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.
Phalanger
http://v4.php-compiler.net/
http://wiki.php-compiler.net/Phalanger_Wiki
https://github.com/devsense/phalanger
Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.
Bambalam
https://github.com/xZero707/Bamcompile/
Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension).
It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!
ZZEE PHPExe
http://www.zzee.com/phpexe/
ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.
phc-win
http://wiki.swiftlytilting.com/Phc-win
The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.
Requires
- php5ts.dll
- php_win32std.dll
- php_bcompiler.dll
- php-embed.ini
ExeOutput
http://www.exeoutput.com/
Commercial
WinBinder
http://winbinder.org/
WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.
PHPDesktop
https://github.com/cztomczak/phpdesktop
PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.
PHP Nightrain
https://github.com/kjellberg/nightrain
Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!
phc-win "fork"
https://github.com/RDashINC/phc-win
A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.
EDIT
Another option is to use
http://www.appcelerator.com/products/titanium-cross-platform-application-development/
an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP
TideSDK
http://www.tidesdk.org/
TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.
Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.
How to create a temporary directory/folder in Java?
This code should work reasonably well:
public static File createTempDir() {
final String baseTempPath = System.getProperty("java.io.tmpdir");
Random rand = new Random();
int randomInt = 1 + rand.nextInt();
File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
if (tempDir.exists() == false) {
tempDir.mkdir();
}
tempDir.deleteOnExit();
return tempDir;
}
Get error message if ModelState.IsValid fails?
publicIHttpActionResultPost(Productproduct) {
if (ModelState.IsValid) {
//Dosomethingwiththeproduct(notshown).
returnOk();
} else {
returnBadRequest();
}
}
OR
public HttpResponseMessage Post(Product product)
{
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
Detect Route Change with react-router
If you want to listen to the history
object globally, you'll have to create it yourself and pass it to the Router
. Then you can listen to it with its listen()
method:
// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';
// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
console.log(action, location.pathname, location.state);
});
// Pass history to Router.
<Router history={history}>
...
</Router>
Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';
Typescript: React event types
I think the simplest way is that:
type InputEvent = React.ChangeEvent<HTMLInputElement>;
type ButtonEvent = React.MouseEvent<HTMLButtonElement>;
update = (e: InputEvent): void => this.props.login[e.target.name] = e.target.value;
submit = (e: ButtonEvent): void => {
this.props.login.logIn();
e.preventDefault();
}
JQuery - File attributes
<form id = "uploadForm" name = "uploadForm" enctype="multipart/form-data">
<label for="uploadFile">Upload Your File</label>
<input type="file" name="uploadFile" id="uploadFile">
</form>
<script>
$('#uploadFile').change(function(){
var fileName = this.files[0].name;
var fileSize = this.files[0].size;
var fileType = this.files[0].type;
alert('FileName : ' + fileName + '\nFileSize : ' + fileSize + ' bytes');
});
</script>
Note:
To get the uploading file name means then use jquery val() method.
For Ex:
var fileName = $('#uploadFile').val();
I checked this above code before post, it works perfectly.!
Get Absolute URL from Relative path (refactored method)
The final version taking care of all previous complaints (ports, logical url, relative url, existing absolute url...etc.) considering the current handler is the page:
public static string ConvertToAbsoluteUrl(string url)
{
if (!IsAbsoluteUrl(url))
{
if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Handler is System.Web.UI.Page)
{
var originalUrl = HttpContext.Current.Request.Url;
return string.Format("{0}://{1}{2}{3}", originalUrl.Scheme, originalUrl.Host, !originalUrl.IsDefaultPort ? (":" + originalUrl.Port) : string.Empty, ((System.Web.UI.Page)HttpContext.Current.Handler).ResolveUrl(url));
}
throw new Exception("Invalid context!");
}
else
return url;
}
private static bool IsAbsoluteUrl(string url)
{
Uri result;
return Uri.TryCreate(url, UriKind.Absolute, out result);
}
Two divs side by side - Fluid display
_x000D_
_x000D_
#sides{_x000D_
margin:0;_x000D_
}_x000D_
#left{_x000D_
float:left;_x000D_
width:75%;_x000D_
overflow:hidden;_x000D_
}_x000D_
#right{_x000D_
float:left;_x000D_
width:25%;_x000D_
overflow:hidden;_x000D_
}
_x000D_
<h1 id="left">Left Side</h1>_x000D_
<h1 id="right">Right Side</h1>_x000D_
<!-- It Works!-->
_x000D_
_x000D_
_x000D_
Passing dynamic javascript values using Url.action()
This answer might not be 100% relevant to the question. But it does address the problem.
I found this simple way of achieving this requirement. Code goes below:
<a href="@Url.Action("Display", "Customer")?custId={{cust.Id}}"></a>
In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.
I haven't tried passing multiple variables using this method but I'm hopeful that also can be appended to the Url if required.
How to analyze a JMeter summary report?
Sample: Number of requests sent.
The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.
The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.
The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.
Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.
Min and Max are the minimum and maximum response time.
An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!
Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.
The following equation show how the standard deviation (s) is calculated:
s = 1/n * v Si=1…n (xi-µ)2
For Details, see here!!
So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.
Kb/sec: The throughput measured in Kilobytes per second.
Error % : Percent of requests with errors.
An example is always better to understand!!! I think, this article will help you.
IntelliJ - Convert a Java project/module into a Maven project/module
The easiest way is to add the project as a Maven project directly. To do this, in the project explorer on the left, right-click on the POM file for the project, towards the bottom of the context menu, you will see an option called 'Add as Maven Project', click it. This will automatically convert the project to a Maven project
Pandas: create two new columns in a dataframe with values calculated from a pre-existing column
The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *
. Also, the map
method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply
is used for.
So, if you must use the above approach, I would write it like this
df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
There's actually no reason to use zip here. You can simply do this:
df["A1"], df["A2"] = calculate(df['a'])
This second method is also much faster on larger DataFrames
df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})
DataFrame created with 300,000 rows
%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
60x faster than zip
In general, avoid using apply
Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above
%%timeit
A1, A2 = [], []
for val in df['a']:
A1.append(val**2)
A2.append(val**3)
df['A1'] = A1
df['A2'] = A2
298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:
%load_ext cython
%%cython
cpdef power(vals):
A1, A2 = [], []
cdef double val
for val in vals:
A1.append(val**2)
A2.append(val**3)
return A1, A2
%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Directly assigning without apply
You can get even greater speed improvements if you use the direct vectorized operations.
%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.
The simplest speed test with apply
The above example should clearly show how slow apply
can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply
s = pd.Series(np.random.rand(10000000))
%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Without apply is 50x faster
%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Passing struct to function
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
How to update Ruby to 1.9.x on Mac?
There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.
I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.
Reading CSV files using C#
First of all need to understand what is CSV and how to write it.
- Every next string (
/r/n
) is next "table" row.
- "Table" cells is separated by some delimiter symbol. Most often used symbols is
\t
or ,
- Every cell possibly can contain this delimiter symbol (cell must to start with quotes symbol and ends with this symbol in this case)
- Every cell possibly can contains
/r/n
sybols (cell must to start with quotes symbol and ends with this symbol in this case)
The easiest way for C#/Visual Basic to work with CSV files is to use standard Microsoft.VisualBasic
library. You just need to add needed reference, and the following string to your class:
using Microsoft.VisualBasic.FileIO;
Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.
Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
You can find my class by the following link:
https://github.com/ukushu/DataExporter
Simple example of using:
Csv csv = new Csv("\t");//delimiter symbol
csv.FileOpen("c:\\file1.csv");
var row1Cell6Value = csv.Rows[0][5];
csv.AddRow("asdf","asdffffff","5")
csv.FileSave("c:\\file2.csv");
How to clear the Entry widget after a button is pressed in Tkinter?
You shall proceed with ent.delete(0,"end")
instead of using 'END', use 'end' inside quotation.
secret = randrange(1,100)
print(secret)
def res(real, secret):
if secret==eval(real):
showinfo(message='that is right!')
real.delete(0, END)
def guess():
ge = Tk()
ge.title('guessing game')
Label(ge, text="what is your guess:").pack(side=TOP)
ent = Entry(ge)
ent.pack(side=TOP)
btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
btn.pack(side=LEFT)
ge.mainloop()
This shall solve your problem
Datatable select with multiple conditions
If you really don't want to run into lots of annoying errors (datediff and such can't be evaluated in DataTable.Select
among other things and even if you do as suggested use DataTable.AsEnumerable
you will have trouble evaluating DateTime fields) do the following:
1) Model Your Data (create a class with DataTable columns)
Example
public class Person
{
public string PersonId { get; set; }
public DateTime DateBorn { get; set; }
}
2) Add this helper class to your code
public static class Extensions
{
/// <summary>
/// Converts datatable to list<T> dynamically
/// </summary>
/// <typeparam name="T">Class name</typeparam>
/// <param name="dataTable">data table to convert</param>
/// <returns>List<T></returns>
public static List<T> ToList<T>(this DataTable dataTable) where T : new()
{
var dataList = new List<T>();
//Define what attributes to be read from the class
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
//Read Attribute Names and Types
var objFieldNames = typeof(T).GetProperties(flags).Cast<PropertyInfo>().
Select(item => new
{
Name = item.Name,
Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
}).ToList();
//Read Datatable column names and types
var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
Select(item => new {
Name = item.ColumnName,
Type = item.DataType
}).ToList();
foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var classObj = new T();
foreach (var dtField in dtlFieldNames)
{
PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);
var field = objFieldNames.Find(x => x.Name == dtField.Name);
if (field != null)
{
if (propertyInfos.PropertyType == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, ConvertToDateTime(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(int))
{
propertyInfos.SetValue
(classObj, ConvertToInt(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(long))
{
propertyInfos.SetValue
(classObj, ConvertToLong(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(decimal))
{
propertyInfos.SetValue
(classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(String))
{
if (dataRow[dtField.Name].GetType() == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, ConvertToDateString(dataRow[dtField.Name]), null);
}
else
{
propertyInfos.SetValue
(classObj, ConvertToString(dataRow[dtField.Name]), null);
}
}
}
}
dataList.Add(classObj);
}
return dataList;
}
private static string ConvertToDateString(object date)
{
if (date == null)
return string.Empty;
return HelperFunctions.ConvertDate(Convert.ToDateTime(date));
}
private static string ConvertToString(object value)
{
return Convert.ToString(HelperFunctions.ReturnEmptyIfNull(value));
}
private static int ConvertToInt(object value)
{
return Convert.ToInt32(HelperFunctions.ReturnZeroIfNull(value));
}
private static long ConvertToLong(object value)
{
return Convert.ToInt64(HelperFunctions.ReturnZeroIfNull(value));
}
private static decimal ConvertToDecimal(object value)
{
return Convert.ToDecimal(HelperFunctions.ReturnZeroIfNull(value));
}
private static DateTime ConvertToDateTime(object date)
{
return Convert.ToDateTime(HelperFunctions.ReturnDateTimeMinIfNull(date));
}
}
public static class HelperFunctions
{
public static object ReturnEmptyIfNull(this object value)
{
if (value == DBNull.Value)
return string.Empty;
if (value == null)
return string.Empty;
return value;
}
public static object ReturnZeroIfNull(this object value)
{
if (value == DBNull.Value)
return 0;
if (value == null)
return 0;
return value;
}
public static object ReturnDateTimeMinIfNull(this object value)
{
if (value == DBNull.Value)
return DateTime.MinValue;
if (value == null)
return DateTime.MinValue;
return value;
}
/// <summary>
/// Convert DateTime to string
/// </summary>
/// <param name="datetTime"></param>
/// <param name="excludeHoursAndMinutes">if true it will execlude time from datetime string. Default is false</param>
/// <returns></returns>
public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
{
if (datetTime != DateTime.MinValue)
{
if (excludeHoursAndMinutes)
return datetTime.ToString("yyyy-MM-dd");
return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
return null;
}
}
3) Easily convert your DataTable
(dt) to a List of objects with following code:
List<Person> persons = Extensions.ToList<Person>(dt);
4) have fun using Linq without the annoying row.Field<type>
bit you have to use when using AsEnumerable
Example
var personsBornOn1980 = persons.Where(x=>x.DateBorn.Year == 1980);
How to get ID of the last updated row in MySQL?
This is officially simple but remarkably counter-intuitive. If you're doing:
update users set status = 'processing' where status = 'pending'
limit 1
Change it to this:
update users set status = 'processing' where status = 'pending'
and last_insert_id(user_id)
limit 1
The addition of last_insert_id(user_id)
in the where
clause is telling MySQL to set its internal variable to the ID of the found row. When you pass a value to last_insert_id(expr)
like this, it ends up returning that value, which in the case of IDs like here is always a positive integer and therefore always evaluates to true, never interfering with the where clause. This only works if some row was actually found, so remember to check affected rows. You can then get the ID in multiple ways.
MySQL last_insert_id()
You can generate sequences without calling LAST_INSERT_ID(), but the
utility of using the function this way is that the ID value is
maintained in the server as the last automatically generated value. It
is multi-user safe because multiple clients can issue the UPDATE
statement and get their own sequence value with the SELECT statement
(or mysql_insert_id()), without affecting or being affected by other
clients that generate their own sequence values.
MySQL mysql_insert_id()
Returns the value generated for an AUTO_INCREMENT column by the
previous INSERT or UPDATE statement. Use this function after you have
performed an INSERT statement into a table that contains an
AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column
value with LAST_INSERT_ID(expr).
The reason for the differences between LAST_INSERT_ID() and
mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in
scripts while mysql_insert_id() tries to provide more exact
information about what happens to the AUTO_INCREMENT column.
PHP mysqli_insert_id()
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID()
function will also modify the value returned by the mysqli_insert_id()
function.
Putting it all together:
$affected_rows = DB::getAffectedRows("
update users set status = 'processing'
where status = 'pending' and last_insert_id(user_id)
limit 1"
);
if ($affected_rows) {
$user_id = DB::getInsertId();
}
(FYI that DB class is here.)
Node Multer unexpected field
We have to make sure the type= file with name attribute should be same
as the parameter name passed in upload.single('attr')
var multer = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
/** The original name of the uploaded file
stored in the variable "originalname". **/
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { res.render('complete'); });
src.on('error', function(err) { res.render('error'); });
});
How to find the width of a div using vanilla JavaScript?
call below method on div or body tag onclick="show(event);"
function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
java.lang.IllegalArgumentException: contains a path separator
You cannot use path with directory separators directly, but you will
have to make a file object for every directory.
NOTE: This code makes directories, yours may not need that...
File file= context.getFilesDir();
file.mkdir();
String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
file=new File(file,array[t]);
file.mkdir();
}
File f=new File(file,array[array.length-1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);
Convert PEM traditional private key to PKCS8 private key
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
Pass a PHP array to a JavaScript function
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
What's the main difference between int.Parse() and Convert.ToInt32
It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...
YOU HAVE BEEN WARNED!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
Confirmation before closing of tab/browser
If you want to ask based on condition:
var ask = true
window.onbeforeunload = function (e) {
if(!ask) return null
e = e || window.event;
//old browsers
if (e) {e.returnValue = 'Sure?';}
//safari, chrome(chrome ignores text)
return 'Sure?';
};
How to convert object array to string array in Java
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
Pass by Reference / Value in C++
I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:
struct Object {
int i;
};
void sample(Object* o) { // 1
o->i++;
}
void sample(Object const& o) { // 2
// nothing useful here :)
}
void sample(Object & o) { // 3
o.i++;
}
void sample1(Object o) { // 4
o.i++;
}
int main() {
Object obj = { 10 };
Object const obj_c = { 10 };
sample(&obj); // calls 1
sample(obj) // calls 3
sample(obj_c); // calls 2
sample1(obj); // calls 4
}
Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.
I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:
sample(&obj);
// yields a `Object*`. Passes a *pointer* to the object by value.
// The caller can change the pointer (the parameter), but that
// won't change the temporary pointer created on the call side (the argument).
sample(obj)
// passes the object by *reference*. It denotes the object itself. The callee
// has got a reference parameter.
sample(obj_c);
// also passes *by reference*. the reference parameter references the
// same object like the argument expression.
sample1(obj);
// pass by value. The parameter object denotes a different object than the
// one passed in.
I vote for the following definition:
An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.
That means that the following is pass by value:
void f1(Object const& o);
f1(Object()); // 1
void f2(int const& i);
f2(42); // 2
void f3(Object o);
f3(Object()); // 3
Object o1; f3(o1); // 4
void f4(Object *o);
Object o1; f4(&o1); // 5
1
is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2
is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3
is pass by value, because the parameter has not reference type. 4
is pass by value for the same reason. 5
is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):
void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1
void f2(Object const& op);
Object b; f2(b); // 2
struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference
git am error: "patch does not apply"
I faced same error. I reverted the commit version while creating patch. it worked as earlier patch was in reverse way.
[mrdubey@SNF]$ git log 65f1d63
commit 65f1d6396315853f2b7070e0e6d99b116ba2b018
Author: Dubey Mritunjaykumar
Date: Tue Jan 22 12:10:50 2019 +0530
commit e377ab50081e3a8515a75a3f757d7c5c98a975c6
Author: Dubey Mritunjaykumar
Date: Mon Jan 21 23:05:48 2019 +0530
Earlier commad used: git diff new_commit_id..prev_commit_id > 1 diff
Got error: patch failed: filename:40
working one: git diff prev_commit_id..latest_commit_id > 1.diff
ActionLink htmlAttributes
The problem is that your anonymous object property data-icon
has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:
Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
Use the overload that takes in a dictionary:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });
Table scroll with HTML and CSS
Table with Fixed Header
_x000D_
_x000D_
<table cellspacing="0" cellpadding="0" border="0" width="325">_x000D_
<tr>_x000D_
<td>_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr style="color:white;background-color:grey">_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="width:320px; height:80px; overflow:auto;">_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
Result
This is working in all browser
Demo jsfiddle http://jsfiddle.net/nyCKE/6302/
Can a foreign key refer to a primary key in the same table?
I think the question is a bit confusing.
If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.
If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!
create table t1(c1 int not null primary key foreign key references t1(c1))
But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.
AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.
How to convert list data into json in java
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
Difference between File.separator and slash in paths
With the Java libraries for dealing with files, you can safely use /
(slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.
You might want to use File.separator
in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.
Update: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using File.separator
because you know that will work.
What is copy-on-write?
Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.
Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy
object (the proxy) implements the copy-on-write technique by:
- having an attribute bound to an immutable
Value
object (the subject);
- translating copy requests to the creation of a new
ValueProxy
object sharing the same subject attribute as the original ValueProxy
object;
- forwarding read requests to the subject attribute;
- translating write requests to the creation of a new immutable
Value
object with the new state and the rebinding of the subject attribute to this new immutable Value
object.
import abc
class BaseValue(abc.ABC):
@abc.abstractmethod
def read(self):
raise NotImplementedError
@abc.abstractmethod
def write(self, data):
raise NotImplementedError
class Value(BaseValue):
def __init__(self, data):
self.data = data
def read(self):
return self.data
def write(self, data):
pass
class ValueProxy(BaseValue):
def __init__(self, subject):
self.subject = subject
def read(self):
return self.subject.read()
def write(self, data):
self.subject = Value(data)
def clone(self):
return ValueProxy(self.subject)
v1 = ValueProxy(Value('foo'))
v2 = v1.clone() # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar') # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject
Sorting int array in descending order
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);