Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
In fact you cannot do it easily right now (at the time I am writing this message). I will try to explain why.
First of all, the glibc is no more, it has been subsumed by the eglibc project. And, the Debian distribution switched to eglibc some time ago (see here and there and even on the glibc source package page). So, you should consider installing the eglibc package through this kind of command:
apt-get install libc6-amd64 libc6-dev libc6-dbg
Replace amd64
by the kind of architecture you want (look at the package list here).
Unfortunately, the eglibc package version is only up to 2.13 in unstable
and testing
. Only the experimental
is providing a 2.17 version of this library. So, if you really want to have it in 2.15 or more, you need to install the package from the experimental version (which is not recommended). Here are the steps to achieve as root:
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Update your package database:
apt-get update
Install the eglibc package:
apt-get -t experimental install libc6-amd64 libc6-dev libc6-dbg
Pray...
Well, that's all folks.
If you want something that closely resembles the top answer but is also synchronous then this will work.
var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";
var options = {
encoding: 'utf8'
};
console.log(execSync(cmd, options));
UTF-8 Byte Order Mark at the beginning of the document^THIS for me solved the issue. I opened the inolved file with an HEX editor and removed the BOM at the start of the file.
As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.
You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master
. To the best of my knowledge, you can control --depth
via .travis.yml
but not the --branch
. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.
Before:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
The fix:
$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch
After:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
minrk's answer is right.
However, I found that the images appeared broken in Print View (on my Windows machine running the Anaconda distribution of IPython version 0.13.2 in a Chrome browser)
The workaround for this was to use <img src="../files/image.png">
instead.
This made the image appear correctly in both Print View and the normal iPython editing view.
UPDATE: as of my upgrade to iPython v1.1.0 there is no more need for this workaround since the print view no longer exists. In fact, you must avoid this workaround since it prevents the nbconvert tool from finding the files.
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
htmlspecialchars()
is perfectly adequate for filtering user input that is displayed in html forms.
Since the encoding that turns "the Family" into "t?? T???ly" is effectively random and not following any algorithm that can be explained by the information of the Unicode codepoints involved, there's no general way to solve this algorithmically.
You will need to build the mapping of Unicode characters into latin characters which they resemble. You could probably do this with some smart machine learning on the actual glyphs representing the Unicode codepoints. But I think the effort for this would be greater than manually building that mapping. Especially if you have a good amount of examples from which you can build your mapping.
To clarify: a few of the substitutions can actually be solved via the Unicode data (as the other answers demonstrate), but some letters simply have no reasonable association with the latin characters which they resemble.
Examples:
You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap
object you have.
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)
For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under()
and cmap.set_over()
.
For "special" numbers such as np.nan
and np.inf
the default is to use the 0.0 value, this can be changed using cmap.set_bad()
similarly to under and over as above.
Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]
. This can be done using matplotlib.colors.Normalize
simply as shown in the small example below where the arguments vmin
and vmax
describe what numbers should be mapped to 0.0 and 1.0 respectively.
import matplotlib
norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)
print(norm(15.0)) # 0.5
A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.
(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
Using iText (existing PDF in bytes)
public static byte[] mergePDF(List<byte[]> pdfFilesAsByteArray) throws DocumentException, IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
for (byte[] pdfByteArray : pdfFilesAsByteArray) {
try {
PdfReader reader = new PdfReader(pdfByteArray);
int numberOfPages = reader.getNumberOfPages();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document, outStream); // new
document.open();
}
PdfImportedPage page;
for (int i = 0; i < numberOfPages;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
document.close();
outStream.close();
return outStream.toByteArray();
}
This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri
as obsolete.
Anyway, probably a better way to manipulate relative Uri
s is to give it what it wants:
var requestUri = new Uri("x://x").MakeRelativeUri(
new UriBuilder("x://x") { Path = path, Query = query }.Uri);
You can use the other answers to actually build the query string.
If you're using zsh, you can use multiple redirections, so you don't even need tee
:
./cmd 1>&1 2>&2 1>out_file 2>err_file
Here you're simply redirecting each stream to itself and the target file.
Full example
% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err
Note that this requires the MULTIOS
option to be set (which is the default).
MULTIOS
Perform implicit
tee
s orcat
s when multiple redirections are attempted (see Redirection).
For those having the percentages in a pandas Series, here is my implemantation of the Largest remainder method (as in Varun Vohra's answer), where you can even select the decimals to which you want to round.
import numpy as np
def largestRemainderMethod(pd_series, decimals=1):
floor_series = ((10**decimals * pd_series).astype(np.int)).apply(np.floor)
diff = 100 * (10**decimals) - floor_series.sum().astype(np.int)
series_decimals = pd_series - floor_series / (10**decimals)
series_sorted_by_decimals = series_decimals.sort_values(ascending=False)
for i in range(0, len(series_sorted_by_decimals)):
if i < diff:
series_sorted_by_decimals.iloc[[i]] = 1
else:
series_sorted_by_decimals.iloc[[i]] = 0
out_series = ((floor_series + series_sorted_by_decimals) / (10**decimals)).sort_values(ascending=False)
return out_series
Another possibility is to use an absolute positioning oriented to the right. You can do it this way:
style="position: absolute; right: 0;"
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
Or
$dataProvider->setSort([
'defaultOrder' => ['topic_order'=>SORT_DESC],
'attributes' => [...
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.
Number of levels recorded for each setting level:
ALL DEBUG INFO WARN ERROR FATAL OFF
•All
•DEBUG •DEBUG
•INFO •INFO •INFO
•WARN •WARN •WARN •WARN
•ERROR •ERROR •ERROR •ERROR •ERROR
•FATAL •FATAL •FATAL •FATAL •FATAL •FATAL
•OFF •OFF •OFF •OFF •OFF •OFF •OFF
In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:
$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")
Clarification: small files only folks! Please don't try this on your 40 GB log file :)
The server might require some kind of encryption and secure authentication.
see http://swiftmailer.org/docs/sending.html#encrypted-smtp
As slight improvement to @MONTYHS answer, iterating through a tup of fieldnames:
import csv
import json
csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)
fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')
output = []
for each in reader:
row = {}
for field in fieldnames:
row[field] = each[field]
output.append(row)
json.dump(output, jsonfile, indent=2, sort_keys=True)
if you are able to access node on ubuntu terminal using nodejs command,then this problem can be simply solved using -creating a symbolic link of nodejs and node using
ln -s /usr/bin/nodejs /usr/bin/node
and this may solve the problem
I think the $(window).load
event is not supported by JQuery 3.x
Update: 5/5/2015 For your MVC 5 project you need to set the Version to 5.0.0.0 in your /views/web.config
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</system.web.webPages.razor>
Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
Your Button2Click
and Button3Click
functions pass klad.xls
and smimime.txt
. These files most likely aren't actual executables indeed.
In order to open arbitrary files using the application associated with them, use ShellExecute
Note that tr
can only handle plain ASCII, making any tr
-based solution fail when facing international characters.
Same goes for the bash 4 based ${x,,}
solution.
The awk
tool, on the other hand, properly supports even UTF-8 / multibyte input.
y="HELLO"
val=$(echo "$y" | awk '{print tolower($0)}')
string="$val world"
Answer courtesy of liborw.
There are two cases you deal with when working with images in Android:
- You want to load an image for your device density and you are going to use it “as is”, without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.
- You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image’s size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up.
SO
Thus, the rule of thumb to decide where to put your image into would be:
Launcher icons always go into mipmap folder.
Images, which are often scaled up (or extremely scaled down) and whose quality is critical for the app, go into mipmap folder as well.
All other images are usual drawables.
Citation from this article.
Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).
If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.
for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.
You can do
[n.name for n in tf.get_default_graph().as_graph_def().node]
Also, if you are prototyping in an IPython notebook, you can show the graph directly in notebook, see show_graph
function in Alexander's Deep Dream notebook
Graphviz is evidently included in Anaconda so as to be used with pydot or pydot-ng (both of which are included in Anaconda). You may want to consider using one of those instead of the 'graphviz' Python module.
I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager
interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static ConfigurationSection GetSection( string name )
{
return ConfigurationManager.GetSection( name );
}
.....
public static ConfigurationSection GetWidgetSection()
{
return GetSection( "widgets" );
}
}
The VOLUME
command in a Dockerfile
is quite legit, totally conventional, absolutely fine to use and it is not deprecated in anyway. Just need to understand it.
We use it to point to any directories which the app in the container will write to a lot. We don't use VOLUME
just because we want to share between host and container like a config file.
The command simply needs one param; a path to a folder, relative to WORKDIR
if set, from within the container. Then docker will create a volume in its graph(/var/lib/docker) and mount it to the folder in the container. Now the container will have somewhere to write to with high performance. Without the VOLUME
command the write speed to the specified folder will be very slow because now the container is using it's copy on write
strategy in the container itself. The copy on write
strategy is a main reason why volumes exist.
If you mount over the folder specified by the VOLUME
command, the command is never run because VOLUME
is only executed when the container starts, kind of like ENV
.
Basically with VOLUME
command you get performance without externally mounting any volumes. Data will save across container runs too without any external mounts. Then when ready simply mount something over it.
Some good example use cases:
- logs
- temp folders
Some bad use cases:
- static files
- configs
- code
Fork Vs. Clone - two words that both mean copy
Please see this diagram. (Originally from http://www.dataschool.io/content/images/2014/Mar/github1.png).
.-------------------------. 1. Fork .-------------------------.
| Your GitHub repo | <-------------- | Joe's GitHub repo |
| github.com/you/coolgame | | github.com/joe/coolgame |
| ----------------------- | 7. Pull Request | ----------------------- |
| master -> c224ff7 | --------------> | master -> c224ff7 (c) |
| anidea -> 884faa1 (a) | | anidea -> 884faa1 (b) |
'-------------------------' '-------------------------'
| ^
| 2. Clone |
| |
| |
| |
| |
| | 6. Push (anidea => origin/anidea)
v |
.-------------------------.
| Your computer | 3. Create branch 'anidea'
| $HOME/coolgame |
| ----------------------- | 4. Update a file
| master -> c224ff7 |
| anidea -> 884faa1 | 5. Commit (to 'anidea')
'-------------------------'
(a) - after you have pushed it
(b) - after Joe has accepted it
(c) - eventually Joe might merge 'anidea' (make 'master -> 884faa1')
Fork
Clone
Its nothing more easy.
run command: ./gradlew clean -PjobId=9999
and
in gradle use: println(project.gradle.startParameter.projectProperties)
You will get clue.
After much research and testing this seems to work
function getPosition(e) {
var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
var x = 0, y = 0;
while (e) {
x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
e = e.offsetParent;
}
return { x: x + window.scrollX, y: y + window.scrollY };
}
In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example,
object.__getattribute__(self, name)
.
Meaning:
def __getattribute__(self,name):
...
return self.__dict__[name]
You're calling for an attribute called __dict__
. Because it's an attribute, __getattribute__
gets called in search for __dict__
which calls __getattribute__
which calls ... yada yada yada
return object.__getattribute__(self, name)
Using the base classes __getattribute__
helps finding the real attribute.
Assuming the changes you want are at the head of the branch you want the changes from, use git checkout
for a single file :
git checkout branch_that_has_the_changes_you_want path/to/file.rb
for multiple files just daisy chain :
git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb
Here is a more general solution:
int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
for(int j = 0; j < increment; j++)
{
if(i+j < theData.Length) {
//theData[i + j] for the current index
}
}
}
If you are using maven, define your profiles as shown below within your pom.xml
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>prod</id>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
</profile>
By default, i.e if No profile is selected, the local profile will always be use.
To select a specific profile in Spring Boot 2.x.x, use the below command.
mvn spring-boot:run -Dspring-boot.run.profiles=dev
If you want want to build/compile using properties of a specific profile, use the below command.
mvn clean install -Pdev -DprofileIdEnabled=true
DECLARE @first AS INT = 1
DECLARE @last AS INT = 300
WHILE(@first <= @last)
BEGIN
INSERT INTO tblFoo VALUES(@first)
SET @first += 1
END
I had a similar problem now were I was using a bash script to dump some data. I ended up creating a symbolic link in the script folder with out any spaces in it. I then pointed my script to the symbolic link and that works fine.
To create your link. ln -s [TARGET DIRECTORY OR FILE] ./[SHORTCUT]
Mau or may not be of use.
This what worked for me
byte[] bytes = Convert.FromBase64String(textString);
And in reverse:
string str = Convert.ToBase64String(bytes);
I find Jack Aidley's suggested answer a useful one.
I wanted to throw out another option. Suppose you have a series with many small numbers, and you want to ensure the axis labels write out the full decimal point (e.g. 5e-05 -> 0.0005), then:
NotFancy <- function(l) {
l <- format(l, scientific = FALSE)
parse(text=l)
}
ggplot(data = data.frame(x = 1:100,
y = seq(from=0.00005,to = 0.0000000000001,length.out=100) + runif(n=100,-0.0000005,0.0000005)),
aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=NotFancy)
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Try this:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
Use the pause command and enter the number of milliseconds in the Target field.
Set speed to fastest (Actions --> Fastest), otherwise it won't work.
The only issue with promises is that IE doesn't support them. Edge does, but there's plenty of IE 10 and 11 out there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise (compatibility at the bottom)
So, JavaScript is single-threaded. If you're not making an asynchronous call, it will behave predictably. The main JavaScript thread will execute one function completely before executing the next one, in the order they appear in the code. Guaranteeing order for synchronous functions is trivial - each function will execute completely in the order it was called.
Think of the synchronous function as an atomic unit of work. The main JavaScript thread will execute it fully, in the order the statements appear in the code.
But, throw in the asynchronous call, as in the following situation:
showLoadingDiv(); // function 1
makeAjaxCall(); // function 2 - contains async ajax call
hideLoadingDiv(); // function 3
This doesn't do what you want. It instantaneously executes function 1, function 2, and function 3. Loading div flashes and it's gone, while the ajax call is not nearly complete, even though makeAjaxCall()
has returned. THE COMPLICATION is that makeAjaxCall()
has broken its work up into chunks which are advanced little by little by each spin of the main JavaScript thread - it's behaving asychronously. But that same main thread, during one spin/run, executed the synchronous portions quickly and predictably.
So, the way I handled it: Like I said the function is the atomic unit of work. I combined the code of function 1 and 2 - I put the code of function 1 in function 2, before the asynch call. I got rid of function 1. Everything up to and including the asynchronous call executes predictably, in order.
THEN, when the asynchronous call completes, after several spins of the main JavaScript thread, have it call function 3. This guarantees the order. For example, with ajax, the onreadystatechange event handler is called multiple times. When it reports it's completed, then call the final function you want.
I agree it's messier. I like having code be symmetric, I like having functions do one thing (or close to it), and I don't like having the ajax call in any way be responsible for the display (creating a dependency on the caller). BUT, with an asynchronous call embedded in a synchronous function, compromises have to be made in order to guarantee order of execution. And I have to code for IE 10 so no promises.
Summary: For synchronous calls, guaranteeing order is trivial. Each function executes fully in the order it was called. For a function with an asynchronous call, the only way to guarantee order is to monitor when the async call completes, and call the third function when that state is detected.
For a discussion of JavaScript threads, see: https://medium.com/@francesco_rizzi/javascript-main-thread-dissected-43c85fce7e23 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
Also, another similar, highly rated question on this subject: How should I call 3 functions in order to execute them one after the other?
@aisbaa's answer works if you don't care when the environment variable was declared. If you want the environment variable, even if it has been declared inside of an exec /bin/bash
session, use something like:
IFS="=" read -a out <<< $(docker exec container /bin/bash -c "env | grep ENV_VAR" 2>&1)
It's not very pretty, but it gets the job done.
To then get the value, use:
echo ${out[1]}
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
Generally it is that you are inserting a value that is greater than the maximum allowed value. Ex, data column can only hold up to 200 characters, but you are inserting 201-character string
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
You can download in the current directory with a .
:
cd # by default, goes to $HOME
scp me@host:/path/to/file .
or in you HOME
directly with :
scp me@host:/path/to/file ~
Sorry, this is Python instead of C#, but at least the results are correct:
def ColIdxToXlName(idx):
if idx < 1:
raise ValueError("Index is too small")
result = ""
while True:
if idx > 26:
idx, r = divmod(idx - 1, 26)
result = chr(r + ord('A')) + result
else:
return chr(idx + ord('A') - 1) + result
for i in xrange(1, 1024):
print "%4d : %s" % (i, ColIdxToXlName(i))
Assembly code is discussed here.
"An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture."
Machine code is discussed here.
"Machine code or machine language is a system of instructions and data executed directly by a computer's central processing unit."
Basically, assembler code is the language and it is translated to object code (the native code that the CPU runs) by an assembler (analogous to a compiler).
Like so:
def find_and_replace(file, word, replacement):
with open(file, 'r+') as f:
text = f.read()
f.write(text.replace(word, replacement))
Since you mentioned that you're working on a NFS system, do you have access to those semaphores and shared memory? I think you misunderstood what they are, they are an API code that enables processes to communicate with each other, semaphores are a solution for preventing race conditions and for threads to communicate with each other, in simple answer, they do not leave any residue on any filesystem.
Unless you are using an socket or a pipe? Do you have the necessary permissions to remove them, why are they on an NFS system?
Hope this helps, Best regards, Tom.
As another option it is worth looking at react scroll component.
There is not currently any way to style HTML5 <audio>
players using CSS. Instead, you can leave off the control
attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.
Calling savefig before show() worked for me.
fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')
plt.savefig('figure.png')
plt.show()
You can use parentheses to override rules of precedence.
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.
What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.
jQuery("[name='test']")
Although you should avoid it and if possible select by ID (e.g. #myId
) as this has better performance because it invokes the native getElementById
.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
<script>
$(document).ready(function(){
$(window).on('resize', function() {
jQuery("#grid").setGridWidth($('#fill').width(), false);
jQuery("#grid").setGridHeight($('#fill').height(),true);
}).trigger('resize');
});
</script>
import java.sql.*;
class Time3 {
public static void main(String args[]){
String time1 = "01:03:23";
String time2 = "02:32:00";
long difference ;
Time t1 = Time.valueOf(time1);
Time t2 = Time.valueOf(time2);
if(t2.getTime() >= t1.getTime()){
difference = t2.getTime() - t1.getTime() -19800000;
}
else{
difference = t1.getTime() - t2.getTime() -19800000;
}
java.sql.Time time = new java.sql.Time(difference);
System.out.println(time);
}
}
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
String[] mString = new String[] {"B", "D", "F"};
for (int j = 0; j < mString.length-1; j++) {
List_Of_Array.remove(mString[j]);
}
You can set backupdir and directory to null in order to completely disable your swap files, but it is generally recommended to simply put them in a centralized directory. Vim takes care of making sure that there aren't name collissions or anything like that; so, this is a completely safe alternative:
set backupdir=~/.vim/backup/
set directory=~/.vim/backup/
Use the Make shell
builtin like in MY_VAR=$(shell echo whatever)
me@Zack:~$make
MY_VAR IS whatever
me@Zack:~$ cat Makefile
MY_VAR := $(shell echo whatever)
all:
@echo MY_VAR IS $(MY_VAR)
Why nobody wrote this simple way of converting JSON string in List ?
List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));
SET
SET @var_name = value
OR
SET @var := value
both operators = and := are accepted
SELECT
SELECT col1, @var_name := col2 from tb_name WHERE "conditon";
if multiple record sets found only the last value in col2 is keep (override);
SELECT col1, col2 INTO @var_name, col3 FROM .....
in this case the result of select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( @NR, 0 ) + 1;
...
I discovered that SequenceEqual
is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).
I wanted to test this myself so I created two methods:
/// <summary>
/// Compares two string lists using LINQ's SequenceEqual.
/// </summary>
public bool CompareLists1(List<string> list1, List<string> list2)
{
return list1.SequenceEqual(list2);
}
/// <summary>
/// Compares two string lists using a loop.
/// </summary>
public bool CompareLists2(List<string> list1, List<string> list2)
{
if (list1.Count != list2.Count)
return false;
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] != list2[i])
return false;
}
return true;
}
The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)
As it turns out, with two lists containing 32k strings, over 100 executions:
I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.
Edit:
I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):
Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
Below is the code using lambdas
#include "stdafx.h"
#include <vector>
#include <algorithm>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};
int main()
{
std::vector < MyStruct > vec;
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
std::sort(vec.begin(), vec.end(),
[] (const MyStruct& struct1, const MyStruct& struct2)
{
return (struct1.key < struct2.key);
}
);
return 0;
}
Screen Size Class
-
Hidden on all .d-none
Hidden only on xs .d-none .d-sm-block
Hidden only on sm .d-sm-none .d-md-block
Hidden only on md .d-md-none .d-lg-block
Hidden only on lg .d-lg-none .d-xl-block
Hidden only on xl .d-xl-none
Visible on all .d-block
Visible only on xs .d-block .d-sm-none
Visible only on sm .d-none .d-sm-block .d-md-none
Visible only on md .d-none .d-md-block .d-lg-none
Visible only on lg .d-none .d-lg-block .d-xl-none
Visible only on xl .d-none .d-xl-block
Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements
I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection
EDIT:
@InjectionMap
private Map<String, Object> injectionMap = new HashMap<>();
@BeforeEach
public void beforeEach() throws Exception {
injectionMap.put("securityEnabled", Boolean.TRUE);
}
@AfterEach
public void afterEach() throws Exception {
injectionMap.clear();
}
You can just do:
git checkout --orphan assets
cp /where/image/currently/located/on/machine/diagram.png .
git add .
git commit -m 'Added diagram'
git push -u origin assets
Then you can just reference it in the README
file like so:
![diagram](diagram.png)
date --date="2:00:01 PM" +%T
14:00:01
date --date="2:00 PM" +%T | cut -d':' -f1-2
14:00
var="2:00:02 PM"
date --date="$var" +%T
14:00:02
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).
Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.
Now write down the new SA password.
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
Are you dealing with outsourced code that would use floats for things named sectionID and currentSectionID? Just curious.
@Bill K: "The binary representation of a float is kind of annoying." How so? How would you do it better? There are certain numbers that cannot be represented in any base properly, because they never end. Pi is a good example. You can only approximate it. If you have a better solution, contact Intel.
An easy alternative that works for me is to insert the svg code into a div. This simple example uses javascript to manipulate the div innerHTML.
svg = '<svg height=150>';
svg+= '<rect height=100% fill=green /><circle cx=150 cy=75 r=60 fill=yellow />';
svg+= '<text x=150 y=95 font-size=60 text-anchor=middle fill=red>IIIIIII</text></svg>';
document.all.d1.innerHTML=svg;
_x000D_
<div id='d1' style="float:right;"></div><hr>
_x000D_
The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).
The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK
A bit more information from the extract about them:
Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.
Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.
Ripple event for android Cardview
control:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp" />
If you have a view with no background this line will help you
android:outlineProvider="bounds"
If you have a view with background this line will help you
android:outlineProvider="paddedBounds"
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
Mark Russinovich wrote a terrific tool called AccessChk that lets you get this information from the command line. No installation is necessary.
http://technet.microsoft.com/en-us/sysinternals/bb664922.aspx
For example:
accesschk.exe /accepteula -q -a SeServiceLogonRight
Returns this for me:
IIS APPPOOL\DefaultAppPool
IIS APPPOOL\Classic .NET AppPool
NT SERVICE\ALL SERVICES
By contrast, whoami /priv
and whoami /all
were missing some entries for me, like SeServiceLogonRight
.
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.
https://github.com/nathco/jQuery.scrollSpeed
Here's a Demo
My experience with windows client and linux/mysql server:
When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.
Assuming mysql is already up and running and the databases to be accessed are up and functional:
• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.
a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “
i. “PE d” it is 64.
ii. “PE L” it is 32.
b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.
• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.
a. Driver name = mysql-connector-java-x.x.xx
b. Copy it into someplace related to your sqldeveloper directory.
c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)
• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for
bind-address = 127.0.0.1 (this linux localhost)
and change to
bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)
• Enter to linux mysql and grant needed access for example
# mysql –u root -p
GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';
flush privileges;
restart mysql - sudo /etc/init.d/mysql restart
• Start sqldev and create a new connection
a. user = root
b. pass = (your mysql pass)
c. Choose MySql tab
i. Hostname = the linux IP hostname
ii. Port = 3306 (default for mysql)
iii. Choose Database = (from pull down the mysql database you want to use)
iv. save and connect
That is all I had to do in my case.
Thank you,
Ale
I used Dapper to bypass this constraint of Entity framework Core.
IDbConnection.Query
is working with either sql query or stored procedure with multiple parameters. By the way it's a bit faster (see benchmark tests )
Dapper is easy to learn. It took 15 minutes to write and run stored procedure with parameters. Anyway you may use both EF and Dapper. Below is an example:
public class PodborsByParametersService
{
string _connectionString = null;
public PodborsByParametersService(string connStr)
{
this._connectionString = connStr;
}
public IList<TyreSearchResult> GetTyres(TyresPodborView pb,bool isPartner,string partnerId ,int pointId)
{
string sqltext "spGetTyresPartnerToClient";
var p = new DynamicParameters();
p.Add("@PartnerID", partnerId);
p.Add("@PartnerPointID", pointId);
using (IDbConnection db = new SqlConnection(_connectionString))
{
return db.Query<TyreSearchResult>(sqltext, p,null,true,null,CommandType.StoredProcedure).ToList();
}
}
}
There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.
The window.returnValue property does not work directly when you are opening a window using window.open() while it does work when you are using window.showModalDialog()
So in your case you have two options to achieve what you are trying to do.
Option 1 - Using window.showModalDialog()
In your parent page
var answer = window.showModalDialog(<your page and other arguments>)
if (answer == 1)
{ do some thing with answer }
and inside your child page you can make use of the window.returnValue directly like
window.returnValue = 'value that you want to return';
showModalDialog halts the executions of the JavaScript until the dialog box is closed and can get a return value from the opened dialog box when its closing.But the problem with showModalDialog is that it is not supported on many modern browsers. In contrast window.open just opens a window asynchronously (User can access both the parent window and the opened window). And the JavaScript execution will continue immediately. Which bring us to Option 2
Option 2 - Using window.open() In your parent page write a function that deals with opening of your dialog.
function openDialog(url, width, height, callback){
if(window.showModalDialog){
options = 'dialogHeight: '+ height + '; dialogWidth: '+ width + '; scroll=no'
var returnValue = window.showModalDialog(url,this,options);
callback(returnValue)
}
else {
options ='toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=yes, scrollbars=no, width=' + width + ', height=' + height;
var childWindow = window.open(url,"",options);
$(childWindow).on('unload',function(){
if (childWindow.isOpened == null) {
childWindow.isOpened = 1;
}
else {
if(callback){
callback(childWindow.returnValue);
}
}
});
}
}
And whenever you want to use open a dialog. Write a callback that deals with the return value and pass it as a parameter to openDialog function
function callback(returnValue){
if(returnValue){
do something nice with the returnValue
}}
And when calling the function
openDialog(<your page>, 'width px', 'height px', callbak);
Check out an article on how to replace window.showModalDialog with window.open
To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).
You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:
On the machine with Mosquitto Server running,
On the outside-word machine with mqtt-spy running,
I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really.
And also to my knowledge to run the mosquitto_sub
and mosquitto_pub
you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,
sudo apt-get install mosquitto-clients
I tried the approach mentioned by Onkaar Singh,
But the problem is it didn't work for the Apis which requires authorisation.
This was my curl request:
curl -v -H "Accept: application/json" -H "Content-type:
application/json" -X POST -d '
{"customer_id":"812122", "event":"add_to_cart", "email": "[email protected]", }'
-u 9f4d7f5445e7: https://api.myapp.com/api/event
After importing the body got imported correctly, the headers and the Url also got imported. Only the api key 9f4d7f5445e7 which is
-u 9f4d7f5445e7: https://api.myapp.com/api/v1/event
in the curl request did not import.
The way I solved it is, -u is basically used for Authorization. So while using it in Postman, you have to take the API key (which is 9f4d7f5445e7
in this case) and do Base64 Encode. Once encoded it will return the value OWY0ZDdmNTQ0NWU3
. Then add a new header, the key name would be Authorization
and key value would be Basic OWY0ZDdmNTQ0NWU3
. After making that changes, the request worked for me.
There are online Base64 Encoders available, the one I used is http://www.url-encode-decode.com/base64-encode-decode/
Hope it helps!!!
I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.
netstat -ano
There will be plenty of processes using various ports. So to get only port we need use findstr
like below (here I use port 80)
netstat -ano | findstr 80
this will gave you result like this
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 7964
Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill
command for that.
taskkill /PID 7964 /F
Run your server again. This time it will be able to run. This can uses for Mysql server too.
The easiest way would probably be to put your web resources into the assets folder then call:
webView.loadUrl("file:///android_asset/filename.html");
For Complete Communication between Java and Webview See This
Update: The assets folder is usually the following folder:
<project>/src/main/assets
This can be changed in the asset folder configuration setting in your <app>.iml
file as:
<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” />
See Article Where to place the assets folder in Android Studio
I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).
I needed to assess if a field (field type varchar(1)) was null.
This statement worked for my scenario:
SELECT * FROM [table name] WHERE [field name] = ''
Just target font-awesome predefined class name
in ex:
HTML
<i class="fa fa-facebook"></i>
CSS
i.fa {
color: red;
font-size: 30px;
}
This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.
def some_func(a_char, a_float, a_something):
print a_char
params = ['a', 3.4, None]
some_func(*params)
>> a
Those of you looking for a short command to switch off all ticks and labels should be fine with
plt.tick_params(top=False, bottom=False, left=False, right=False,
labelleft=False, labelbottom=False)
which allows type bool
for respective parameters since version matplotlib>=2.1.1
For custom tick settings, the docs are helpful:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html
The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away.
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
@Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
@Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
@Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
When a method only takes a reference type as a parameter (say a generic method constrained to be a class via the new
constraint), you will not be able to pass a reference type to it and have to box it.
This is also true for any methods that take object
as a parameter - this will have to be a reference type.
I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
If you are only checking for whitespace and don't care about null then you can use org.apache.commons.lang.StringUtils.isWhitespace(String str),
StringUtils.isWhitespace(String str);
(Checks if the String contains only whitespace.)
If you also want to check for null(including whitespace) then
StringUtils.isBlank(String str);
this states that Account.deposit(Double.MAX_VALUE);
it is setting deposit value to MAX value of Double
dataType.to procced for running tests.
In your storyboard you should set the 'Identifier' of your prototype cell to be the same as your CellReuseIdentifier "Cell". Then you won't get that message or need to call that registerClass: function.
multi-disciplinary
will not be hyphenated, as explained by kennytm. But multi-\-disciplinary
has the same hyphenation opportunities that multidisciplinary
has.
I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):
The command
\-
inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.
Use the Filter() method as shown here - https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filter-function
In reactjs, you can disable the resize widget using style props.
<textarea id={"multiline-id"} ref={'my-ref'} style={{resize: "none"}} className="text-area-additional-styles" />
This converts all text in columns of an Excel Workbook to numbers.
Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range
'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub
I was getting Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
This worked for me on windows 8.1 64 bit using wampserver 3.0.6 64bit.
Edited my.ini file from C:\wamp64\bin\mysql\mysql5.7.14
Delete entry secure_file_priv c:\wamp64\tmp\ (or whatever dir you have here)
Stopped everything -exit wamp etc.- and restarted everything; then punt my cvs file on C:\wamp64\bin\mysql\mysql5.7.14\data\u242349266_recur (the last dir being my database name)
executed LOAD DATA INFILE 'myfile.csv'
INTO TABLE alumnos
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
... and VOILA!!!
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
What worked for me is inserting a column before the first column and deleting it immediately. Basically, do a change that will affect all the cells in the worksheet that will trigger recalculation.
From the jQuery.each() documentation:
.each( function(index, Element) )
function(index, Element)A function to execute for each matched element.
So you'll want to use:
$('#list option').each(function(i,e){
//do stuff
});
...where index will be the index and element will be the option element in list
I use:
rails db:drop
to delete the databases.rails db:create
to create the databases based on config/database.yml
The previous commands may be replaced with rails db:reset
.
Don't forget to run rails db:migrate
to run the migrations.
I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy
And sending just some "ping" message from server to client every x second resolved problem
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function var isset = function(variable){ return typeof(variable) !== "undefined" && variable !== null && variable !== ''; }
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined"
checks if the variable is defined at allvariable !== null
checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)variable !== ''
checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use caseHope this helps someone :)
As in this forum post by Gonzalo Medina, a third way may be:
\documentclass{article}
\usepackage{caption}
\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}
\begin{document}
Some text
\begin{equ}[!ht]
\begin{equation}
a=b+c
\end{equation}
\caption{Caption of the equation}
\end{equ}
Some other text
\end{document}
More details of the commands used from package caption
: here.
A screenshot of the output of the above code:
I struggled with the same problem for a while just now (using Mac). Here is what I did and it finally worked:
(1) Confirm the .ssh directory exists:
#show all files including hidden
ls -a
(2) Accept all default values by just pressing enter at the prompt
Enter file in which to save the key (/Users/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
You should get a message :
Your identification has been saved in /Users/username/.ssh/id_rsa.
Your public key has been saved in /Users/username/.ssh/id_rsa.pub.
The key fingerprint is:
BZA156:HVhsjsdhfdkjfdfhdX+BundfOytLezXvbx831/s [email protected]
The key's randomart image is:XXXXX
PS If you are configuring git for rails, do the following (source):
git config --global color.ui true
git config --global user.name "yourusername"
git config --global user.email "[email protected]"
ssh-keygen -t rsa -C "[email protected]"
(then accept all defaults by pressing enter)
I would avoid now using /// <reference path='moo.ts'/>
but for external libraries where the definition file is not included into the package.
The reference path
solves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -out
to one file.
From Typescript 1.5
Just prefix what you want to export at the file level (root scope)
aLib.ts
{
export class AClass(){} // exported i.e. will be available for import
export valueZero = 0; // will be available for import
}
You can also add later in the end of the file what you want to export
{
class AClass(){} // not exported yet
valueZero = 0; // not exported yet
valueOne = 1; // not exported (and will not in this example)
export {AClass, valueZero} // pick the one you want to export
}
Or even mix both together
{
class AClass(){} // not exported yet
export valueZero = 0; // will be available for import
export {AClass} // add AClass to the export list
}
For the import you have 2 options, first you pick again what you want (one by one)
anotherFile.ts
{
import {AClass} from "./aLib.ts"; // you import only AClass
var test = new AClass();
}
Or the whole exports
{
import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
var test = new lib.AClass();
}
Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }
Use Arrays.copyOf my friend.
sbt eclipse
from the project root directory. boolean
Can be true
or false
.
Default value is false
.
(Source: Java Primitive Variables)
Boolean
Can be a Boolean
object representing true
or false
, or can be null
.
Default value is null
.
The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)The classes above can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.
OK, the answer is easy, but read on:
col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px
The pixel numbers are the breakpoints, so for example col-xs
is targeting the element when the window is smaller than 768px(likely mobile devices)...
I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6
to show you how the grid system work in the page, look at how lg
, md
and xs
are responsive to the window size:
If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows
git rebase --onto <sha of 1> <sha of 2> <blue branch>
And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.
I faced same issue but now i am happy to resolve this issue.
npm i core-js
index.js
file.
import core-js
innerText is the current correct answer for this. The other answers are outdated and incorrect.
document.getElementById('ShowButton').innerText = 'Show filter';
innerHTML also works, and can be used to insert HTML.
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
Add an = at the beginning. That makes it a function rather than an entry.
getElementById
is defined by DOM Level 1 HTML to return null
in the case no element is matched.
!==null
is the most explicit form of the check, and probably the best, but there is no non-null
falsy value that getElementById
can return - you can only get null
or an always-truthy Element object. So there's no practical difference here between !==null
, !=null
or the looser if (document.getElementById('xx'))
.
We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View single_row = inflater.inflate(R.layout.list_row, null,
true);
TextView textView = (TextView) single_row.findViewById(R.id.textView);
ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
textView.setText(color_names[position]);
imageView.setImageResource(image_id[position]);
return single_row;
}
Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.
Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);
Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
NOTE: each boundary string must be prefixed with an extra --
, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.
Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.
In the example above, you can see the input MAX_FILE_SIZE
with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition
header.
The full details are here.
Why not get the html first then pass it to the web view?
private String getHtml(String url){
HttpGet pageGet = new HttpGet(url);
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String html;
if (entity != null) {
html = EntityUtils.toString(entity);
return html;
} else {
return null;
}
}
};
pageHTML = null;
try {
while (pageHTML==null){
pageHTML = client.execute(pageGet, handler);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageHTML;
}
@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
webview.getSettings().setJavaScriptEnabled(true);
WebViewClient anchorWebViewClient = new WebViewClient()
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Do what you want to with the html
String html = getHTML(url);
if( html!=null && !url.equals(lastLoadedURL)){
lastLoadedURL = url;
webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
}
}
This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.
you can do it Pragmatically also
GradientDrawable gradientDrawable=new GradientDrawable();
gradientDrawable.setStroke(4,getResources().getColor(R.color.line_Input));
Then set the background of layout as :
LinearLayout layout = (LinearLayout ) findViewById(R.id.ayout); layout .setBackground(gradientDrawable);
You can set the s
bit for your script so that it does not need sudo
and runs as root (and you do not need to write your root password in the script):
sudo chmod +s myscript
In short: You should be able to achieve in the order of millions of simultaneous active TCP connections and by extension HTTP request(s). This tells you the maximum performance you can expect with the right platform with the right configuration.
Today, I was worried whether IIS with ASP.NET would support in the order of 100 concurrent connections (look at my update, expect ~10k responses per second on older ASP.Net Mono versions). When I saw this question/answers, I couldn't resist answering myself, many answers to the question here are completely incorrect.
Best Case
The answer to this question must only concern itself with the simplest server configuration to decouple from the countless variables and configurations possible downstream.
So consider the following scenario for my answer:
Detailed Answer
Synchronous thread-bound designs tend to be the worst performing relative to Asynchronous IO implementations.
WhatsApp can handle a million WITH traffic on a single Unix flavoured OS machine - https://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/.
And finally, this one, http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html, goes into a lot of detail, exploring how even 10 million could be achieved. Servers often have hardware TCP offload engines, ASICs designed for this specific role more efficiently than a general purpose CPU.
Good software design choices
Asynchronous IO design will differ across Operating Systems and Programming platforms. Node.js was designed with asynchronous in mind. You should use Promises at least, and when ECMAScript 7 comes along, async
/await
. C#/.Net already has full asynchronous support like node.js. Whatever the OS and platform, asynchronous should be expected to perform very well. And whatever language you choose, look for the keyword "asynchronous", most modern languages will have some support, even if it's an add-on of some sort.
To WebFarm?
Whatever the limit is for your particular situation, yes a web-farm is one good solution to scaling. There are many architectures for achieving this. One is using a load balancer (hosting providers can offer these, but even these have a limit, along with bandwidth ceiling), but I don't favour this option. For Single Page Applications with long-running connections, I prefer to instead have an open list of servers which the client application will choose from randomly at startup and reuse over the lifetime of the application. This removes the single point of failure (load balancer) and enables scaling through multiple data centres and therefore much more bandwidth.
Busting a myth - 64K ports
To address the question component regarding "64,000", this is a misconception. A server can connect to many more than 65535 clients. See https://networkengineering.stackexchange.com/questions/48283/is-a-tcp-server-limited-to-65535-clients/48284
By the way, Http.sys on Windows permits multiple applications to share the same server port under the HTTP URL schema. They each register a separate domain binding, but there is ultimately a single server application proxying the requests to the correct applications.
Update 2019-05-30
Here is an up to date comparison of the fastest HTTP libraries - https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext
If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch()
. Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
Append a class containing pointer-events:non
.active a{ //css
text-decoration: underline;
background-color: #fff;
pointer-events: none;}
$(this).addClass('active');
Instead of using ">" to redirect like this:
java Foo > log
use ">>" to append normal "stdout" output to a new or existing file:
java Foo >> log
However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:
java Foo >> log 2>&1
You can do the following:
IQueryable query = from x in appEntities
where x.id == 32
select x;
var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
or in EF6:
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query)
.ToTraceString();
That will give you the SQL that was generated.
So here's how to do that:
In the bottom bar of VSCode, you'll see the label
UTF-8
. Click it. A popup opens. ClickSave with encoding
. You can now pick a new encoding for that file.
Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8"
. If using the graphical settings page in VSCode, simply search for encoding
. Do note however that this only applies to newly created files.
The storage_path
function returns the fully qualified path to the storage directory:
$path = storage_path();
You may also use the storage_path
function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');
Source: Laravel Doc
This worked for me
let exampleArray = [1, 2, 3, 4, 5];
let exampleToString = exampleArray.toString(); //convert to toString
let query = `Select * from table_name where column_name in (${exampleToString})`; //Execute the query to get response
I have got the same problem, then after an hour of effort I got to know that the array should not be directly accessed in the query. So I then found that the data should be sent in the paranthesis it self, then again I have converted that array to string using toString method in js. So I have worked by executing the above query and got my expected result
This service returns Countries (name,code) and cities for any country as REST, SErvice. You can also download database and sample REST service
http://tecorange.com/content/world-countries-and-cities-restjson-service-12-months-subscription
Technical Note TN2265: Troubleshooting Push Notifications
The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.
If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on.
Update: As noted in the comments below, this solution stopped working since iOS 5.1. I would encourage filing a bug with Apple so they can update their documentation. The current solution seems to be resetting the device's content and settings.
Update: The tech note has been updated with new steps that work correctly as of iOS 7.
- Delete your app from the device.
- Turn the device off completely and turn it back on.
- Go to Settings > General > Date & Time and set the date ahead a day or more.
- Turn the device off completely again and turn it back on.
UPDATE as of iOS 9
Simply deleting and reinstalling the app will reset the notification status to notDetermined
(meaning prompts will appear).
Thanks to the answer by Gomfucius below: https://stackoverflow.com/a/33247900/704803
When a function is a part of a class, it's called a method.
C# is an OOP language and doesn't have functions that are declared outside of classes, that's why all functions in C# are actually methods.
Though, beside this formal difference, they are the same...
You can use jQuery's attr()
function, like $("#id").attr('src',"source")
.
Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea
mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql
This is a program, not a mysql command
Then, log into mysql and
source dump.sql;
Achieve this by using the toolbar
like this :
<android.support.v7.widget.Toolbar
android:id="@+id/base_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
You can use a simple funcion to invert keys and values, it will work with arrays also as it converts numerical integer strings to numbers. The code is small, simple and reusable for this and other use cases.
var objInvert = function (obj) {_x000D_
var invert = {}_x000D_
for (var i in obj) {_x000D_
if (i.match(/^\d+$/)) i = parseInt(i,10)_x000D_
invert[obj[i]] = i_x000D_
}_x000D_
return invert_x000D_
}_x000D_
_x000D_
var musicStyles = Object.freeze(objInvert(['ROCK', 'SURF', 'METAL',_x000D_
'BOSSA-NOVA','POP','INDIE']))_x000D_
_x000D_
console.log(musicStyles)
_x000D_
Try this:
SELECT a.person, a.group, a.age FROM person AS a WHERE
(SELECT COUNT(*) FROM person AS b
WHERE b.group = a.group AND b.age >= a.age) <= 2
ORDER BY a.group ASC, a.age DESC
Runnable
is often used to provide the code that a thread should run, but Runnable
itself has nothing to do with threads. It's just an object with a run()
method.
In Android, the Handler
class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable
is used to provide the code that should run later.
setBounds
is used to define the bounding rectangle of a component. This includes it's position and size.
The is used in a number of places within the framework.
For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.
Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)
I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0
or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.
Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).
gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate |
select DisplayName, InstallDate |
fl | out-file addrem.txt
You can just go for String
replace method.-
line1 = line1.replace("\"", "");
I'm aware this question is a bit old. But since I stumbled on this while doing research, I thought a little addition might be helpful.
As stated the error cannot be solved by the client, since it is a network related issue. However, what you can do is retry connecting a few times. This may work as a workaround until the real issue is fixed.
for (int retries = 0; retries < 3; retries++) {
try {
final HttpClient client = createHttpClientWithDefaultSocketFactory(null, null);
final HttpResponse response = client.execute(get);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new IllegalStateException("GET Request on '" + get.getURI().toString() + "' resulted in " + statusCode);
} else {
return response.getEntity();
}
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
}
Maybe this helps someone.
You could add
/project_root/third_party_git_repository_used_by_my_project
to
/project_root/.gitignore
that should prevent the nested repo to be included in the parent repo, and you can work with them independently.
But: If a user runs git clean -dfx in the parent repo, it will remove the ignored nested repo. Another way is to symlink the folder and ignore the symlink. If you then run git clean, the symlink is removed, but the 'nested' repo will remain intact as it really resides elsewhere.
For checking the version of scikit-learn in shell script, if you have pip installed, you can try this command
pip freeze | grep scikit-learn
scikit-learn==0.17.1
Hope it helps!
You can use the command PSGetSid from Microsoft's SysInternals team.
Download URL: http://technet.microsoft.com/en-gb/sysinternals/bb897417.aspx
Usage:
psgetsid [\\computer[,computer[,...] | @file] [-u username [-p password]]] [account|SID]
-u Specifies optional user name for login to remote computer.
-p Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
Account PsGetSid will report the SID for the specified user account rather than the computer.
SID PsGetSid will report the account for the specified SID.
Computer Direct PsGetSid to perform the command on the remote computer or computers specified. If you omit the computer name PsGetSid runs the command on the local system, and if you specify a wildcard (\\*), PsGetSid runs the command on all computers in the current domain.
@file PsGetSid will execute the command on each of the computers listed in the file.
Example:
psgetsid S-1-5-21-583907252-682003330-839522115-63941
NB:
Update
If you use PowerShell, the following may be useful for resolving any AD users listed:
#create a drive for HKEY USERS:
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue
#List all immediate subfolders
#where they're a folder (not a key)
#and they's an SID (i.e. exclude .DEFAULT and SID_Classes entries)
#return the SID
#and return the related AD entry (should one exist).
Get-ChildItem -Path 'HKU:\' `
| ?{($_.PSIsContainer -eq $true) `
-and ($_.PSChildName -match '^S-[\d-]+$')} `
| select @{N='SID';E={$_.PSChildName}} `
, @{N='Name';E={Get-ADUser $_.PSChildName | select -expand Name}}
You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
I found my solution after hours of research here.
Stop MySQL
sudo service mysql stop
Make MySQL service directory.
sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld
Start MySQL manually, without permission checks or networking.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Log in without a password.
mysql -uroot mysql
update password
UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%';
EXIT;
Turn off MySQL.
sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Start the MySQL service normally.
sudo service mysql start
as another option:
$ curl -i http://google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 19 Jun 2010 04:15:10 GMT
Expires: Mon, 19 Jul 2010 04:15:10 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
But it doesn't go past the first one.
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
To see the keys:
for key in d.keys():
print(key)
To get the values that each key is referencing:
for key in d.keys():
print(d[key])
Add to a list:
for key in d.keys():
mylist.append(d[key])
<ul class="names" id="names_list">
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>
</ul>
$(document).ready(function(){
var a=0;
var ac;
var ac2;
$(".names li").click(function(){
var b=0;
if(a==0)
{
var accc="#"+ac2;
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
$(this).css({
"background":"#d3b730",
"color":"#000",
});
ac=$(this).attr('class');
ac2=$(this).attr('id');
a=1;
}
else{
var accc="#"+ac2;
//alert(accc);
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
a=0;
ac=$(this).attr('class');
ac2=$(this).attr('id');
$(this).css({
"background":"#d3b730",
"color":"#000",
});
}
});
Instead of QString::number()
i would use QLocale::toString()
, so i can get locale aware group seperatores like german "1.234.567,89".
For Angular 7, I followed these steps to directly import json data:
In tsconfig.app.json:
add "resolveJsonModule": true
in "compilerOptions"
In a service or component:
import * as exampleData from '../example.json';
And then
private example = exampleData;
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl();
is toDataURL();
and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
I had the exact same problem yesterday working through problem 2-3 in Accelerated C++. The key is to change all variables you will be comparing (using Boolean operators) to compatible types. In this case, that means string::size_type
(or unsigned int
, but since this example is using the former, I will just stick with that even though the two are technically compatible).
Notice that in their original code they did exactly this for the c counter (page 30 in Section 2.5 of the book), as you rightly pointed out.
What makes this example more complicated is that the different padding variables (padsides and padtopbottom), as well as all counters, must also be changed to string::size_type
.
Getting to your example, the code that you posted would end up looking like this:
cout << "Please enter the size of the frame between top and bottom";
string::size_type padtopbottom;
cin >> padtopbottom;
cout << "Please enter size of the frame from each side you would like: ";
string::size_type padsides;
cin >> padsides;
string::size_type c = 0; // definition of c in the program
if (r == padtopbottom + 1 && c == padsides + 1) { // where the error no longer occurs
Notice that in the previous conditional, you would get the error if you didn't initialize variable r as a string::size_type
in the for
loop. So you need to initialize the for loop using something like:
for (string::size_type r=0; r!=rows; ++r) //If r and rows are string::size_type, no error!
So, basically, once you introduce a string::size_type
variable into the mix, any time you want to perform a boolean operation on that item, all operands must have a compatible type for it to compile without warnings.
Take a look at the Huffman algorithm.
https://codereview.stackexchange.com/questions/44473/huffman-code-implementation
The idea is that each character is replaced with sequence of bits, depending on their frequency in the text (the more frequent, the smaller the sequence).
You can read your entire text and build a table of codes, for example:
Symbol Code
a 0
s 10
e 110
m 111
The algorithm builds a symbol tree based on the text input. The more variety of characters you have, the worst the compression will be.
But depending on your text, it could be effective.
It is possible to use Object.defineProperty()
in order to redefine the 'value' property of the input element and do anything during its changing.
Object.defineProperty()
allows us to define a getter and setter for a property, thus controlling it.
replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) {
console.log("new value:", value)
});
function replaceWithWrapper(obj, property, callback) {
Object.defineProperty(obj, property, new function() {
var _value = obj[property];
return {
set: function(value) {
_value = value;
callback(obj, property, value)
},
get: function() {
return _value;
}
}
});
}
$("#hid1").val(4);
For people coming from the future, you can now do this purely in CSS.
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
margin: 5rem;
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
width: 120px;
bottom: 100%;
left: 50%;
margin-left: -60px;
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
The last suggestion is the correct solution. Just to repeat, first set android:focusable="true"
in the layout xml
file, then requestFocus()
on the view in your code.
Try Server.UrlEncode()
, or System.Web.HttpUtility.UrlEncode()
for instances when you don't have access to the Server
object. You can also use System.Uri.EscapeUriString()
to avoid adding a reference to the System.Web
assembly.
As Marc says, this is not possible (although Visual Studio allows you to add an application configuration file in a class library project).
You might want to check out the AssemblySettings class which seems to make assembly config files possible.
Converting from file with base64 string to png image.
4 variants which works.
var {promisify} = require('util');
var fs = require("fs");
var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)
async function run () {
// variant 1
var d = await readFile('./1.txt', 'utf8')
await writeFile("./1.png", d, 'base64')
// variant 2
var d = await readFile('./2.txt', 'utf8')
var dd = new Buffer(d, 'base64')
await writeFile("./2.png", dd)
// variant 3
var d = await readFile('./3.txt')
await writeFile("./3.png", d.toString('utf8'), 'base64')
// variant 4
var d = await readFile('./4.txt')
var dd = new Buffer(d.toString('utf8'), 'base64')
await writeFile("./4.png", dd)
}
run();
**EDITED for Swift 4.2:
As @Koen commented, swift 4.2 allows:
guard let self = self else {
return // Could not get a strong reference for self :`(
}
// Now self is a strong reference
self.doSomething()
P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.
EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**
For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement
guard let `self` = self else {
return
}
self.doSomething()
If you are wondering what the quote marks are around self
is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.
Step 1
Go to C:\wamp\bin\apache\Apache2.2.17\conf\
open httpd.conf
file and change #Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.
Step 2
Go to C:\wamp\bin\apache\Apache2.2.17\conf\extra
and open httpd-vhosts.conf
file and add the following code
<VirtualHost myWebsite.local>
DocumentRoot "C:/wamp/www/myWebsite/"
ServerName myWebsite.local
ServerAlias myWebsite.local
<Directory "C:/wamp/www/myWebsite/">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
change myWebsite.local
and C:/wamp/www/myWebsite/
as per your requirements.
Step 3
Open hosts
file in C:/Windows/System32/drivers/etc/
and add the following line ( Don't delete anything )
127.0.0.1 myWebsite.local
change myWebsite.local
as per your name requirements
Step 4
restart your server. That's it
Same steps as that of WAMP just change the paths according to XAMPP which corresponds to path in WAMP
For a simple array, you have the union approach, but you can also use :
_.uniq([2, 1, 2]);
There is bug in MySQL 5.6 version. Even mysqld show as :
Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Realy settings are reading in following order :
Default options are read from the following files in the given order:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Check file: "C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"
Hope it help somebody.
You can also use:
{{ word|striptags('<b>')|raw }}
so that only <b>
tag will be allowed.
I would do something like:
select
A.id, A.age, B.count
from
students A,
(select age, count(*) as count from students group by age) B
where A.age=B.age;
I've found that you can move div elements to the next line simply by setting the property
Display: block;
On each div.