JSON.stringify(data).length return string length not Object length, you can use Object.keys.
<% for(var i=0; i < Object.keys(data).length ; i++) {%>
Some of the benefits of PreparedStatement over Statement are:
Read more about SQL injection issue at http://www.journaldev.com/2489/jdbc-statement-vs-preparedstatement-sql-injection-example
echo ".dump" | sqlite3 /tmp/db.sqlite > db.sql
watch out for CREATE statements
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)
In app-level gradle, you have to write these code:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
They come from JavaVersion.java in Android.
An enumeration of Java versions.
Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
After 9: http://openjdk.java.net/jeps/223
@canerkaseler
Basically it would be the wrong thing to do.
There are two ways this could be implemented:
Keep hold of the lock, only releasing it at the end of the block.
This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).
Release the lock in the await, and reacquire it when the await returns
This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait
in a lock block, you expect to own the lock for the duration of the block.
So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:
// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}
So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.
I have worked alot with msaccess vba. I think you are looking for MID function
example
dim myReturn as string
myreturn = mid("bonjour tout le monde",9,4)
will give you back the value "tout"
Originally ZIP files were created with MS-DOS command line software from PKWare, the two programs were PKZIP.EXE and PKUNZIP.EXE. I think you can still download PKUNZIP at the PKWare site here:
http://www.pkware.com/software-pkzip/dos-compression
The actual command line could look something like this:
C:\>pkunzip c:\myzipfile.zip c:\extracttothisfolder\
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.
You need to stream the page into an HtmlDocument object and then select your required element.
// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;
try
{
var webRequest = HttpWebRequest.Create(pageUrl);
Stream stream = webRequest.GetResponse().GetResponseStream();
doc.Load(stream);
stream.Close();
}
catch (System.UriFormatException uex)
{
Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
throw;
}
catch (System.Net.WebException wex)
{
Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
throw;
}
//get the div by id and then get the inner text
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();
[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.
Code sample directly from their site:
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;
//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
var title = item.QuerySelector("h3:not(.share)").InnerText;
var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
var description = item.QuerySelector("span:has(b)").InnerHtml;
}
I don't think it can get any simpler than that.
in my problem I want the text of anchor <a>text</a>
inside my view to be based on some value
and that text is retrieved form App string Resources
so, this @()
is the solution
<a href='#'>
@(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>
if the text is not from App string Resources
use this
@(Model.ID == 0 ? "Back" :"Descart Changes")
Declare the property place holder as follows
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>file:///path.to.your.app.config.properties</value>
</list>
</property>
</bean>
Then lets say you want to read System.property("java.io.tmpdir")
for your Tomcat bean or any bean then add following in your properties file:
tomcat.tmp.dir=${java.io.tmpdir}
It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!
Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:
switch (<condition>) {
case c_0: ...
case c_1: ...
...
case c_n: ...
default: ...
}
where c_0
, c_1
, ..., and c_N
are integral numbers that are targets of the switch statement, and <condition>
must resolve to an integer expression.
If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k
is larger than some empirical value, a jump table can be generated, which is highly efficient.
If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.
For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.
Finally, of course, if the domain of <condition>
is not the integers, a switch
statement is completely useless.
There might be a reason that Typescript
is not installed globally, so install it
npm install -g typescript // installs typescript globally
If you want to convert .ts
files into .js
, do this as per your need
tsc file.ts // file.ts will be converted to file.js file
tsc // all .ts files will be converted to .js files in the directory
tsc --watch // converts all .ts files to .js, and watch changes in .ts files
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
decimal d = 5.5
;
int i = decimal.ToInt32(d);// you will get i = 5
ref: link text
Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.
I will give 2 examples from personal experience where using a Rules Engine was a bad idea, maybe that will help:-
Lesson: They are called "Business Rules" for a reason, do not use rules when you cannot design a system that can be easily maintained/understood by Business users.
Lesson: Requirements tend to change a lot during initial release changes and do not warrant usage of rules. Use rules when your business changes often (not requirements). Eg:- A software that does your taxes will change every year as taxation laws change and usage of rules is an excellent idea. Release 1.0 of an web app will change often as users identify new requirements but will stabilize over time. Do not use rules as an alternative to code deploy. ?
NOTE: Later versions of the IDE may use "pch" rather than "stdafx" in the default names for related files. It may be necessary to substitute pch for stdafx in the instructions below. I apologize. It's not my fault.
Click Okay
If you do not have stdafx.h in your Header Files put it there. Edit it to #include all the headers you want precompiled.
Lucky 13. Cross your fingers and hit Build.
Use the Java Calendar
class.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SUNDAY:
// Current day is Sunday
break;
case Calendar.MONDAY:
// Current day is Monday
break;
case Calendar.TUESDAY:
// etc.
break;
}
$arr1 = array(
"0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
"1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
"2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
"3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
"4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
);
if you want to convert this array as following:
$arr2 = array(
"0" => array(
"0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
"1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
"2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
"3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
),
"1" => array(
"0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
)
);
so, my answer will be like this:
$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
{
$inner_array = array();
$fid_value = $value['fid'];
if(!in_array($value['fid'], $unique_array))
{
array_push($unique_array, $fid_value);
unset($value['fid']);
array_push($inner_array, $value);
$outer_array[$fid_value] = $inner_array;
}else{
unset($value['fid']);
array_push($outer_array[$fid_value], $value);
}
}
var_dump(array_values($outer_array));
hope this answer will help somebody sometime.
You could also do something like:
String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");
It handles white spaces and words of variable length and produces the array:
[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]
Here is a simple and clear example of how this works
Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
String: "!* UserName10 John Smith 01123 *!"
group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):
group(3): John Smith
group(4):
group(5): 01123
As you can see, I have created FIVE groups which are each enclosed in parentheses.
I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.
Hope this makes sense.
If you added a library to the project structure (rather than via maven, that would be different), be sure it is included as a dependency for the relevant module.
Project Structure -> Modules -> Dependencies
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
One point from me. I used a mutual cert authentication with spring-boot microservices. The following is working for me, key points here are
keyManagerFactory.init(...)
and sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom())
lines of code without them, at least for me, things did not work. Certificates are packaged by PKCS12.
@Value("${server.ssl.key-store-password}")
private String keyStorePassword;
@Value("${server.ssl.key-store-type}")
private String keyStoreType;
@Value("${server.ssl.key-store}")
private Resource resource;
private RestTemplate getRestTemplate() throws Exception {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
private HttpClient httpClient() throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance(keyStoreType);
if (resource.exists()) {
InputStream inputStream = resource.getInputStream();
try {
if (inputStream != null) {
trustStore.load(inputStream, keyStorePassword.toCharArray());
keyManagerFactory.init(trustStore, keyStorePassword.toCharArray());
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} else {
throw new RuntimeException("Cannot find resource: " + resource.getFilename());
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
CSS3 allows this sort of thing and it looks like this:
body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:
<body>
<div id="bgTopDiv">
content here
</div>
</body>
body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
I think what you are looking for is iter_swap
which you can find also in <algorithm>
.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:
// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap
new_list = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
for i in range(len(new_list)):
new_list[i]=new_list[i].replace('\n','')
print(new_list)
Output Will be like this
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']
The methods in the other answers will not work properly when the yticks are large. The ylabel will either overlap with ticks, be clipped on the left or completely invisible/outside of the figure.
I've modified Hagne's answer so it works with more than 1 column of subplots, for both xlabel and ylabel, and it shifts the plot to keep the ylabel visible in the figure.
def set_shared_ylabel(a, xlabel, ylabel, labelpad = 0.01, figleftpad=0.05):
"""Set a y label shared by multiple axes
Parameters
----------
a: list of axes
ylabel: string
labelpad: float
Sets the padding between ticklabels and axis label"""
f = a[0,0].get_figure()
f.canvas.draw() #sets f.canvas.renderer needed below
# get the center position for all plots
top = a[0,0].get_position().y1
bottom = a[-1,-1].get_position().y0
# get the coordinates of the left side of the tick labels
x0 = 1
x1 = 1
for at_row in a:
at = at_row[0]
at.set_ylabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
bboxes = bboxes.inverse_transformed(f.transFigure)
xt = bboxes.x0
if xt < x0:
x0 = xt
x1 = bboxes.x1
tick_label_left = x0
# shrink plot on left to prevent ylabel clipping
# (x1 - tick_label_left) is the x coordinate of right end of tick label,
# basically how much padding is needed to fit tick labels in the figure
# figleftpad is additional padding to fit the ylabel
plt.subplots_adjust(left=(x1 - tick_label_left) + figleftpad)
# set position of label,
# note that (figleftpad-labelpad) refers to the middle of the ylabel
a[-1,-1].set_ylabel(ylabel)
a[-1,-1].yaxis.set_label_coords(figleftpad-labelpad,(bottom + top)/2, transform=f.transFigure)
# set xlabel
y0 = 1
for at in axes[-1]:
at.set_xlabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.xaxis.get_ticklabel_extents(fig.canvas.renderer)
bboxes = bboxes.inverse_transformed(fig.transFigure)
yt = bboxes.y0
if yt < y0:
y0 = yt
tick_label_bottom = y0
axes[-1, -1].set_xlabel(xlabel)
axes[-1, -1].xaxis.set_label_coords((left + right) / 2, tick_label_bottom - labelpad, transform=fig.transFigure)
It works for the following example, while Hagne's answer won't draw ylabel (since it's outside of the canvas) and KYC's ylabel overlaps with the tick labels:
import matplotlib.pyplot as plt
import itertools
fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
for i, a in enumerate(itertools.chain(*axes)):
a.plot([0,4**i], [0,4**i])
a.set_title(i)
set_shared_ylabel(axes, 'common X', 'common Y')
plt.show()
Alternatively, if you are fine with colorless axis, I've modified Julian Chen's solution so ylabel won't overlap with tick labels.
Basically, we just have to set ylims of the colorless so it matches the largest ylims of the subplots so the colorless tick labels sets the correct location for the ylabel.
Again, we have to shrink the plot to prevent clipping. Here I've hard coded the amount to shrink, but you can play around to find a number that works for you or calculate it like in the method above.
import matplotlib.pyplot as plt
import itertools
fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
miny = maxy = 0
for i, a in enumerate(itertools.chain(*axes)):
a.plot([0,4**i], [0,4**i])
a.set_title(i)
miny = min(miny, a.get_ylim()[0])
maxy = max(maxy, a.get_ylim()[1])
# add a big axes, hide frame
# set ylim to match the largest range of any subplot
ax_invis = fig.add_subplot(111, frameon=False)
ax_invis.set_ylim([miny, maxy])
# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")
# shrink plot to prevent clipping
plt.subplots_adjust(left=0.15)
plt.show()
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
I use this command.
kubectl -n <namespace> logs -f deployment/<app-name> --all-containers=true --since=10m
.sort()
, in pymongo, takes key
and direction
as parameters.
So if you want to sort by, let's say, id
then you should .sort("_id", 1)
For multiple fields:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']
<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['Make']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
echo $maker;
}
?>
You can sharpen an image using an unsharp mask. You can find more information about unsharp masking here. And here's a Python implementation using OpenCV:
import cv2 as cv
import numpy as np
def unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):
"""Return a sharpened version of the image, using an unsharp mask."""
blurred = cv.GaussianBlur(image, kernel_size, sigma)
sharpened = float(amount + 1) * image - float(amount) * blurred
sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))
sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))
sharpened = sharpened.round().astype(np.uint8)
if threshold > 0:
low_contrast_mask = np.absolute(image - blurred) < threshold
np.copyto(sharpened, image, where=low_contrast_mask)
return sharpened
def example():
image = cv.imread('my-image.jpg')
sharpened_image = unsharp_mask(image)
cv.imwrite('my-sharpened-image.jpg', sharpened_image)
Here's a version using the excellent requests library:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
print(response.headers)
print(response.text)
Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show
them to see the diff and use patch -R
to unapply them.
How to add new line in Markdown presentation?
Check the following resource Line Return
To force a line return, place two empty spaces at the end of a line.
There is a way to use guards for individual (or multiple) attributes.
@debug: true;
header {
/* guard for attribute */
& when (@debug = true) {
background-color: yellow;
}
/* guard for nested class */
#title when (@debug = true) {
background-color: orange;
}
}
/* guard for class */
article when (@debug = true) {
background-color: red;
}
/* and when debug is off: */
article when not (@debug = true) {
background-color: green;
}
...and with Less 1.7; compiles to:
header {
background-color: yellow;
}
header #title {
background-color: orange;
}
article {
background-color: red;
}
Get the real path to your script
if [ -L $0 ] ; then
ME=$(readlink $0)
else
ME=$0
fi
DIR=$(dirname $ME)
(This is answer to the same my question here: Get the name of the directory where a script is executed)
MySQL is most likely in STRICT
mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.
Change the column to allow null:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL
or, give it a default value as empty string:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''
New version, now you also have the GC= try to replace both DPB and GC with those
DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"
password will be "test"
The ggrepel
package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel()
(draws rectangles around the text) or geom_text_repel()
functions.
library(ggplot2)
library(ggrepel)
nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")
nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) +
geom_point(color = "blue", size = 3)
### geom_label_repel
nbaplot +
geom_label_repel(aes(label = Name),
box.padding = 0.35,
point.padding = 0.5,
segment.color = 'grey50') +
theme_classic()
### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) +
geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77",
nba$PTS < 18 ~ "#d95f02",
TRUE ~ "#7570b3"),
size = 3, alpha = 0.8) +
geom_text_repel(data = subset(nba, PTS > 25),
nudge_y = 32 - subset(nba, PTS > 25)$PTS,
size = 4,
box.padding = 1.5,
point.padding = 0.5,
force = 100,
segment.size = 0.2,
segment.color = "grey50",
direction = "x") +
geom_label_repel(data = subset(nba, PTS < 18),
nudge_y = 16 - subset(nba, PTS < 18)$PTS,
size = 4,
box.padding = 0.5,
point.padding = 0.5,
force = 100,
segment.size = 0.2,
segment.color = "grey50",
direction = "x") +
scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
theme_classic(base_size = 16)
Edit: To use ggrepel
with lines, see this and this.
Created on 2019-05-01 by the reprex package (v0.2.0).
unlink('path_to_filename');
will delete one file at a time.
If your whole files from directory is gone means you listed all files and deleted one by one in a loop.
Well you cannot de delete in the same page. You have to do with other page. create a page called deletepage.php
which will contain script to delete and link to that page with 'file' as parameter.
foreach($FilesArray as $file)
{
$FileLink = $Directory.'/'.$file['FileName'];
if($OpenFileInNewTab) $LinkTarget = ' target="_blank"';
else $LinkTarget = '';
echo '<a href="'.$FileLink.'">'.$FileName.'</a>';
echo '<a href="deletepage.php?file='.$fileName.'"><img src="images/icons/delete.gif"></a></td>';
}
On the deletepage.php
//and also consider to check if the file exists as with the other guy suggested.
$filename = $_GET['file']; //get the filename
unlink('DIRNAME'.DIRECTORY_SEPARATOR.$filename); //delete it
header('location: backto prev'); //redirect back to the other page
If you don't want to navigate, then use ajax to make elegant.
As an alternative, you can save old data and create a new table with new parameters.
In SQL Server Management Studio: "your database" => task => generatescripts => select specific database object => "your table" => advanced => types of data to script - schema and data => generate
Personally, I did so.
1st option -
You can nest REPLACE()
functions up to 32 levels deep. It runs fast.
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (@str, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '')
2nd option -- do the reverse of -
Removing nonnumerical data out of a number + SQL
3rd option - if you want to use regex
This is what Array#map are good at
var arr = oFullResponse.results.map(obj => ({
key: obj.label,
sortable: true,
resizeable: true
}))
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
You can do the following
git cherry-pick --abort
From the git cherry-pick
docs
--abort
Cancel the operation and return to the pre-sequence state.
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
After searching and combining answers, 2018 version of this question and it worked for me:
1) On navigation tab change it to project view
2) Navigate to [YourProjectName]/.idea/libraries/
3) Delete all files starting with Gradle__com_android_support_[libraryName]
E.g: Gradle__com_android_support_animated_vector_drawable_26_0_0.xml
4) In your gradle file define a variable and use it to replace version number like ${variableName}
Def variable:
ext {
support_library_version = '28.0.0' //use the version of choice
}
Use variable:
implementation "com.android.support:cardview-v7:${support_library_version}"
example gradle:
dependencies {
ext {
support_library_version = '28.0.0' //use the version of choice
}
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:animated-vector-drawable:${support_library_version}"
implementation "com.android.support:appcompat-v7:${support_library_version}"
implementation "com.android.support:customtabs:${support_library_version}"
implementation "com.android.support:cardview-v7:${support_library_version}"
implementation "com.android.support:support-compat:${support_library_version}"
implementation "com.android.support:support-v4:${support_library_version}"
implementation "com.android.support:support-core-utils:${support_library_version}"
implementation "com.android.support:support-core-ui:${support_library_version}"
implementation "com.android.support:support-fragment:${support_library_version}"
implementation "com.android.support:support-media-compat:${support_library_version}"
implementation "com.android.support:appcompat-v7:${support_library_version}"
implementation "com.android.support:recyclerview-v7:${support_library_version}"
implementation "com.android.support:design:${support_library_version}"
}
For Windows' IDE:
If your path doesn't work, you can try to add the chromedriver.exe
to your project, like in this project structure.
Then you should load the chromedriver.exe
in your main file. As for me, I loaded the driver.exe
in driver.py
.
def get_chrome_driver():
return webdriver.Chrome("..\\content\\engine\\chromedriver.exe",
chrome_options='--no-startup-window')
..
means driver.py's
upper directory
.
means the directory where the driver.py
is located
Hope this will be helpful.
I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception
.
After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.
The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000
and accept max 200
pending sockets.
new Thread(() -> {
try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
logger.info("Server starts listening on TCP port {}", port);
while (true) {
try {
ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
executor.execute(clientHandler::start);
} catch (Exception e) {
logger.error(e.getMessage());
}
}
} catch (IOException | SecurityException | IllegalArgumentException e) {
logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
}
}).start();
From Javadoc of ServerSocket:
The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.
To clarify, system variables are the same as environment variables. User environment variables are set per user and are different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.
To access either the current value of a system wide variable or a user variable in Java, see below:
String javaHome = System.getenv("JAVA_HOME");
For more information on environment variables see this wikipedia page.
Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:
echo %MYENVVAR%
You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.
I did not know about DMBS_METADATA, but your answers prompted me to create a utility to script all objects owned by an Oracle user.
You can define an interface as array with simply extending the Array interface.
export interface MyInterface extends Array<MyType> { }
With this, any object which implements the MyInterface
will need to implement all function calls of arrays and only will be able to store objects with the MyType
type.
On my system: CentOS 5
I can use \s
outside of collections but have to use [:space:]
inside of collections. In fact I can use [:space:]
only inside collections. So to match a single space using this I have to use [[:space:]]
Which is really strange.
echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"
Result: a b cX
\s
[[:space:]]
[^[:space:]]
These two will not work:
a[:space:]b instead use a\sb or a[[:space:]]b
a[^\s]b instead use a[^[:space:]]b
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
I cannot reproduce the error.
Perhaps I'm not understanding the problem.
The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
GO
select company, stepid, fieldid from #Results
GO
ALTER TABLE #Results ADD foo VARCHAR(50) NULL
GO
select company, stepid, fieldid, foo from #Results
GO
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
Hive Vs Pig-
Hive is as SQL interface which allows sql savvy users or Other tools like Tableu/Microstrategy/any other tool or language that has sql interface..
PIG is more like a ETL pipeline..with step by step commands like declaring variables, looping, iterating , conditional statements etc.
I prefer writing Pig scripts over hive QL when I want to write complex step by step logic. When I am comfortable writing a single sql for pulling the data i want i use Hive. for hive you will need to define table before querying(as you do in RDBMS)
The purpose of both are different but under the hood, both do the same, convert to map reduce programs.Also the Apache open source community is add more and more features to both there projects
Others have answered the broad strokes pretty well, so I'll throw in a few details.
Stack and heap need not be singular. A common situation in which you have more than one stack is if you have more than one thread in a process. In this case each thread has its own stack. You can also have more than one heap, for example some DLL configurations can result in different DLLs allocating from different heaps, which is why it's generally a bad idea to release memory allocated by a different library.
In C you can get the benefit of variable length allocation through the use of alloca, which allocates on the stack, as opposed to alloc, which allocates on the heap. This memory won't survive your return statement, but it's useful for a scratch buffer.
Making a huge temporary buffer on Windows that you don't use much of is not free. This is because the compiler will generate a stack probe loop that is called every time your function is entered to make sure the stack exists (because Windows uses a single guard page at the end of your stack to detect when it needs to grow the stack. If you access memory more than one page off the end of the stack you will crash). Example:
void myfunction()
{
char big[10000000];
// Do something that only uses for first 1K of big 99% of the time.
}
To send json to the server, you first have to create json
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob",
...
}),
dataType: 'json'
});
}
This is how you would structure the ajax request to send the json as a post var.
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
data: { json: JSON.stringify({
name:"Bob",
...
})},
dataType: 'json'
});
}
The json will now be in the json
post var.
I think you could just do:
let array = [];
array.length = 2;
Object.defineProperty(array, 'length', {writable:false});
array[0] = 1 // [1, undefined]
array[1] = 2 // [1, 2]
array[2] = 3 // [1, 2] -> doesn't add anything and fails silently
array.push("something"); //but this throws an Uncaught TypeError
You must to download MySQLConnection NET from here.
Then you need add MySql.Data.DLL
to MSVisualStudio like this:
C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
If you want to know more visit: enter link description here
To use in the code you must import the library:
using MySql.Data.MySqlClient;
An example with connectio to Mysql database (NO SSL MODE) by means of Click event:
using System;
using System.Windows;
using MySql.Data.MySqlClient;
namespace Deportes_WPF
{
public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;
public Login()
{
InitializeComponent();
server = "server_name";
database = "database_name";
user = "user_id";
password = "password";
port = "3306";
sslM = "none";
connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
private void conexion()
{
try
{
connection.Open();
MessageBox.Show("successful connection");
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message + connectionString);
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
conexion();
}
}
}
Maybe this can help:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: basic-auth-server.herokuapp.com
schemes:
- http
- https
securityDefinitions:
Bearer:
type: apiKey
name: Authorization
in: header
paths:
/:
get:
security:
- Bearer: []
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.
There are also several examples in the swagger editor web with more complex security configurations which could help you.
run - Create a container using image and Start the same. (Create & Start)
start - Start the container(s) in docker list which was in stopped state.
I recommend 2 things. First is associative array.
$person = Array();
$person['name'] = "Joe";
$person['age'] = 22;
Second is classes.
Detailed documentation here: http://php.net/manual/en/language.oop5.php
General sibling combinator
The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.
For some reason I could not get this to work with the proposed answers, but I found another variation, using select, that worked for me:
models.Post.find().sort('-date').limit(10).select('published').exec(function(e, data){
...
});
Has the api perhaps changed? I am using version 3.8.19
You can also configure your SSL in xampp/apache/conf/extra/httpd-vhost.conf
like this:
<VirtualHost *:443>
DocumentRoot C:/xampp/htdocs/yourProject
ServerName yourProject.whatever
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
</VirtualHost>
I guess, it's better not change it in the httpd-ssl.conf
if you have more than one project and you need SSL on more than one of them
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine() sc.nextLine()
WITH SensorTimes As (
SELECT sensorID, MAX(timestamp) "LastReading"
FROM sensorTable
GROUP BY sensorID
)
SELECT s.sensorID,s.timestamp,s.sensorField1,s.sensorField2
FROM sensorTable s
INNER JOIN SensorTimes t on s.sensorID = t.sensorID and s.timestamp = t.LastReading
for more details about context, read this article. I will explain that briefly.
If you wanna know what is context you must know what it does...
for example getContext() is one of the methods that retrieve context. In getContext(), Context is tied to an Activity and its lifecycle. We can imagine Context as layer which stands behind Activity and it will live as long as Activity lives. The moment the Activity dies, Context will too. this method gives list of functionalities to activity, like:
Load Resource Values,
Layout Inflation,
Start an Activity,
Show a Dialog,
Start a Service,
Bind to a Service,
Send a Broadcast,
Register BroadcastReceiver.
now imagine that :
Context is a layer(interface) which stands behind its component (Activity, Application…) and component’s lifecycle, which provides access to various functionalities which are supported by application environment and Android framework.
In Ubuntu the file path is ./opt/lampp/var/mysql
Microsoft now has an extension for VS 2010 that provides this functionality:
My solution similar as mefa:::rep.data.frame
, but a little faster and cares about row names:
rep.data.frame <- function(x, times) {
rnames <- attr(x, "row.names")
x <- lapply(x, rep.int, times = times)
class(x) <- "data.frame"
if (!is.numeric(rnames))
attr(x, "row.names") <- make.unique(rep.int(rnames, times))
else
attr(x, "row.names") <- .set_row_names(length(rnames) * times)
x
}
Compare solutions:
library(Lahman)
library(microbenchmark)
microbenchmark(
mefa:::rep.data.frame(Batting, 10),
rep.data.frame(Batting, 10),
Batting[rep.int(seq_len(nrow(Batting)), 10), ],
times = 10
)
#> Unit: milliseconds
#> expr min lq mean median uq max neval cld
#> mefa:::rep.data.frame(Batting, 10) 127.77786 135.3480 198.0240 148.1749 278.1066 356.3210 10 a
#> rep.data.frame(Batting, 10) 79.70335 82.8165 134.0974 87.2587 191.1713 307.4567 10 a
#> Batting[rep.int(seq_len(nrow(Batting)), 10), ] 895.73750 922.7059 981.8891 956.3463 1018.2411 1127.3927 10 b
Quick fix! If you don't want to manually add a space, you can do this:
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
(edit: i see that this is actually answered above, sorry!)
sdk
You can see the location there – most of the time it is:
/Users/<name>/Library/Android/sdk
Open your Terminal edit your ~/.bash_profile
file in nano by typing:
nano ~/.bash_profile
If you use Zsh, edit ~/.zshrc
instead.
Go to the end of the file and add the directory path to your $PATH
:
export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
Ctrl+X
adb
) and verify it is opened/executedI think you're looking for the ndenumerate.
>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
... print x,y
...
0 0
0 1
1 0
1 1
2 0
2 1
Regarding the performance. It is a bit slower than a list comprehension.
X = np.zeros((100, 100, 100))
%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop
%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop
If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate
, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords
attribute of the flat iterator.
a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop
If you have code that needs to run various versions you could do something like this:
import sklearn
if sklearn.__version__ > '0.18':
from sklearn.model_selection import train_test_split
else:
from sklearn.cross_validation import train_test_split
This isn't ideal though because you're comparing package versions as strings, which usually works but doesn't always. If you're willing to install packaging
, this is a much better approach:
from packaging.version import parse
import sklearn
if parse(sklearn.__version__) > parse('0.18'):
from sklearn.model_selection import train_test_split
else:
from sklearn.cross_validation import train_test_split
For AMD processors:
You don't need Genymotion, just create a new Virtual Device and while selecting the system Image select the ABI as armeabi instead of the default x86 one.
For older .xls
files, you can use xlrd
either you can use xlrd
directly by importing it. Like below
import xlrd
wb = xlrd.open_workbook(file_name)
Or you can also use pandas pd.read_excel()
method, but do not forget to specify the engine, though the default is xlrd
, it has to be specified.
pd.read_excel(file_name, engine = xlrd)
Both of them work for older .xls
file formats.
Infact I came across this when I used OpenPyXL
, i got the below error
InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.
(If you are in MacOS 10.10, try the accumulative -c option of top:
top -c a -pid PID
(This option is not available in other linux, tried with Scientific Linux el6 and RHEL6)
This is what I found when I had this doubt.
mysql> create table numbers (a decimal(10,2), b float);
mysql> insert into numbers values (100, 100);
mysql> select @a := (a/3), @b := (b/3), @a * 3, @b * 3 from numbers \G
*************************** 1. row ***************************
@a := (a/3): 33.333333333
@b := (b/3): 33.333333333333
@a + @a + @a: 99.999999999000000000000000000000
@b + @b + @b: 100
The decimal did exactly what's supposed to do on this cases, it truncated the rest, thus losing the 1/3 part.
So for sums the decimal is better, but for divisions the float is better, up to some point, of course. I mean, using DECIMAL will not give you a "fail proof arithmetic" in any means.
Hope this helps.
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.
Seems there is a change in handling of attribute protection and now you must whitelist params in the controller (instead of attr_accessible in the model) because the former optional gem strong_parameters became part of the Rails Core.
This should look something like this:
class PeopleController < ActionController::Base
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age)
end
end
So params.require(:model).permit(:fields)
would be used
and for nested attributes something like
params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])
Some more details can be found in the Ruby edge API docs and strong_parameters on github or here
Simple add trigger change like this:
$('#selectId').val('').trigger('change');
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
To find out URI:
current_uri = request.env['PATH_INFO']
# If you are browsing http://example.com/my/test/path,
# then above line will yield current_uri as "/my/test/path"
To find out the route i.e. controller, action and params:
path = ActionController::Routing::Routes.recognize_path "/your/path/here/"
# ...or newer Rails versions:
#
path = Rails.application.routes.recognize_path('/your/path/here')
controller = path[:controller]
action = path[:action]
# You will most certainly know that params are available in 'params' hash
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
I closed modal Programmatically with this trick
Add a button in modal with data-dismiss="modal"
and hide the button with display: none
. Here is how it will look like
<div class="modal fade" id="addNewPaymentMethod" role="dialog">
<div class="modal-dialog">
.
.
.
<button type="button" id="close-modal" data-dismiss="modal" style="display: none">Close</button>
</div>
</div>
Now when you want to close modal Programmatically just trigger a click event on that button, which is not visible to user
In Javascript you can trigger click on that button like this:
document.getElementById('close-modal').click();
Here is a solution for transposing a list of lists that is not necessarily square:
maxCol = len(l[0])
for row in l:
rowLength = len(row)
if rowLength > maxCol:
maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
lTrans.append([])
for row in l:
if colIndex < len(row):
lTrans[colIndex].append(row[colIndex])
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
Collection is an Interface which can used to Represent a Group of Individual object as a single Entity.
Collections is an utility class to Define several Utility Methods for Collection object.
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
I just ran into this issue as well. There's an option to "refresh fields", which I found useful. What I didn't find intuitive at first was that one has to enter values used to execute the query in such a fashion as to refresh the fields. Once I figured this out, and refreshed the fields - things worked. The data sets and the shared dataset that's being called have to correlate.
Use those queries to find all FKs:
Declare @SchemaName VarChar(200) = 'Schema Name'
Declare @TableName VarChar(200) = 'Table name'
-- Find FK in This table.
SELECT
'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
See this MDN article for more info on the FileList
type.
Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files
property in non-File API browsers.
To obtain the id of the documents in a collection, you must use snapshotChanges()
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example
Should you? Yes.
Why? Log4J has essentially been deprecated by Logback.
Is it urgent? Maybe not.
Is it painless? Probably, but it may depend on your logging statements.
Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.
Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)
This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
You can use jQuery's attr() function. For example, if your img
tag has an id
attribute of 'my_image', you would do this:
<img id="my_image" src="first.jpg"/>
Then you can change the src
of your image with jQuery like this:
$("#my_image").attr("src","second.jpg");
To attach this to a click
event, you could write:
$('#my_image').on({
'click': function(){
$('#my_image').attr('src','second.jpg');
}
});
To rotate the image, you could do this:
$('img').on({
'click': function() {
var src = ($(this).attr('src') === 'img1_on.jpg')
? 'img2_on.jpg'
: 'img1_on.jpg';
$(this).attr('src', src);
}
});
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
## b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3
df <- data.frame(a = c(0, 0, 0), df)
df
## a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3
Assuming we're working with strings here, here's another "elegant" solution using IndexOf()
.
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.IndexOf(description, StringComparison.OrdinalIgnoreCase) != -1);
}
onSaveInstanceState()
is a method used to store data before pausing the activity.Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.
onRestoreInstanceState()
is method used to retrieve that data back.Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).
Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause()
method of Activity as a bundle & in onResume()
method call the onRestoreInstanceState()
method .
Please see :
How to use onSavedInstanceState example please
http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/
Here's all the exception assertions you can do. Note that all of them are optional.
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
// make your exception assertions
$this->expectException(InvalidArgumentException::class);
// if you use namespaces:
// $this->expectException('\Namespace\MyExceptio??n');
$this->expectExceptionMessage('message');
$this->expectExceptionMessageRegExp('/essage$/');
$this->expectExceptionCode(123);
// code that throws an exception
throw new InvalidArgumentException('message', 123);
}
public function testAnotherException()
{
// repeat as needed
$this->expectException(Exception::class);
throw new Exception('Oh no!');
}
}
Documentation can be found here.
You're looking for the .filter()
function:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
});
That'll produce an array that contains only those objects whose "selected" property is true
(or truthy).
edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
}).map(function(obj) { return obj.id; });
Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck()
function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.
This is a right answer. you need to import FormsMoudle
first in app.module.ts
**
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
FormsModule,
ReactiveFormsModule ,
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
** second in app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
Best regards and hope will be helpfull
There is a significant different in how jQuery handles the this variable with a "on" method
$("outer DOM element").on('click',"inner DOM element",function(){
$(this) // refers to the "inner DOM element"
})
If you compare this with :-
$("outer DOM element").click(function(){
$(this) // refers to the "outer DOM element"
})
Given other answers are a few years old, currently here are my thoughts that may be helpful:
Simplest way
private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
var client = new HttpClient();
var response = await client.PostAsync(uri, dataOut);
return await response.Content.ReadAsStringAsync();
// For non strings you can use other Content.ReadAs...() method variations
}
A More Practical Example
Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as:
public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var results = await PostAsync(uri, content); // from previous block of code
return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}
An example of how this could be called:
var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);
Try this one:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
return false;
});
The very simplest way would be to run Eclipse CDT on the Linux Box and use either X11-Forwarding or remote desktop software such as VNC.
This, of course, is only possible when you Eclipse is present on the Linux box and your network connection to the box is sufficiently fast.
The advantage is that, due to everything being local, you won't have synchronization issues, and you don't get any awkward cross-platform issues.
If you have no eclipse on the box, you could thinking of sharing your linux working directory via SMB (or SSHFS) and access it from your windows machine, but that would require quite some setup.
Both would be better than having two copies, especially when it's cross-platform.
Found following solution working for my similar problem:
private ExtendedHashMap mData = new ExtendedHashMap();
private String[] mKeys;
public void setNewData(ExtendedHashMap data) {
mData.putAll(data);
mKeys = data.keySet().toArray(new String[data.size()]);
notifyDataSetChanged();
}
Using the clear-command
mData.clear()
is not nessescary
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/
You're just trying to concatenate the two byte
arrays?
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < one.length ? one[i] : two[i - one.length];
}
Or you could use System.arraycopy
:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
System.arraycopy(one,0,combined,0 ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);
Or you could just use a List
to do the work:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));
byte[] combined = list.toArray(new byte[list.size()]);
Or you could simply use ByteBuffer
with the advantage of adding many arrays.
byte[] allByteArray = new byte[one.length + two.length + three.length];
ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);
byte[] combined = buff.array();
This will list all certificates:
keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts"
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload
at the end of your <body>
tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
This is to remove double quotes in a string.
str1 = str.replace(/"/g, "");
alert(str1);
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
Kotlin
data class Player(val name : String, val surname: String)
val json = [
{
"name": "name 1",
"surname": "surname 1"
},
{
"name": "name 2",
"surname": "surname 2"
},
{
"name": "name 3",
"surname": "surname 3"
}
]
val typeToken = object : TypeToken<List<Player>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)
OR
val playerArray = Gson().fromJson(json, Array<Player>::class.java)
You need to clone in ssh not in https.
For that you need to set your ssh keys. I have prepared this little script that automates this:
#!/usr/bin/env bash
email="$1"
hostname="$2"
hostalias="$hostname"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t rsa -C $email -f $keypath
if [ $? -eq 0 ]; then
cat >> ~/.ssh/config <<EOF
Host $hostalias
Hostname $hostname *.$hostname
User git
IdentitiesOnly yes
IdentityFile $keypath
EOF
fi
and run it like
bash script.sh [email protected] github.com
Change your remote url
git remote set-url origin [email protected]:user/foo.git
Add content of ~/.ssh/github.com_rsa.pub
to your ssh keys on github.com
Check connection
ssh -T [email protected]
Here is an example:
#include"stdio.h"
#include"conio.h"
void main()
{
int rm, vivek;
clrscr();
printf("Enter any numbers\t(E.g., 1, 2, 5");
scanf("%d", &rm); // rm = 5(0101) << 2 (two step add zero's), so the value is 10100
printf("This left shift value%d=%d", rm, rm<<4);
printf("This right shift value%d=%d", rm, rm>>2);
getch();
}
if adding dependencies haven`t solved your problem, create WAR archive again. In my case, I used obsolete WAR file without security-web and security-conf jars
You could pass a function to the key
parameter to the .sort
method. With this, the system will sort by key(x) instead of x.
list1.sort(key=int)
BTW, to convert the list to integers permanently, use the map
function
list1 = list(map(int, list1)) # you don't need to call list() in Python 2.x
or list comprehension
list1 = [int(x) for x in list1]
For doing this in iOS 7:
[[UINavigationBar appearance] setBarTintColor:myColor];
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
imgDics.setOnClickListener(onPlayer2Click);
anim = new RotateAnimation(0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(4000);
// Start animating the image
imgDics.startAnimation(anim);
(ansible 2.9.6 ansible-lint 4.2.0)
See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string
when: test_myscript.stderr != ""
Correct syntax and also "Ansible Galaxy Warning-Free" option is
when: test_myscript.stderr | length > 0
Quoting from source code
"Use
when: var|length > 0
rather thanwhen: var != ""
(or ' 'converselywhen: var|length == 0
rather thanwhen: var == ""
)"
Notes
- debug:
msg: "Empty string '{{ var }}' evaluates to False"
when: not var
vars:
var: ''
- debug:
msg: "Empty list {{ var }} evaluates to False"
when: not var
vars:
var: []
give
"msg": "Empty string '' evaluates to False"
"msg": "Empty list [] evaluates to False"
ANSIBLE_CONDITIONAL_BARE_VARS=false
the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true
the condition will fail - debug:
msg: "String '{{ var }}' evaluates to True"
when: var
vars:
var: 'abc'
gives
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check 'var' failed. The error was: error while
evaluating conditional (var): 'abc' is undefined
Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'
). When the filter bool
is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true
and ANSIBLE_CONDITIONAL_BARE_VARS=false
have no effect
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var|bool
vars:
var: 'abc'
gives
skipping: [localhost]
- include_tasks: teardown.yml
when: teardown
- include_tasks: provision.yml
when: not teardown
" based on a variable you define as a string (with quotation marks around it):"
In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'
In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'
In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')
"Expect that this setting eventually will be deprecated after 2.12"
You can find the answer here: Is there a minlength validation attribute in HTML5?
Therefore this should do the job:
<input pattern=".{6,6}">
Your response should be something like this to be qualified as Json Array.
{
"songs":[
{"2562862600": {"id":"2562862600", "pos":1}},
{"2562862620": {"id":"2562862620", "pos":1}},
{"2562862604": {"id":"2562862604", "pos":1}},
{"2573433638": {"id":"2573433638", "pos":1}}
]
}
You can parse your response as follows
String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);
JSONArray arr = ob.getJSONArray("songs");
for(int i=0; i<arr.length(); i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o);
}
So it seems that there is no way to reattach a stale detached entity in JPA.
merge()
will push the stale state to the DB,
and overwrite any intervening updates.
refresh()
cannot be called on a detached entity.
lock()
cannot be called on a detached entity,
and even if it could, and it did reattach the entity,
calling 'lock' with argument 'LockMode.NONE'
implying that you are locking, but not locking,
is the most counterintuitive piece of API design I've ever seen.
So you are stuck.
There's an detach()
method, but no attach()
or reattach()
.
An obvious step in the object lifecycle is not available to you.
Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.
It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.
Mik
You can find standard sizes for everything in Google's style guide.
Here are the values they use for for buttons:
Buttons
English: Medium 14sp, all caps
Dense: Medium 15sp, all caps
Tall: Bold 15sp
I would like to add my solution to get reliable statistics on how many real users visit my site with javascript disabled over the total users. The check is done one time only per session with these benefits:
My code uses PHP, mysql and jquery with ajax but could be adapted to other languanges:
Create a table in your DB like this one:
CREATE TABLE IF NOT EXISTS `log_JS` (
`logJS_id` int(11) NOT NULL AUTO_INCREMENT,
`data_ins` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`session_id` varchar(50) NOT NULL,
`JS_ON` tinyint(1) NOT NULL DEFAULT '0',
`agent` varchar(255) DEFAULT NULL,
PRIMARY KEY (`logJS_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Add this to every page after using session_start() or equivalent (jquery required):
<? if (!isset($_SESSION["JSTest"]))
{
mysql_query("INSERT INTO log_JS (session_id, agent) VALUES ('" . mysql_real_escape_string(session_id()) . "', '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']). "')");
$_SESSION["JSTest"] = 1; // One time per session
?>
<script type="text/javascript">
$(document).ready(function() { $.get('JSOK.php'); });
</script>
<?
}
?>
Create the page JSOK.php like this:
<?
include_once("[DB connection file].php");
mysql_query("UPDATE log_JS SET JS_ON = 1 WHERE session_id = '" . mysql_real_escape_string(session_id()) . "'");
Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.
Go to where your R program is installed. This is referred to as R_Home
in the literature. Once you find it, go to the /etc subdirectory.
C:\R\R-2.10.1\etc
Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:
# my custom library path
.libPaths("C:/R/library")
(The comment added to keep track of what I did to the file.)
In R, typing the .libPaths()
function yields the first target at C:/R/Library
NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.
The main difference is fairness, in other words are requests handled FIFO or can there be barging? Method level synchronization ensures fair or FIFO allocation of the lock. Using
synchronized(foo) {
}
or
lock.acquire(); .....lock.release();
does not assure fairness.
If you have lots of contention for the lock you can easily encounter barging where newer requests get the lock and older requests get stuck. I've seen cases where 200 threads arrive in short order for a lock and the 2nd one to arrive got processed last. This is ok for some applications but for others it's deadly.
See Brian Goetz's "Java Concurrency In Practice" book, section 13.3 for a full discussion of this topic.
The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
output
Array
(
[0] => 42S02
[1] => -204
[2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N "DANIELS.BONES" is an undefined name. SQLSTATE=42704
)
For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:
class DropTables < ActiveRecord::Migration
def up
drop_table :table_you_dont_want
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.
Date myDate = new Date();
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
Date dt = sm.parse(strDate);
System.out.println(strDate);
At first glance, your code will not compile. Since the nested if statement doesn't have any braces, it will consider the next line the code that it should execute. Also, you are comparing a char against a String, " ". Try comparing the values as chars instead. I think the correct syntax would be:
if(c == ' '){
//do something here
}
But then again, I am not familiar with the "Equal"
class
The main difference between Dispose and Finalize is that:
Dispose
is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {}
statement is invented. When your program finishes the execution of the code inside the {}
, it will call Dispose
method automatically.
Finalize
is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.
I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
There are several ways, like:
where some_column is null or some_column = ''
or
where ifnull(some_column, '') = ''
or
where coalesce(some_column, '') = ''
of
where ifnull(length(some_column), 0) = 0
Java doesn't have direct equivalent of C# language feature called async/await, however there's a different approach to the problem that async/await tries to solve. It's called project Loom, which will provide virtual threads for high-throughput concurrency. It will be available in some future version of OpenJDK.
This approach also solves "colored function problem" that async/await has.
Similar feature can be also found in Golang (goroutines).
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block
support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.
In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.
If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/
This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.
Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).
(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)
I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
If you want the counters to begin to increase once the page is loaded, put counter1()
and counter2()
in foo()
before countingSpeed
is called. Otherwise, it takes speed
milliseconds before execution.
EDIT : Shorter answer.
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.
~function () {
function Smooth () {
this.$container = document.querySelector('.levit-container');
this.$placeholder = document.createElement('div');
}
Smooth.prototype.init = function () {
var instance = this;
setContainer.call(instance);
setPlaceholder.call(instance);
bindEvents.call(instance);
}
function bindEvents () {
window.addEventListener('scroll', handleScroll.bind(this), false);
}
function setContainer () {
var style = this.$container.style;
style.position = 'fixed';
style.width = '100%';
style.top = '0';
style.left = '0';
style.transition = '0.5s ease-out';
}
function setPlaceholder () {
var instance = this,
$container = instance.$container,
$placeholder = instance.$placeholder;
$placeholder.setAttribute('class', 'levit-placeholder');
$placeholder.style.height = $container.offsetHeight + 'px';
document.body.insertBefore($placeholder, $container);
}
function handleScroll () {
this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
}
var smooth = new Smooth();
smooth.init();
}();
I suspect you need to use ClientID
rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server"
.
E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):
var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;
If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.
Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
while this worked in both browsers:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.
Your visual basic code would look something like this:
Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")
cmd.Parameters.Add("@query", searchString)
I had to do a lot of settings edits like the previous answers, so I don't know which made it work after a lot of modifications.
Nothing worked until I closed and openen my IDE, but the last three things I did was disable the lonefy.vscode-js-css-html-formatter
, "html.format.enable": true,
and restart Visual Studio.
{
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"workbench.colorTheme": "Default Light+",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features",
"editor.tabSize": 2,
"editor.detectIndentation": false,
"editor.insertSpaces": true
},
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
"editor.tabSize": 2,
"typescript.format.insertSpaceAfterConstructor": true,
"files.autoSave": "afterDelay",
"html.format.indentHandlebars": true,
"html.format.indentInnerHtml": true,
"html.format.enable": true,
"editor.detectIndentation": false,
"editor.insertSpaces": true,
}
You can use the keyword IDENTITY
as the data type to the column along with PRIMARY KEY
constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
You can Use sender argument
@IBAction func TickToeButtonClick(sender: AnyObject) {
sender.setTitle("my text here", forState: .normal)
}
If you are using JQuery dataTable so you need to just add "bFilter":true
. This will display default search box outside table and its works dynamically..as per expected
$("#archivedAssignments").dataTable({
"sPaginationType": "full_numbers",
"bFilter":true,
"sPageFirst": false,
"sPageLast": false,
"oLanguage": {
"oPaginate": {
"sPrevious": "<< previous",
"sNext" : "Next >>",
"sFirst": "<<",
"sLast": ">>"
}
},
"bJQueryUI": false,
"bLengthChange": false,
"bInfo":false,
"bSortable":true
});
To quote an official document, the Java Cryptography Architecture guide says this about char[]
vs. String
passwords (about password-based encryption, but this is more generally about passwords of course):
It would seem logical to collect and store the password in an object of type
java.lang.String
. However, here's the caveat:Object
s of typeString
are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of aString
after usage. This feature makesString
objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in achar
array instead.
Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):
Guideline 2-2: Do not log highly sensitive information
Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.
This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.
In my case sleep
created side effect so I used wait
let _ = XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)
Try one of these two methods:
string get_file_string(){
std::ifstream ifs("path_to_file");
return string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
}
string get_file_string2(){
ifstream inFile;
inFile.open("path_to_file");//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
return strStream.str();//str holds the content of the file
}
kubectl run
= kubectl create deployment
kubectl create -f your-object-config.yaml
kubectl delete -f your-object-config.yaml
kubectl replace -f your-object-config.yaml
kubectl diff -f configs/
kubectl apply -f configs/
#visibilityOfElementLocated
None of the answers using isDisplayed
or similar are correct. They only check if the display
property is not none
, not if the element can actually be seen! Selenium had a bunch of static utility methods added in the ExpectedConditions
class. Two of them can be used in this case:
Usage
@Test
// visibilityOfElementLocated has been statically imported
public demo(){
By searchButtonSelector = By.className("search_button");
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(homeUrl);
WebElement searchButton = wait.until(
visibilityOfElementLocated
(searchButtonSelector));
//clicks the search button
searchButton.click();
This was my answer before finding out about the utility methods on ExpectedConditions
. It might still be relevant, as I assume it does more than the method mentioned above, which only checks the element has a height and a width.
In essence: this cannot be answered by Java and the findElementBy*
methods and WebElement#isDisplayed
alone, as they can only tell you if an element exists, not if it is actually visible. The OP hasn't defined what visible means, but it normally entails
opacity
> 0display
property set to something else than none
visibility
prop is set to visible
Most people would also include the requirement that it is actually within the viewport as well (so a person would be able to see it).
For some reason, this quite normal need is not met by the pure Java API, while front-ends to Selenium that builds upon it often implements some variation of isVisible
, which is why I knew this should be possible. And after browsing the source of the Node framework WebDriver.IO I found the source of isVisible
, which is now renamed to the more aptly name of isVisibleInViewport
in the 5.0-beta.
Basically, they implement the custom command as a call that delegates to a javascript that runs on the client and does the actual work! This is the "server" bit:
export default function isDisplayedInViewport () {
return getBrowserObject(this).execute(isDisplayedInViewportScript, {
[ELEMENT_KEY]: this.elementId, // w3c compatible
ELEMENT: this.elementId // jsonwp compatible
})
}
So the interesting bit is the javascript sent to run on the client:
/**
* check if element is visible and within the viewport
* @param {HTMLElement} elem element to check
* @return {Boolean} true if element is within viewport
*/
export default function isDisplayedInViewport (elem) {
const dde = document.documentElement
let isWithinViewport = true
while (elem.parentNode && elem.parentNode.getBoundingClientRect) {
const elemDimension = elem.getBoundingClientRect()
const elemComputedStyle = window.getComputedStyle(elem)
const viewportDimension = {
width: dde.clientWidth,
height: dde.clientHeight
}
isWithinViewport = isWithinViewport &&
(elemComputedStyle.display !== 'none' &&
elemComputedStyle.visibility === 'visible' &&
parseFloat(elemComputedStyle.opacity, 10) > 0 &&
elemDimension.bottom > 0 &&
elemDimension.right > 0 &&
elemDimension.top < viewportDimension.height &&
elemDimension.left < viewportDimension.width)
elem = elem.parentNode
}
return isWithinViewport
}
This piece of JS can actually be copied (almost) verbatim into your own codebase (remove export default
and replace const
with var
in case of non-evergreen browsers)! To use it, read it from File
into a String
that can be sent by Selenium for running on the client.
Another interesting and related script that might be worth looking into is selectByVisibleText.
If you haven't executed JS using Selenium before you could have a small peek into this or browse the JavaScriptExecutor API.
Usually, try to always use non-blocking async scripts (meaning #executeAsyncScript), but since we already have a synchronous, blocking script we might as well use the normal sync call. The returned object can be many types of Object, so cast approprately. This could be one way of doing it:
/**
* Demo of a java version of webdriverio's isDisplayedInViewport
* https://github.com/webdriverio/webdriverio/blob/v5.0.0-beta.2/packages/webdriverio/src/commands/element/isDisplayedInViewport.js
* The super class GuiTest just deals with setup of the driver and such
*/
class VisibleDemoTest extends GuiTest {
public static String readScript(String name) {
try {
File f = new File("selenium-scripts/" + name + ".js");
BufferedReader reader = new BufferedReader( new FileReader( file ) );
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch(IOError e){
throw new RuntimeError("No such Selenium script: " + f.getAbsolutePath());
}
}
public static Boolean isVisibleInViewport(RemoteElement e){
// according to the Webdriver spec a string that identifies an element
// should be deserialized into the corresponding web element,
// meaning the 'isDisplayedInViewport' function should receive the element,
// not just the string we passed to it originally - how this is done is not our concern
//
// This is probably when ELEMENT and ELEMENT_KEY refers to in the wd.io implementation
//
// Ref https://w3c.github.io/webdriver/#dfn-json-deserialize
return js.executeScript(readScript("isDisplayedInViewport"), e.getId());
}
public static Boolean isVisibleInViewport(String xPath){
driver().findElementByXPath("//button[@id='should_be_visible']");
}
@Test
public demo_isVisibleInViewport(){
// you can build all kinds of abstractions on top of the base method
// to make it more Selenium-ish using retries with timeouts, etc
assertTrue(isVisibleInViewport("//button[@id='should_be_visible']"));
assertFalse(isVisibleInViewport("//button[@id='should_be_hidden']"));
}
}
You don't need jquery inside the iframe to do this, but I use it cause the code is so much simpler...
Put this in the document inside your iframe.
$(document).ready(function() {
parent.set_size(this.body.offsetHeight + 5 + "px");
});
added five above to eliminate scrollbar on small windows, it's never perfect on size.
And this inside your parent document.
function set_size(ht)
{
$("#iframeId").css('height',ht);
}
On Windows with Python v3.6.5
py -m pip install requests
Open Android Studio -> Open Manifest File
add
<uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>
don't forget to include xmlns:tools="http://schemas.android.com/tools"
too, before the <application>
tag
Here is an IFrame solution that works for IE and Chrome:
function printHTML(htmlString) {
var newIframe = document.createElement('iframe');
newIframe.width = '1px';
newIframe.height = '1px';
newIframe.src = 'about:blank';
// for IE wait for the IFrame to load so we can access contentWindow.document.body
newIframe.onload = function() {
var script_tag = newIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
script_tag.appendChild(script);
newIframe.contentWindow.document.body.innerHTML = htmlString;
newIframe.contentWindow.document.body.appendChild(script_tag);
// for chrome, a timeout for loading large amounts of content
setTimeout(function() {
newIframe.contentWindow.Print();
newIframe.contentWindow.document.body.removeChild(script_tag);
newIframe.parentElement.removeChild(newIframe);
}, 200);
};
document.body.appendChild(newIframe);
}
There is a solution that requires no non-standard modules and is 100% transportable
import thread
def input_thread(a_list):
raw_input()
a_list.append(True)
def do_stuff():
a_list = []
thread.start_new_thread(input_thread, (a_list,))
while not a_list:
stuff()
declare @xx int
set @xx = 3
select @xx
select @xx * 2 -- yields another integer
select @xx/1 -- same
select @xx/1.0 --yields 6 decimal places
select @xx/1.00 -- 6
select @xx * 1.0 -- 1 decimal place - victory
select @xx * 1.00 -- 2 places - hooray
Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.
To file under both 'established' and 'key-value store': Berkeley DB.
Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).
Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.
Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/
Basically, you can set your image path in config.rb and you use the image-url() helper
I think the previous answers are correct, but here is another example (just a f.y.i, success() and error() are deprecated according to AngularJS Main page:
$http
.get('http://someendpoint/maybe/returns/JSON')
.then(function(response) {
return response.data;
}).catch(function(e) {
console.log('Error: ', e);
throw e;
}).finally(function() {
console.log('This finally block');
});
This worked for me
EditText etname = (EditText) findViewById(R.id.etname);
if(etname.length() == 0){
etname.setError("Required field");
}else{
Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
}
or Use this for strings
String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}
There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId
. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear()
method. But the best way is to set another irrelevant object (usually null
value) in the session in correspondance to a key. For example, to nullify Session["FirstName"]
, simply set it to Session["FirstName"] = null
.
just set data-trigger="focus click"
Try this:
.row > .span3 {
display: inline-block !important;
vertical-align: middle !important;
}
Fiddle: http://jsfiddle.net/EexYE/
You may need to add Diego's float: none !important;
also if span3 is floating and it interferes.
Fiddle: http://jsfiddle.net/D8McR/
In response to Alberto: if you fix the height of the row div, then to continue the vertical center alignment you'll need to set the line-height of the row to be the same as the pixel height of the row (ie. both to 300px in your case). If you'll do that you will notice that the child elements inherit the line-height, which is a problem in this case, so you will then need to set your line height for the span3s to whatever it should actually be (1.5 is the example value in the fiddle, or 1.5 x the font-size, which we did not change when we changed the line-height).
If you're trying to put a button in a rounded-rectangle border, you should check out msdn's example. I found this by googling for images of the problem (instead of text). Their bulky outer rectangle is (thankfully) easy to remove.
Note that you will have to redefine the button's behavior (since you've changed the ControlTemplate). That is, you will need to define the button's behavior when clicked using a Trigger tag (Property="IsPressed" Value="true") in the ControlTemplate.Triggers tag. Hope this saves someone else the time I lost :)
Add the following to your app build.gradle and select the specified release build variant and run
signingConfigs {
config {
keyAlias 'keyalias'
keyPassword 'keypwd'
storeFile file('<<KEYSTORE-PATH>>.keystore')
storePassword 'pwd'
}
}
buildTypes {
release {
debuggable true
signingConfig signingConfigs.config
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):
max_allowed_packet
from 1M to 4M (You may need to experiment with this value.)The database imported successfully after that.
Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).
You can combine "scroll" and "scrollstop" events in order to achieve desired result:
$(window).on("scroll",function(){
$('nav').addClass('shrink');
});
$(window).on("scrollstop",function(){
$('nav').removeClass('shrink');
});
So i tried all the suggested solutions to no avail. All i did was to set run the app from the server and it displayed the error in full, this should have worked when i set customErrors mode to false but it didn't. The moment i browsed the API form the server i was able to see the problem.
Normally setting axis limit @ max of your variable is enough
a <- c(0:1000000)
b <- c(0:1000000)
plot(a, b, ylim = c(0, max(b)))
It's usually based on significant figures of both the exponent and significand in base 2, not base 10. From what I can tell in the C99 standard, however, there is no specified precision for floats and doubles (other than the fact that 1 and 1 + 1E-5
/ 1 + 1E-7
are distinguishable [float
and double
repsectively]). However, the number of significant figures is left to the implementer (as well as which base they use internally, so in other words, an implementation could decide to make it based on 18 digits of precision in base 3). [1]
If you need to know these values, the constants FLT_RADIX
and FLT_MANT_DIG
(and DBL_MANT_DIG
/ LDBL_MANT_DIG
) are defined in float.h.
The reason it's called a double
is because the number of bytes used to store it is double the number of a float (but this includes both the exponent and significand). The IEEE 754 standard (used by most compilers) allocate relatively more bits for the significand than the exponent (23 to 9 for float
vs. 52 to 12 for double
), which is why the precision is more than doubled.
1: Section 5.2.4.2.2 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf )
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);
If you need an independent environment for your project: Install your environment to your project folder using the --prefix option:
conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3
In VSCode launch.json configuration set your "pythonPath" to:
"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"
Those seem to be MySQL data types.
According to the documentation they take:
tinyint
= 1 bytesmallint
= 2 bytesmediumint
= 3 bytesint
= 4 bytesbigint
= 8 bytesAnd, naturally, accept increasingly larger ranges of numbers.
Try in Swift, don't update the tintColor
if you have some design for your UIBarButtonItem like font size in AppDelegate, it will totally change the appearance of your button when showing up.
In case of a text button, changing title can let your button 'disappear'.
if WANT_TO_SHOW {
myBarButtonItem.enabled = true
myBarButtonItem.title = "BUTTON_NAME"
}else{
myBarButtonItem.enabled = false
myBarButtonItem.title = ""
}
You can use xxd
:
$cat hex.txt
68 65 6c 6c 6f
$cat hex.txt | xxd -r -p
hello
Use fs.writeFileSync inside the try/catch block as below.
`var fs = require('fs');
try {
const file = fs.writeFileSync(ASIN + '.json', JSON.stringify(results))
console.log("JSON saved");
return results;
} catch (error) {
console.log(err);
}`
I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.