You can use ~/img/myImage.png
instead of ../img/myImage.png
to avoid this error in ASP.NET pages.
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.
double a;
a=3669.0;
int b;
b=a+ 1e-9;
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'
Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1
argument.
Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)
You config proxy settings for some network and now you connect another network. Now have to remove the proxy settings. For that use these commands:
git config --global --unset https.proxy
git config --global --unset http.proxy
Now you can push too. (If did not remove proxy configuration still you can use git commands like add , commit and etc)
In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.
add this to your stylesheet. line-height should match the height of your logo
.navbar-nav li a {
line-height: 50px;
}
Check out the fiddle at: http://jsfiddle.net/nD4tW/
Changing in my package.json file "start": "export PORT=3001 && react-scripts start"
worked for me too and I'm on macOS 10.13.4
If you are using something like this.
Response.Write("Hello \r\n")
Response.Write("World \r\n")
and the output is
Hello\r\nWorld\r\n
Then you are basically looking for something like this
Response.Write("Hello <br/>")
Response.Write("World <br/>")
This will output
Hello
World
you can also just define "<br />" as constant and reuse it
eg.
Public Const HtmlNewLine as string ="<br />"
Response.Write("Hello " & HtmlNewLine)
Response.Write("World " & HtmlNewLine)
Just a few more notes on this topic based on my recent experiences. The university I work for issues laptops with IE 8 set to compatibility mode for all Intranet Sites. I tried adding the meta tag to disable this mode for pages being served up by my site but IE consistently ignored this tag. As Lance mentioned in his post, adding a response header fixed this issue. This is how I set the header based on the HTML5 boilerplate method:
<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge,chrome=1"
# mod_headers can't match by content-type, but we don't want to send this header on *everything*...
<FilesMatch "\.(appcache|crx|css|eot|gif|htc|ico|jpe?g|js|m4a|m4v|manifest|mp4|oex|oga|ogg|ogv|otf|pdf|png|safariextz|svg|svgz|ttf|vcf|webm|webp|woff|xml|xpi)$">
Header unset X-UA-Compatible
</FilesMatch>
</IfModule>
In order for this header to actually be sent, you have to make sure you have mod_headers turned on in Apache. If you want to make sure you have this mod turned on, put this in a page that can run php:
<pre>
<?php
print_r(apache_get_modules());
?>
</pre>
have you tried SQL> alter database open; ? after first login?
According to this MDN documentation, an element's offsetParent
property will return null
whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have no position: fixed;
elements on your page, might look like:
// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
return (el.offsetParent === null)
}
On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle()
. The function in that case might be:
// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
var style = window.getComputedStyle(el);
return (style.display === 'none')
}
Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.
You can use the following line
Collections.sort(listOfCountryNames, String.CASE_INSENSITIVE_ORDER)
It is similar to the suggestion of Thilo, but will not make a difference between upper and lowercase characters.
Just a note...
If you add that code to setclasspath.bat or setclasspath.sh, it will actually be used by all of Tomcat's scripts you could run, rather than just Catalina.
The method for setting the variable is as the other's have described.
It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:
unspecified
emailAddress
– e.g. [email protected]
X509SubjectName
– e.g. CN=john,O=Company Ltd.,C=US
WindowsDomainQualifiedName
– e.g. CompanyDomain\John
kerberos
– e.g. john@realm
entity
– this one in used to identify entities that provide SAML-based services and looks like a URIpersistent
– this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.transient
– opaque identifier which should be treated as temporary.An awk
code based on RS
.
awk '1' RS=',\n' file
or:
awk 'BEGIN{RS=",\n"}1' file
This last example will be valid for any char before newline:
awk '1' RS='.\n' file
Note: dot .
matches any character except line breaks.
Explanation
awk
allows us to use different record (line) regex
separators, we just need to include the comma before the line break (or dot
for any char) in the one used for the input
, the RS
.
Note: what that 1
means?
Short answer, It's just a shortcut to avoid using the print
statement.
In awk
when a condition gets matched the default action is to print the input line, example:
$ echo "test" |awk '1'
test
That's because 1
will be always true, so this expression is equivalent to:
$ echo "test"|awk '1==1'
test
$ echo "test"|awk '{if (1==1){print}}'
test
Documentation
Check Record Splitting with Standard awk and Output Separators.
Here is a video about Debugging with eclipse.
For more details read this page.
Instead of Debugging as Java program, use Debug as Android Application
May help new comers.
You can use this
char name[20];
scanf("%20[^\n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("\n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^\n]", variable);
}
char name[20];
getText("Your name", name, 20);
$(document).ready(function() {
$('#media').carousel({
pause: true,
interval: 40000,
});
});
By using the above script, you will be able to move the images automaticaly
$(document).ready(function() {
$('#media').carousel({
pause: true,
interval: false,
});
});
By using the above script, auto-rotation
will be blocked because interval
is false
you mean getiing sum(Amount of all types) for each property where EndDate is null:
SELECT propertyId, SUM(Amount) as TOTAL_COSTS
FROM MyTable
WHERE EndDate IS NULL
GROUP BY propertyId
Just found out the hard way that it is
SELECT 1 FROM DUAL
for MaxDB as well.
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
I'll answer for Windows guests. If you have VMware Tools installed, then the taskbar's notification area (near the clock) has an icon for VMware Tools. Double-click that and set your options.
If you don't have VMware Tools installed, you can still set the clock's option for internet time to sync with some NTP server. If your physical machine serves the NTP protocol to your guest machines then you can get that done with host-only networking. Otherwise you'll have to let your guests sync with a genuine NTP server out on the internet, for example time.windows.com.
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader
for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable
as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;
To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.
The R packages geosphere will calculate bearingRhumb, which is a constant bearing line given an origin point and easting/northing. The easting and northing must be in a matrix or vector. The origin point for a wind rose is 0,0. The following code seems to readily resolve the issue:
windE<-wind$uasE
windN<-wind$vasN
wind_matrix<-cbind(windE, windN)
wind$wind_dir<-bearingRhumb(c(0,0), wind_matrix)
wind$wind_dir<-round(wind$wind_dir, 0)
THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
I used to get this error after updating the connector jar, issue resolved.
Try forcing updates using the mvn cpu
option:
usage: mvn [options] [<goal(s)>] [<phase(s)>]
Options:
-cpu,--check-plugin-updates Force upToDate check for any
relevant registered plugins
Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.
$('#btn').click(function() {
$('#wizard').toggle();
});
Refer to the JQuery website for more information.
This can also be done without JQuery. Using only standard JavaScript:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
Then add onclick="toggle_visibility('id_of_element_to_toggle');"
to the button that is used to show and hide the div.
You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.
public interface Application {
public String myFunction(String abc);
}
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
(function ($) {
$(document).ready(function(){
$("#myspan").text("This is span");
});
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>
_x000D_
user text()
to change span text.
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
| TIMESTAMP | DATETIME |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
| TIMESTAMP requires 4 bytes. | DATETIME requires 8 bytes. |
| Timestamp is the number of seconds that have elapsed since January 1, 1970 00:00 UTC. | DATETIME is a text displays 'YYYY-MM-DD HH:MM:SS' format. |
| TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC. | DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59' |
| TIMESTAMP during retrieval converted back to the current time zone. | DATETIME can not do this. |
| TIMESTAMP is used mostly for metadata i.e. row created/modified and audit purpose. | DATETIME is used mostly for user-data. |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
str.toCharArray().length
should work.
Or how about:
str.lastIndexOf("")
Probably even runs in constant time :)
Another one
Matcher m = Pattern.compile("$").matcher(str);
m.find();
int length = m.end();
One of the dumbest solutions: str.split("").length - 1
Is this cheating: new StringBuilder(str).length()
? :-)
I needed to make report for a catering firm which serves lunches for various clients. In other words, catering may have on or more firms which take orders from catering, and it must know how many lunches it must produce every single day for all it's clients !
Just to notice, I didn't use sorting, in order not to over complicate this example.
This is my code :
@Test
public void test_2() throws Exception {
Firm catering = DS.firm().get(1);
LocalDateTime ldtFrom = LocalDateTime.of(2017, Month.JANUARY, 1, 0, 0);
LocalDateTime ldtTo = LocalDateTime.of(2017, Month.MAY, 2, 0, 0);
Date dFrom = Date.from(ldtFrom.atZone(ZoneId.systemDefault()).toInstant());
Date dTo = Date.from(ldtTo.atZone(ZoneId.systemDefault()).toInstant());
List<PersonOrders> LON = DS.firm().getAllOrders(catering, dFrom, dTo, false);
Map<Object, Long> M = LON.stream().collect(
Collectors.groupingBy(p
-> Arrays.asList(p.getDatum(), p.getPerson().getIdfirm(), p.getIdProduct()),
Collectors.counting()));
for (Map.Entry<Object, Long> e : M.entrySet()) {
Object key = e.getKey();
Long value = e.getValue();
System.err.println(String.format("Client firm :%s, total: %d", key, value));
}
}
tail -f admin.log|grep -v -E '(Nopaging the limit is|keyword to remove is)'
You can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left
) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width
see: Canvas width and height in HTML5).
Example: http://jsfiddle.net/sierawski/4xezb7nL/
Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
Data as factor can be used as input to the plot function.
An answer to a similar question has been given here: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html
x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),
50, replace=T)
x=as.factor(x)
plot(x)
Need for Virtual Function explained [Easy to understand]
#include<iostream>
using namespace std;
class A{
public:
void show(){
cout << " Hello from Class A";
}
};
class B :public A{
public:
void show(){
cout << " Hello from Class B";
}
};
int main(){
A *a1 = new B; // Create a base class pointer and assign address of derived object.
a1->show();
}
Output will be:
Hello from Class A.
But with virtual function:
#include<iostream>
using namespace std;
class A{
public:
virtual void show(){
cout << " Hello from Class A";
}
};
class B :public A{
public:
virtual void show(){
cout << " Hello from Class B";
}
};
int main(){
A *a1 = new B;
a1->show();
}
Output will be:
Hello from Class B.
Hence with virtual function you can achieve runtime polymorphism.
Old question but heck, the simplest solution is:
You need to place google-services.json
into app/
dir. And for each build type, there should be accordant director in
app/src
folder.
For example, if you have release and debug:
app/google-services.json
app/src/debug/google-services.json
In all google-services.json files you should specify correct package_name
according to build type.
For example, inside debug dir it should be like {com.myapp}.debug
To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.
UITableViewAutomaticDimension
to rowHeight & estimatedRowHeightheightForRowAt
and return a value UITableViewAutomaticDimension
to it)-
Objective C:
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Swift:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
For label instance in UITableviewCell
Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.
You can send some flag to stop while loop in server
for example
import socket
s = socket.socket()
s.bind(("localhost", 5000))
s.listen(1)
c,a = s.accept()
filetodown = open("img.png", "wb")
while True:
print("Receiving....")
data = c.recv(1024)
if data == b"DONE":
print("Done Receiving.")
break
filetodown.write(data)
filetodown.close()
c.send("Thank you for connecting.")
c.shutdown(2)
c.close()
s.close()
#Done :)
import socket
s = socket.socket()
s.connect(("localhost", 5000))
filetosend = open("img.png", "rb")
data = filetosend.read(1024)
while data:
print("Sending...")
s.send(data)
data = filetosend.read(1024)
filetosend.close()
s.send(b"DONE")
print("Done Sending.")
print(s.recv(1024))
s.shutdown(2)
s.close()
#Done :)
Apple has changed the rules on this. I read through all the Apple docs and as many of the US export regs as I could find.
My view on this was until recently even using HTTPS for most apps meant Apple would require the export certificate. Some apps such as banking would be OK but for many apps they did not fall into the excempt category which is very, very broad.
However Apple has now introduced a getout under the exempt category for apps that JUST use https. I do not know when they did this but I think it was either Dec 2016 or Jan 2017. We are now submitting our apps without the certificate from the US Govt.
To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir();
to get the allowed directory for the app.
Or:
getCashDir();
<-- should work
context.getCashDir();
(if in a broadcast receiver)
getDataDir();
<--Api 24
The accepted answer still works but now we have an ECMAScript 6 native method [Array.find][1]
to achieve the same effect.
Quoting MDN:
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
var arr = [];
var item = {
id: '21',
step: 'step2',
label: 'Banana',
price: '19$'
};
arr.push(item);
/* note : data is the actual object that matched search criteria
or undefined if nothing matched */
var data = arr.find( function( ele ) {
return ele.id === '21';
} );
if( data ) {
console.log( 'found' );
console.log(data); // This is entire object i.e. `item` not boolean
}
See my jsfiddle link There is a polyfill for IE provided by mozilla
var accounting = [];
var employees = {};
for(var i in someData) {
var item = someData[i];
accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
employees.accounting = accounting;
Just simply go to res/values/styles.xml file and edit the xml file to change the color of xml file .Here is the sample code
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
// below code is for changing the color of action bar
<item name="colorPrimary">"type your color code here. eg:#ffffff"</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
Hope it will help you...
In a one to many and many to one relationship this error will occur. If you attempt to devote same instance from many to one entity to more than one instance from one to many entity.
For example, each person can have many books but each of these books can be owned by only one person if you consider more than one owner for a book this issue is raised.
Mutual Exclusion. Here's the Wikipedia entry on it.
The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.
Specific details of how this is accomplished obviously varies greatly by programming language.
I know this is an old question however for me it worked by actually using an empty paragraph with margins:
<p class="" style="margin: 4px;"></p>
Increasing or decreasing the margin size will increase or decrease the distance between elements just like a border would do but adjustable.
On top of that, it is browser compatible.
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f: #lines count
for line in f:
num_lines += 1
num_lines_input = int (input("Enter line numbers: "))
if num_lines_input <= num_lines:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
else:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
print("Don't have", num_lines_input, " lines print as much as you can")
print("Total lines in the text",num_lines)
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;
It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload
event measure how much time passed until that event was triggered, and divide this time in the image file size.
Example can be found here: Calculate speed using javascript
Test case applying the fix suggested there:
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!_x000D_
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; _x000D_
var downloadSize = 4995374; //bytes_x000D_
_x000D_
function ShowProgressMessage(msg) {_x000D_
if (console) {_x000D_
if (typeof msg == "string") {_x000D_
console.log(msg);_x000D_
} else {_x000D_
for (var i = 0; i < msg.length; i++) {_x000D_
console.log(msg[i]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var oProgress = document.getElementById("progress");_x000D_
if (oProgress) {_x000D_
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");_x000D_
oProgress.innerHTML = actualHTML;_x000D_
}_x000D_
}_x000D_
_x000D_
function InitiateSpeedDetection() {_x000D_
ShowProgressMessage("Loading the image, please wait...");_x000D_
window.setTimeout(MeasureConnectionSpeed, 1);_x000D_
}; _x000D_
_x000D_
if (window.addEventListener) {_x000D_
window.addEventListener('load', InitiateSpeedDetection, false);_x000D_
} else if (window.attachEvent) {_x000D_
window.attachEvent('onload', InitiateSpeedDetection);_x000D_
}_x000D_
_x000D_
function MeasureConnectionSpeed() {_x000D_
var startTime, endTime;_x000D_
var download = new Image();_x000D_
download.onload = function () {_x000D_
endTime = (new Date()).getTime();_x000D_
showResults();_x000D_
}_x000D_
_x000D_
download.onerror = function (err, msg) {_x000D_
ShowProgressMessage("Invalid image, or error downloading");_x000D_
}_x000D_
_x000D_
startTime = (new Date()).getTime();_x000D_
var cacheBuster = "?nnn=" + startTime;_x000D_
download.src = imageAddr + cacheBuster;_x000D_
_x000D_
function showResults() {_x000D_
var duration = (endTime - startTime) / 1000;_x000D_
var bitsLoaded = downloadSize * 8;_x000D_
var speedBps = (bitsLoaded / duration).toFixed(2);_x000D_
var speedKbps = (speedBps / 1024).toFixed(2);_x000D_
var speedMbps = (speedKbps / 1024).toFixed(2);_x000D_
ShowProgressMessage([_x000D_
"Your connection speed is:", _x000D_
speedBps + " bps", _x000D_
speedKbps + " kbps", _x000D_
speedMbps + " Mbps"_x000D_
]);_x000D_
}_x000D_
}
_x000D_
<h1 id="progress">JavaScript is turned off, or your browser is realllllly slow</h1>
_x000D_
Quick comparison with "real" speed test service showed small difference of 0.12 Mbps when using big picture.
To ensure the integrity of the test, you can run the code with Chrome dev tool throttling enabled and then see if the result matches the limitation. (credit goes to user284130 :))
Important things to keep in mind:
The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me)
The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself. (thanks orcaman for pointing this out))
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
Just steer clear of nested loops (O(n^2)), and .indexOf()
(+O(n)).
function merge(a, b) {
var hash = {};
var i;
for (i = 0; i < a.length; i++) {
hash[a[i]] = true;
}
for (i = 0; i < b.length; i++) {
hash[b[i]] = true;
}
return Object.keys(hash);
}
var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = merge(array1, array2);
console.log(array3);
_x000D_
This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.
ssh
returns 255 when an error occurred or 255 is returned by the remote script:
EXIT STATUS
ssh exits with the exit status of the remote command or
with 255 if an error occurred.
Usually you would an error message something similar to:
ssh: connect to host host.domain.com port 22: No route to host
Or
ssh: connect to host HOSTNAME port 22: Connection refused
Check-list:
What happens if you run the ssh command directly from the command line?
Are you able to ping
that machine?
Does the remote has ssh installed?
If installed, then is the ssh service running?
If you want to list the indexes of all the tables in your schema(s) from your program, all the information is on hand in the catalog:
select
n.nspname as "Schema"
,t.relname as "Table"
,c.relname as "Index"
from
pg_catalog.pg_class c
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
join pg_catalog.pg_index i on i.indexrelid = c.oid
join pg_catalog.pg_class t on i.indrelid = t.oid
where
c.relkind = 'i'
and n.nspname not in ('pg_catalog', 'pg_toast')
and pg_catalog.pg_table_is_visible(c.oid)
order by
n.nspname
,t.relname
,c.relname
If you want to delve further (such as columns and ordering), you need to look at pg_catalog.pg_index. Using psql -E [dbname]
comes in handy for figuring out how to query the catalog.
A list comprehension is absolutely the way to do this. Another way that should be faster is map
and itemgetter
.
import operator
new_list = map(operator.itemgetter(1), old_list)
In response to the comment that the OP couldn't find an answer on google, I'll point out a super naive way to do it.
new_list = []
for item in old_list:
new_list.append(item[1])
This uses:
append
method on a list.If somebody is trying to learn a language and can't put together these basic pieces for themselves, then they need to view it as an exercise and do it themselves even if it takes twenty hours.
One needs to learn how to think about what one wants and compare that to the available tools. Every element in my second answer should be covered in a basic tutorial. You cannot learn to program without reading one.
I hacked together another way to do it without having to manipulate list view. Unfortunately, regular Android Animations seem to manipulate the contents of the row, but are ineffectual at actually shrinking the view. So, first consider this handler:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
Bundle bundle = message.getData();
View view = listView.getChildAt(bundle.getInt("viewPosition") -
listView.getFirstVisiblePosition());
int heightToSet;
if(!bundle.containsKey("viewHeight")) {
Rect rect = new Rect();
view.getDrawingRect(rect);
heightToSet = rect.height() - 1;
} else {
heightToSet = bundle.getInt("viewHeight");
}
setViewHeight(view, heightToSet);
if(heightToSet == 1)
return;
Message nextMessage = obtainMessage();
bundle.putInt("viewHeight", (heightToSet - 5 > 0) ? heightToSet - 5 : 1);
nextMessage.setData(bundle);
sendMessage(nextMessage);
}
Add this collection to your List adapter:
private Collection<Integer> disabledViews = new ArrayList<Integer>();
and add
public boolean isEnabled(int position) {
return !disabledViews.contains(position);
}
Next, wherever it is that you want to hide a row, add this:
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("viewPosition", listView.getPositionForView(view));
message.setData(bundle);
handler.sendMessage(message);
disabledViews.add(listView.getPositionForView(view));
That's it! You can change the speed of the animation by altering the number of pixels that it shrinks the height at once. Not real sophisticated, but it works!
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
seeing it in digital circuit domain
so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment
http://jsbin.com/ubalax/1/edit .You can see the results here
body {
position: relative;
float: left;
height: 3000px;
width: 100%;
}
body div {
position: absolute;
height: 100%;
width: 100%;
top:0;
left:0;
background-color: yellow;
}
If you add helper fields to the coordinates table, you can improve response time of the query.
Like this:
CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)
If you're using TokuDB, you'll get even better performance if you add clustering indexes on either of the predicates, for example, like this:
alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);
You'll need the basic lat and lon in degrees as well as sin(lat) in radians, cos(lat)*cos(lon) in radians and cos(lat)*sin(lon) in radians for each point. Then you create a mysql function, smth like this:
CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
`cos_cos1` FLOAT, `cos_sin1` FLOAT,
`sin_lat2` FLOAT,
`cos_cos2` FLOAT, `cos_sin2` FLOAT)
RETURNS float
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
BEGIN
RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
END
This gives you the distance.
Don't forget to add an index on lat/lon so the bounding boxing can help the search instead of slowing it down (the index is already added in the CREATE TABLE query above).
INDEX `lat_lon_idx` (`lat`, `lon`)
Given an old table with only lat/lon coordinates, you can set up a script to update it like this: (php using meekrodb)
$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');
foreach ($users as $user)
{
$lat_rad = deg2rad($user['lat']);
$lon_rad = deg2rad($user['lon']);
DB::replace('Coordinates', array(
'object_id' => $user['id'],
'object_type' => 0,
'sin_lat' => sin($lat_rad),
'cos_cos' => cos($lat_rad)*cos($lon_rad),
'cos_sin' => cos($lat_rad)*sin($lon_rad),
'lat' => $user['lat'],
'lon' => $user['lon']
));
}
Then you optimize the actual query to only do the distance calculation when really needed, for example by bounding the circle (well, oval) from inside and outside. For that, you'll need to precalculate several metrics for the query itself:
// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));
Given those preparations, the query goes something like this (php):
$neighbors = DB::query("SELECT id, type, lat, lon,
geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
FROM Coordinates WHERE
lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
// center radian values: sin_lat, cos_cos, cos_sin
sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
// min_lat, max_lat, min_lon, max_lon for the outside box
$lat-$dist_deg_lat,$lat+$dist_deg_lat,
$lon-$dist_deg_lon,$lon+$dist_deg_lon,
// min_lat, max_lat, min_lon, max_lon for the inside box
$lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
$lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
// distance in radians
$distance_rad);
EXPLAIN on the above query might say that it's not using index unless there's enough results to trigger such. The index will be used when there's enough data in the coordinates table. You can add FORCE INDEX (lat_lon_idx) to the SELECT to make it use the index with no regards to the table size, so you can verify with EXPLAIN that it is working correctly.
With the above code samples you should have a working and scalable implementation of object search by distance with minimal error.
More complete sample from here and here.
Or you can check out my layout sample. p.s no need to put API key in the map view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
/>
<ListView android:id="@+id/nearby_lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_weight="1"
/>
</LinearLayout>
call chooseImage method like-
public void chooseImage(ImageView v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(imageReturnedIntent != null)
{
Uri selectedImage = imageReturnedIntent.getData();
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Bitmap datifoto = null;
temp.setImageBitmap(null);
Uri picUri = null;
picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
if(picUri !=null){
try {
datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
temp.setImageBitmap(datifoto);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (OutOfMemoryError e) {
Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
else
{
//Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
}
}
You can use the ID
field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
Explicit conversion constructors (C++ only)
The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.
class A
{
public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal:
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A( 1 );
.
If you declare the constructor of the class as explicit
, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{
public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements are legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<A>(1);
Java
Java In a Nutshell.
The name is a bit of a misnomer because it's quite thick but it really has everything you need to learn Java.
We can sort the list in one of two ways:
1. Using Comparator : When required to use the sort logic in multiple places If you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places
Collections.sort(arrayList, new Comparator<ActiveAlarm>() {
public int compare(ActiveAlarm o1, ActiveAlarm o2) {
//Sorts by 'TimeStarted' property
return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);
}
//If 'TimeStarted' property is equal sorts by 'TimeEnded' property
public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {
return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;
}
});
We can have null check for the properties, if we could have used 'Long' instead of 'long'.
2. Using Comparable(natural ordering): If sort algorithm always stick to one property: write a class that implements 'Comparable' and override 'compareTo' method as defined below
class ActiveAlarm implements Comparable<ActiveAlarm>{
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
public ActiveAlarm(long timeStarted,long timeEnded) {
this.timeStarted=timeStarted;
this.timeEnded=timeEnded;
}
public long getTimeStarted() {
return timeStarted;
}
public long getTimeEnded() {
return timeEnded;
}
public int compareTo(ActiveAlarm o) {
return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);
}
public int doSecodaryOrderSort(ActiveAlarm o) {
return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;
}
}
call sort method to sort based on natural ordering
Collections.sort(list);
Do not throw an HttpResponseException or return an HttpResponesMessage for errors - except if the intent is to end the request with that exact result.
HttpResponseException's are not handled the same as other exceptions. They are not caught in Exception Filters. They are not caught in the Exception Handler. They are a sly way to slip in an HttpResponseMessage while terminating the current code's execution flow.
Unless the code is infrastructure code relying on this special un-handling, avoid using the HttpResponseException type!
HttpResponseMessage's are not exceptions. They do not terminate the current code's execution flow. They can not be filtered as exceptions. They can not be logged as exceptions. They represent a valid result - even a 500 response is "a valid non-exception response"!
Make life simpler:
When there is an exceptional/error case, go ahead and throw a normal .NET exception - or a customized application exception type (not deriving from HttpResponseException) with desired 'http error/response' properties such as a status code - as per normal exception handling.
Use Exception Filters / Exception Handlers / Exception Loggers to do something appropriate with these exceptional cases: change/add status codes? add tracking identifiers? include stack traces? log?
By avoiding HttpResponseException the 'exceptional case' handling is made uniform and can be handled as part of the exposed pipeline! For example one can turn a 'NotFound' into a 404 and an 'ArgumentException' into a 400 and a 'NullReference' into a 500 easily and uniformly with application-level exceptions - while allowing extensibility to provide "basics" such as error logging.
The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z
Here's the reference
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html
Integer Division
This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.
I'm using a workaround by returning a function with an object of my global variables:
function globalVariables(){
var variables = {
sheetName: 'Sheet1',
variable1: 1,
variable2: 2
};
return variables;
}
function functionThatUsesVariable (){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}
When testing the "ahref" method, I found that the web developer tools of Firefox and Chrome gets confused. I needed to restart the debugging after the a.click() was issued. Same happened with the FileSaver (it uses the same ahref method to actually make the saving). To work around it, I created new temporary window, added the element a into that and clicked it there.
function download_json(dt) {
var csv = ' var data = ';
csv += JSON.stringify(dt, null, 3);
var uricontent = 'data:application/octet-stream,' + encodeURI(csv);
var newwin = window.open( "", "_blank" );
var elem = newwin.document.createElement('a');
elem.download = "database.js";
elem.href = uricontent;
elem.click();
setTimeout(function(){ newwin.close(); }, 3000);
}
Either is fine, though None
is more common as a convention - None
indicates that no value was passed for the optional parameter.
There will be times when "" is the correct default value to use - in my experience, those times occur less often.
Using 'now()' as default value automatically generates time-stamp.
It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.
It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
END LOOP;
END;
/
Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
ORDER BY c.constraint_type)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
END LOOP;
END;
/
I am just re-posting the steps I used from msdn
blog. It may help the community.
This will help you to
setup a local web server known as lite-server with VS Code
, and also guides you to host your static html
files in localhost
and debug
your Javascript
code.
1. Install Node.js
If not already installed, get it here
It comes with npm (the package manager for acquiring and managing your development libraries)
2. Create a new folder for your project
Somewhere in your drive, create a new folder for your web app.
3. Add a package.json file to the project folder
Then copy/paste the following text:
{
"name": "Demo",
"version": "1.0.0",
"description": "demo project.",
"scripts": {
"lite": "lite-server --port 10001",
"start": "npm run lite"
},
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.5.4"
}
}
4. Install the web server
In a terminal window (command prompt in Windows) opened on your project folder, run this command:
npm install
This will install lite-server (defined in package.json), a static server that loads index.html in your default browser and auto refreshes it when application files change.
5. Start the local web server!
(Assuming you have an index.html file in your project folder).
In the same terminal window (command prompt in Windows) run this command:
npm start
Wait a second and index.html is loaded and displayed in your default browser served by your local web server!
lite-server is watching your files and refreshes the page as soon as you make changes to any html, js or css files.
And if you have VS Code configured to auto save (menu File / Auto Save), you see changes in the browser as you type!
Notes:
That’s it. Now before any coding session just type npm start and you are good to go!
Originally posted here in msdn
blog.
Credits goes to Author : @Laurent Duveau
As the error messages stated, ngFor
only supports Iterables such as Array
, so you cannot use it for Object
.
change
private extractData(res: Response) {
let body = <Afdelingen[]>res.json();
return body || {}; // here you are return an object
}
to
private extractData(res: Response) {
let body = <Afdelingen[]>res.json().afdelingen; // return array from json file
return body || []; // also return empty array if there is no data
}
$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});
var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');
$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');
var result = $('#scheduleDate').val();
alert('result: ' + result);
result: 20, April, 2012
Your format syntax is wrong actual syntax is
FORMAT ( value, format [, culture ] )
Please follow this link it helps you
I´m frequently running into this issue on some custom properties that could not be found using IntelliJ IDEA - likely after changing branches.
What helpes in my case is
File -> Invalidate Caches / Restart
I had the assumption that it is more likely a Gradle caching issue than an IDE issue, but ./gradle clean did not help
If you use AndroidX
(as of July 2019)
you may add these:
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="pin"
app:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.MaterialComponents.Light"/>
NOTE! This was tested to work if your Toolbar
is placed directly inside AppBarLayout
but not inside CollapsingToolbarLayout
One Good solution is to restart the PC, this will make the right entry in the Registry of the PC. Restarting solves my problem
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
I have come up with a solution that is relatively accurate at evaluating when the angular initialisation is complete.
The directive is:
.directive('initialisation',['$rootScope',function($rootScope) {
return {
restrict: 'A',
link: function($scope) {
var to;
var listener = $scope.$watch(function() {
clearTimeout(to);
to = setTimeout(function () {
console.log('initialised');
listener();
$rootScope.$broadcast('initialised');
}, 50);
});
}
};
}]);
That can then just be added as an attribute to the body
element and then listened for using $scope.$on('initialised', fn)
It works by assuming that the application is initialised when there are no more $digest cycles. $watch is called every digest cycle and so a timer is started (setTimeout not $timeout so a new digest cycle is not triggered). If a digest cycle does not occur within the timeout then the application is assumed to have initialised.
It is obviously not as accurate as satchmoruns solution (as it is possible a digest cycle takes longer than the timeout) but my solution doesn't need you to keep track of the modules which makes it that much easier to manage (particularly for larger projects). Anyway, seems to be accurate enough for my requirements. Hope it helps.
importlib.import_module
is what you are looking for. It returns the imported module. (Only available for Python >= 2.7 or 3.x):
import importlib
mymodule = importlib.import_module('matplotlib.text')
You can thereafter access anything in the module as mymodule.myclass
, etc.
You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:
Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:
Hope this helps.
Use the ngModelController $asyncValidators
API which handles asynchronous validation, such as making an $http
request to the backend. Functions added to the object must return a promise that must be resolved when valid or rejected when invalid. In-progress async validations are stored by key in ngModelController.$pending
. For more information, see AngularJS Developer Guide - Forms (Custom Validation).
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
For more information, see
$validators
APIThe accepted answer uses the $parsers
and $formatters
pipelines to add a custom synchronous validator. AngularJS 1.3+ added a $validators
API so there is no need to put validators in the $parsers
and $formatters
pipelines:
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$validators.blacklist = function(modelValue, viewValue) {
var blacklist = attr.blacklist.split(',');
var value = modelValue || viewValue;
var valid = blacklist.indexOf(value) === -1;
return valid;
});
}
};
});
For more information, see AngularJS ngModelController API Reference - $validators.
I normally set paths in
~/.bashrc
However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7
and it was sufficient for me.
you can also define multiple java_home's and have only one of them active (rest commented).
suppose in your bashrc file, you have
export JAVA_HOME=......jdk1.7
#export JAVA_HOME=......jdk1.8
notice 1.8 is commented. Once you do
source ~/.bashrc
jdk1.7 will be in path.
you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
The following is adapted from a blog post answering this question that I posted while this question was still closed. Links are to (an HTML copy of) the ECMAScript 3 spec, still the baseline for JavaScript in today's commonly used web browsers.
First, a comment: this kind of expression is never going to show up in any (sane) production environment and is only of any use as an exercise in just how well the reader knows the dirty edges of JavaScript. The general principle that JavaScript operators implicitly convert between types is useful, as are some of the common conversions, but much of the detail in this case is not.
The expression ++[[]][+[]]+[+[]]
may initially look rather imposing and obscure, but is actually relatively easy break down into separate expressions. Below I’ve simply added parentheses for clarity; I can assure you they change nothing, but if you want to verify that then feel free to read up about the grouping operator. So, the expression can be more clearly written as
( ++[[]][+[]] ) + ( [+[]] )
Breaking this down, we can simplify by observing that +[]
evaluates to 0
. To satisfy yourself why this is true, check out the unary + operator and follow the slightly tortuous trail which ends up with ToPrimitive converting the empty array into an empty string, which is then finally converted to 0
by ToNumber. We can now substitute 0
for each instance of +[]
:
( ++[[]][0] ) + [0]
Simpler already. As for ++[[]][0]
, that’s a combination of the prefix increment operator (++
), an array literal defining an array with single element that is itself an empty array ([[]]
) and a property accessor ([0]
) called on the array defined by the array literal.
So, we can simplify [[]][0]
to just []
and we have ++[]
, right? In fact, this is not the case because evaluating ++[]
throws an error, which may initially seem confusing. However, a little thought about the nature of ++
makes this clear: it’s used to increment a variable (e.g. ++i
) or an object property (e.g. ++obj.count
). Not only does it evaluate to a value, it also stores that value somewhere. In the case of ++[]
, it has nowhere to put the new value (whatever it may be) because there is no reference to an object property or variable to update. In spec terms, this is covered by the internal PutValue operation, which is called by the prefix increment operator.
So then, what does ++[[]][0]
do? Well, by similar logic as +[]
, the inner array is converted to 0
and this value is incremented by 1
to give us a final value of 1
. The value of property 0
in the outer array is updated to 1
and the whole expression evaluates to 1
.
This leaves us with
1 + [0]
... which is a simple use of the addition operator. Both operands are first converted to primitives and if either primitive value is a string, string concatenation is performed, otherwise numeric addition is performed. [0]
converts to "0"
, so string concatenation is used, producing "10"
.
As a final aside, something that may not be immediately apparent is that overriding either one of the toString()
or valueOf()
methods of Array.prototype
will change the result of the expression, because both are checked and used if present when converting an object into a primitive value. For example, the following
Array.prototype.toString = function() {
return "foo";
};
++[[]][+[]]+[+[]]
... produces "NaNfoo"
. Why this happens is left as an exercise for the reader...
You can use "iPhone Configuration Utility" to manage provisioning profiles.
Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:
.container {_x000D_
border: 1px solid #DDDDDD;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.tag {_x000D_
float: left;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1000;_x000D_
background-color: #92AD40;_x000D_
padding: 5px;_x000D_
color: #FFFFFF;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="tag">Featured</div>_x000D_
<img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
The key is the container has to be positioned relative and the tag positioned absolute.
Xamarin.iOS solution
public UIImage CreateImageFromColor()
{
var imageSize = new CGSize(30, 30);
var imageSizeRectF = new CGRect(0, 0, 30, 30);
UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
var context = UIGraphics.GetCurrentContext();
var red = new CGColor(255, 0, 0);
context.SetFillColor(red);
context.FillRect(imageSizeRectF);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
#!/bin/bash
variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable
Notice that there's no space after the equal sign.
You can also use $()
which allows nesting and is readable.
I just discovered an easy way to raise this exception; let your text editor default to saving as UTF-8. Unless you can force it to omit the Byte Order Mark, which may not be easy or even possible, depending on your editor, you'll have a "character" in front of the opening <, which will be hidden from view.
Fortunately, when that possibility crossed my mind, I switched my editor (UltraEdit) into hexadecimal mode, which hides nothing, not even Byte Order Marks. Having written code that processes Byte Order Marks for many years, I recognized it instantly.
Save file as ANSI/ASCII, and accept the default 1252 ANSI Latin-1 code page, problem solved!
You can try this with python 3:
from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))
If you are using windows operating system, the above code may not work for you. Then you can try this code:
from colorama import init
from termcolor import colored
# use Colorama to make Termcolor work on Windows too
init()
# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))
Hope that helps.
To create a complete link to another page from a template, you can use this:
{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}
request.META.HTTP_HOST gives the host name, and url gives the relative name. The template engine then concatenates them into a complete url.
Your first attempt was close. Here is the simplistic approach using your idea.
file="somefileondisk"
lines=`cat $file`
for line in $lines; do
echo "$line"
done
Just add an OR in the conditions
Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])
You can access the id after calling the persist method of the entity manager.
$widgetEntity = new WidgetEntity();
$entityManager->persist($widgetEntity);
$entityManager->flush();
$widgetEntity->getId();
You do need to flush in order to get this id.
Syntax Error Fix: Added semi-colon after $entityManager->flush() is called.
commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems', including this one.
System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));
You can use the querySelector for that:
document.querySelector('[id^="poll-"]').id;
The selector means: get an element where the attribute [id]
begins with the string "poll-"
.
^
matches the start
*
matches any position
$
matches the end
This worked for me. may help some one. Turn off firewall. on RHEL 7
systemctl stop firewalld
One method is:
tar -cf my_archive.tar $( find -name "*.php" -or -name "*.html" )
There are some caveats with this method however:
A workaround to these could be to output the contents of the find command into a file, and then use the "-T, --files-from FILE" option to tar.
Late to the party again but for what it's worth it is possible using jQuery to be a little more succinct. In my case I needed to find the <ul>
parent tag for a <span>
tag contained in the child <li>
. jQuery has the :has
selector so it's possible to identify a parent by the children it contains (updated per @Afrowave's comment ref: https://api.jquery.com/has-selector/):
$("ul").has("#someId")
will select the ul
element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):
$("li").has(".active")
Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).
The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say
select trunc(sysdate) - 1/24/60/60 from dual;
That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.
Splitting a string by whitespace is very simple:
print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';
This is a special form of split
actually (as this function usually takes patterns instead of strings):
As another special case,
split
emulates the default behavior of the command line toolawk
when thePATTERN
is either omitted or a literal string composed of a single space character (such as' '
or"\x20"
). In this case, any leading whitespace inEXPR
is removed before splitting occurs, and thePATTERN
is instead treated as if it were/\s+/
; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator.
Here's an answer for the original question (with a simple string without any whitespace):
Perhaps you want to split on .gz
extension:
my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/, $line;
print $_, "\n" for @abc;
Here I used (?<=...)
construct, which is look-behind assertion, basically making split at each point in the line preceded by .gz
substring.
If you work with the fixed set of extensions, you can extend the pattern to include them all:
my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt', 'xls', 'gz');
my $patt = join '|', map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/, $line;
print $_, "\n" for @abc;
you can also just run it with a shell, for example:
bash example.txt
sh example.txt
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials
(see on MSDN).
Your code looks fine if you need to run a request from server side code or under a different user.
Please note that you should be careful when storing passwords - consider using the SecureString
version of the constructor.
Several people have mentioned the need to restart the servlet container if Jenkins is not running as a standalone. But Tomcat (or what is being used) doesn't need to be restarted. Tomcat can force a restart of the Jenkins context if your Jenkins restart is hung.
But to address another comment, when you put Jenkins in the "shutting down" mode it will not actually shut down. It stops new jobs from executing and place a giant red banner on the system pages so everyone knows that the administrator wants to take it down eventually. There are plugins to trigger a servlet container restart for that context after all builds are completed.
The alternative is to wait till the last running job completes, then manually kick over Jenkins from the container (or via the command line options that others have mentioned for the standalone Jenkins install).
dict.keys.sorted()
that gives [String] https://developer.apple.com/documentation/swift/array/2945003-sorted
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.
const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter
/** remove warning that you don't care about */
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let result = "";
let resultError = "";
pyprog.stdout.on('data', function(data) {
result += data.toString();
});
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
success(JSON.parse(result));
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
Call:
const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});
python:
try:
argu = json.loads(sys.argv[1])
except:
raise Exception("error while loading argument")
Basically, parameters are user specified data to rails application.
When you post a form, you do it generally with POST request as opposed to GET request. You can think normal rails requests as GET requests, when you browse the site, if it helps.
When you submit a form, the control is thrown back to the application. How do you get the values you have submitted to the form? params
is how.
About your code. @vote = Vote.new params[:vote]
creates new Vote to database using data of params[:vote]. Given your form user submitted was named under name :vote, all data of it is in this :vote field of the hash.
Next two lines are used to get item and uid user has submitted to the form.
@extant = Vote.find(:last, :conditions => ["item_id = ? AND user_id = ?", item, uid])
finds newest, or last inserted, vote from database with conditions item_id = item and user_id = uid.
Next lines takes last vote time and current time.
Go to etc folder in Netbeans home --> open netbeans.conf
file and add
on netbeans_default_options
following line:
-J-Dfile.encoding=UTF-8
Restart Netbeans and it should be in UTF-8
To check go to help --> about and check System: Windows Vista version 6.0 running on x86; UTF-8; nl_NL (nb)
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
I had this same issue.
The solution for me was found in the Microsoft KB Article 2452723:
Basically, edit your scheduled task and take the Quotes out of the Start In field:
To get the relevant error message:
1) Convert 2147942667 to hex: 8007010B
2) Take last 4 digits (010B) and convert to decimal: 267
3) Run: net helpmsg 267
4) Result: "The directory name is invalid."
You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.To improve upon the answer given by derobert,
You can determine what your OS connection limit is by catting nf_conntrack_max.
For example: cat /proc/sys/net/netfilter/nf_conntrack_max
You can use the following script to count the number of tcp connections to a given range of tcp ports. By default 1-65535.
This will confirm whether or not you are maxing out your OS connection limit.
Here's the script.
#!/bin/bash
OS=$(uname)
case "$OS" in
'SunOS')
AWK=/usr/bin/nawk
;;
'Linux')
AWK=/bin/awk
;;
'AIX')
AWK=/usr/bin/awk
;;
esac
netstat -an | $AWK -v start=1 -v end=65535 ' $NF ~ /TIME_WAIT|ESTABLISHED/ && $4 !~ /127\.0\.0\.1/ {
if ($1 ~ /\./)
{sip=$1}
else {sip=$4}
if ( sip ~ /:/ )
{d=2}
else {d=5}
split( sip, a, /:|\./ )
if ( a[d] >= start && a[d] <= end ) {
++connections;
}
}
END {print connections}'
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
You can consider using a UI confirmation.
With yesnopopup.bat
@echo off
for /f "tokens=* delims=" %%# in ('yesnopopup.bat') do (
set "result=%%#"
)
if /i result==no (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
the user will see the following and depending on the choice the script will continue:
with absolutely the same script you can use also iexpYNbutton.bat which will produce similar popup.
With buttons.bat you can try the following script:
@echo off
for /f "tokens=* delims=" %%# in ('buttons.bat "Yep!" "Nope!" ') do (
set "result=%%#"
)
if /i result==2 (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
and the user will see:
I had the same problem and have solved it in the following way:
const fetch = (url) => {
return node-fetch(url)
.then(result => result.json())
.catch((e) => {
return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
});
};
tasks = [fetch(url1), fetch(url2) ....];
Promise.all(tasks).then(......)
In that case Promise.all
will wait for every Promise will come into resolved
or rejected
state.
And having this solution we are "stopping catch
execution" in a non-blocking way. In fact, we're not stopping anything, we just returning back the Promise
in a pending state which returns another Promise
when it's resolved after the timeout.
I think the word you're looking for is "overloading". There isn't any method overloading in Python. You can however use default arguments, as follows.
def stackoverflow(self, i=None):
if i != None:
print 'second method', i
else:
print 'first method'
When you pass it an argument, it will follow the logic of the first condition and execute the first print statement. When you pass it no arguments, it will go into the else
condition and execute the second print statement.
For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.
This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.
So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.
If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.
I have found some links using Google, they may help.
They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.
One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.
See these links as well:
NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc"
value to integer..
this is valid string is eg"123"
. in your case split by space..
split(" ");
will split line by " "
by space..
My team moved away from Bower and migrated to npm because:
For more details, see "Why my team uses npm instead of bower".
def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]= message
return result
Results. (evaluate each function 144 times and average the duration)
simple append 0.0102
pre-allocate 0.0098
Conclusion. It barely matters.
Premature optimization is the root of all evil.
There is HasFlag method in .NET 4 or higher.
if(letter.HasFlag(Letters.AB))
{
}
So for this task First Sort your data in order from A to Z or Z to A then you can just use one simple formula as stated below:
=IF(A2=A3, "Duplicate", "Not Duplicate")
The above formula states that if column A2 data ( A is column and 2 is row number) is similar to A3 (A is Column and 3 is Row number) then it will print Duplicate else will print Not Duplicate.
Lets consider an example, Column A consists Email address in which some are duplicate, so in Column 2, I used the above stated formula which in results displayed me the 2 duplicates cells one is Row 2 and Row 6.
One you got the duplicate data just put filter on your sheet and make visible only the duplicate data and delete all the unnecessary data.
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
You mean you want 1b and 1b to be side by side?
<div class="col-lg-6 col-md-6 col-12 child1">
<div class="col-6 child1a">Child content 1a</div>
<div class="col-6 child1b">Child content 1b</div>
</div>
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
@freelancer If you are using ScriptManager then try this code for message..
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
You are missing <context:annotation-config />
from your spring context so the annotations are not being scanned!
The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>
</project>
This can be built, released, and deployed to your local nexus so everyone has access to its artifact.
Now for all projects which you wish to use it, simply include this section:
<parent>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0</version>
</parent>
This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.
If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.
I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.
- pom.xml (aggregator)
- project-parent
- project-module1
- project-module2
What you do with this structure is include your parent module in the aggregator and build everything with a mvn install
from the root directory.
We use this exact solution at my organization and it has stood the test of time and worked quite well for us.
From the current file path you could use:
os.path.join(os.path.dirname(__file__),'..','img','banner.png')
put at the end it will reopen your console
start cmd
LOESS is a very good approach, as Dirk said.
Another option is using Bezier splines, which may in some cases work better than LOESS if you don't have many data points.
Here you'll find an example: http://rosettacode.org/wiki/Cubic_bezier_curves#R
# x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
{
outx <- NULL
outy <- NULL
i <- 1
for (t in seq(0, 1, length.out=n))
{
b <- bez(x, y, t)
outx[i] <- b$x
outy[i] <- b$y
i <- i+1
}
return (list(x=outx, y=outy))
}
bez <- function(x, y, t)
{
outx <- 0
outy <- 0
n <- length(x)-1
for (i in 0:n)
{
outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
}
return (list(x=outx, y=outy))
}
# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red")
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
Look for this:
ANY page in your project that has a missing, or different Namespace...
If you have ANY page in your project with <NO Namespace
> , OR a
DIFFERENT Namespace than Default.aspx, you will get this
"Cannot load Default.aspx", or this: "Default.aspx does not belong here".
ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...
BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??
DGK
You can also use git-fat. I like that it only depends on stock Python and rsync
. It also supports the usual Git workflow, with the following self explanatory commands:
git fat init
git fat push
git fat pull
In addition, you need to check in a .gitfat file into your repository and modify your .gitattributes to specify the file extensions you want git fat
to manage.
You add a binary using the normal git add
, which in turn invokes git fat
based on your gitattributes rules.
Finally, it has the advantage that the location where your binaries are actually stored can be shared across repositories and users and supports anything rsync
does.
UPDATE: Do not use git-fat if you're using a Git-SVN bridge. It will end up removing the binary files from your Subversion repository. However, if you're using a pure Git repository, it works beautifully.
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
If your code is prepared to deal with overflow errors, you can throw an exception if data
is too large.
size_t data = 99999999;
if ( data > INT_MAX )
{
throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);
For Windows, I've created a build.cmd
file:
(replace the keystore path and alias)
For Cordova:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
And for Ionic:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
Save it in the ptoject's directory, you can double click or open it with cmd.
In Git, to "fast forward" means to update the HEAD
pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...
Fast forwarding is not possible when the new HEAD
is in a diverged state relative to the stream you want to integrate. For instance, you are on master
and have local commits, and git fetch
has brought new upstream commits into origin/master
. The branch now diverges from its upstream and cannot be fast forwarded: your master
HEAD
commit is not an ancestor of origin/master
HEAD
. To simply reset master
to the value of origin/master
would discard your local commits. The situation requires a rebase or merge.
If your local master
has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master
. Usually, no special steps are needed to do fast-forwarding; it is done by merge
or rebase
in the situation when there are no local commits.
Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?
No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)
In my mac os python3 you can use: control+p early command contrlo+n next command
difference is that int the inner(equi/default)join and natural join that in the natuarl join common column win will be display in single time but inner/equi/default/simple join the common column will be display double time.
There is bug in MySQL 5.6 version. Even mysqld show as :
Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Realy settings are reading in following order :
Default options are read from the following files in the given order:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Check file: "C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"
Hope it help somebody.
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
mysql> DROP INDEX email ON fuinfo;
where email is the unique key (rather than the column name). You find the name of the unique key by
mysql> SHOW CREATE TABLE fuinfo;
here you see the name of the unique key, which could be email_2, for example. So...
mysql> DROP INDEX email_2 ON fuinfo;
mysql> DESCRIBE fuinfo;
This should show that the index is removed
Think about expectations.
As a client app, you expect to know if something goes wrong on the server side. If the server needs to throw an error when blah
is missing or the requestedResource
value is incorrect than a 400 error would be appropriate.
If all your branches make side-effects or are computationally expensive the following would a semantically-preserving refactoring:
index := func() int {
if val > 0 {
return printPositiveAndReturn(val)
} else {
return slowlyReturn(-val) // or slowlyNegate(val)
}
}(); # exactly one branch will be evaluated
with normally no overhead (inlined) and, most importantly, without cluttering your namespace with a helper functions that are only used once (which hampers readability and maintenance). Live Example
Note if you were to naively apply Gustavo's approach:
index := printPositiveAndReturn(val);
if val <= 0 {
index = slowlyReturn(-val); // or slowlyNegate(val)
}
you'd get a program with a different behavior; in case val <= 0
program would print a non-positive value while it should not! (Analogously, if you reversed the branches, you would introduce overhead by calling a slow function unnecessarily.)
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
You can change the format by doing swapping the values.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var endDate = date
}
This should work:
// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);
If you want to convert dip to pixels, use this:
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
You can use the substring function:
let str = "12345.00";_x000D_
str = str.substring(0, str.length - 1);_x000D_
console.log(str);
_x000D_
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";_x000D_
str = str.slice(0, -1); _x000D_
console.log(str);
_x000D_
The correct way to do it would be:
adb -s 123abc12 shell getprop
Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop
to access its value directly, like this:
adb -s 123abc12 shell getprop ro.product.model
The details in adb devices -l
consist of the following three properties: ro.product.name
, ro.product.model
and ro.product.device
.
Note that ADB shell ends lines with \r\n
, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7
you might get Nexus 7\r
).
i got error related to recaptcha in laravel website, i resolved it by using some command and with env file and above answer will also help in this problem.
first of all check env file(in your case file which has google recaptcha key) for google recpatcha key.
second run these command :
php artisan route:clear
it will solve your problem
This happened to me because I had a ddd()
or dd()
;die; in my routes/web.php file I forgot about.
when bullet have to hide then use:
li { list-style: none;}
when bullet have to list show, then use:
li { list-style: initial;}
void 0
mean?void
[MDN] is a prefix keyword that takes one argument and always returns undefined
.
Examples
void 0
void (0)
void "hello"
void (new Date())
//all will return undefined
It seems pretty useless, doesn't it? If it always returns undefined
, what's wrong with just using undefined
itself?
In a perfect world we would be able to safely just use undefined
: it's much simpler and easier to understand than void 0
. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.
The problem with using undefined
was that undefined
is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined
is a permissible variable name, so you could assign a new value to it at your own caprice.
alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"
Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined
property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.
alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"
void
, on the other hand, cannot be overidden. void 0
will always return undefined
. undefined
, on the other hand, can be whatever Mr. Javascript decides he wants it to be.
void 0
, specifically?Why should we use void 0
? What's so special about 0
? Couldn't we just as easily use 1
, or 42
, or 1000000
or "Hello, world!"
?
And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0
instead of some other argument is that 0
is short and idiomatic.
Although undefined
can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0
: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined
with void 0
to reduce the number of bytes sent to the browser.
before .import command, type ".mode csv"
On Windows 8.1, since .NET 4.5 is built-in, the fix is to run this from an administrative command-prompt:
dism.exe /Online /Enable-Feature /all /FeatureName:IIS-ASPNET45
You can override the default implementation of console.log()
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function (message) {
if (typeof message == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
} else {
logger.innerHTML += message + '<br />';
}
}
})();
Demo: Fiddle
Add
session_start();
at the beginning of your page before any HTML
You will have something like :
<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary
library. The OP suggests that binary.Write()
might have some overhead. Looking at the source for the implementation of Write()
, I see that it does some runtime decisions for maximum flexibility.
func Write(w io.Writer, order ByteOrder, data interface{}) error {
// Fast path for basic types.
var b [8]byte
var bs []byte
switch v := data.(type) {
case *int8:
bs = b[:1]
b[0] = byte(*v)
case int8:
bs = b[:1]
b[0] = byte(v)
case *uint8:
bs = b[:1]
b[0] = *v
...
Right? Write() takes in a very generic data
third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write()
is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.
Something like this:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, 31415926)
fmt.Println(bs)
}
Let us know how this performs.
Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa
) and cast that string to the []byte
type.
package main
import (
"fmt"
"strconv"
)
func main() {
bs := []byte(strconv.Itoa(31415926))
fmt.Println(bs)
}
If after ./configure Makefile.in and Makefile.am are generated and make fail (by showing this following make: *** No targets specified and no makefile found. Stop.) so there is something not configured well, to solve it, first run "autoconf" commande to solve wrong configuration then re-run "./configure" commande and finally "make"
For those attempting Richard's solution above, here are some additional information that might help navigate common errors:
1) When running restore filelistonly you may get Operating system error 5(Access is denied). If that's the case, open SQL Server Configuration Manager and change the login for SQLEXPRESS to a user that has local write privileges.
2) @"This will list the contents of the backup - what you need is the first fields that tell you the logical names" - if your file lists more than two headers you will need to also account for what to do with those files in the RESTORE DATABASE command. If you don't indicate what to do with files beyond the database and the log, the system will apparently try to use the attributes listed in the .bak file. Restoring a file from someone else's environment will produce a 'The path has invalid attributes. It needs to be a directory' (as the path in question doesn't exist on your machine). Simply providing a MOVE statement resolves this problem.
In my case there was a third FTData type file. The MOVE command I added:
MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf',
MOVE 'sysft_...' TO 'c:\temp\other';
in my case I actually had to make a new directory for the third file. Initially I tried to send it to the same folder as the .mdf file but that produced a 'failed to initialize correctly' error on the third FTData file when I executed the restore.
git add
selects changes
git commit
records changes LOCALLY
git push
shares changes
Why can't you just check it yourself and throw an exception if that is what you want.
try {
for (int i = 0; i < tab.length; i++) {
tab[i] = 1.0 / tab[i];
if (tab[i] == Double.POSITIVE_INFINITY ||
tab[i] == Double.NEGATIVE_INFINITY)
throw new ArithmeticException();
}
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException occured!");
}
As noted in the official documentation, simply apply the class(es) btn btn-link
:
<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>
For example, with the code you have provided:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
<div class="row-fluid">_x000D_
<!-- Navigation for the form -->_x000D_
<div class="span3">_x000D_
<ul class="nav nav-tabs nav-stacked">_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
</li>_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
</li>_x000D_
<!-- ... -->_x000D_
</ul>_x000D_
</div>_x000D_
<!-- The actual form -->_x000D_
<div class="span9">_x000D_
<!-- ... -->_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.
@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })
If i understand your question, you just want to be able to access items in a data frame (or list) by row:
x = matrix( ceiling(9*runif(20)), nrow=5 )
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x) # create a small data frame
df[1,] # get the first row
df[3,] # get the third row
df[nrow(df),] # get the last row
lf = as.list(df)
lf[[1]] # get first row
lf[[3]] # get third row
etc.
@skelly solution is good but will not work on mobile devices as the hover state won't work.
I have added a little bit of JS to get the BS 2.3.2 behavior back.
PS: it will work with the CSS you get there: http://bootply.com/71520 though you can comment the following part:
CSS:
/*.dropdown-submenu:hover>.dropdown-menu{display:block;}*/
JS:
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
// Avoid following the href location when clicking
event.preventDefault();
// Avoid having the menu to close when clicking
event.stopPropagation();
// If a menu is already open we close it
$('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
// opening the one you clicked on
$(this).parent().addClass('open');
});
The result can be found on my WordPress theme (Top of the page): http://shprinkone.julienrenaux.fr/
I prefers using Guava :
import com.google.common.base.Charsets;
import com.google.common.io.Files;
File file = new File("/path/to/file", Charsets.UTF_8);
String content = Files.toString(file);
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
have a try with Flex Paper http://flexpaper.devaldi.com/
it works like scribd
Simple fix to this was setting showAsAction
to always
in menu.xml
in res/menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/add_alarm"
android:icon="@drawable/ic_action_name"
android:orderInCategory="100"
android:title="Add"
app:showAsAction="always"
android:visible="true"/>
</menu>
You can do it in one line as below:
YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));
Happy coding ;)
Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.
JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.
Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.
EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.
EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!
Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...
EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...
In my case I had a dual-boot system (Windows 10 and Linux) with project folder on NTFS disk. It turned out that on another update Windows 10 enabled by itself "fast startup" in its settings. After I've unchecked it in the Windows - the "error: cannot open .git/FETCH_HEAD: Permission denied" in Linux was gone.
I had the same problem, and "export LC_ALL=c"
didn't work for me.
Try export LC_ALL="en_US.UTF-8"
(it will work).
you can try chsh -s /bin/bash
to set the bash as the default,
or chsh -s /bin/zsh
to set the zsh as the default.
Terminal will need a restart to take effect.
Run gpresult
at a Windows command prompt. You'll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.
Here is a tweak of McDowell's algorithm that doesn't pad the result:
function toHex(str) {
var result = '';
for (var i=0; i<str.length; i++) {
result += str.charCodeAt(i).toString(16);
}
return result;
}
First extract the string like this
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)
Here is the benchmark code:
require 'benchmark'
h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000
Benchmark.bm do |b|
GC.start
b.report("hash keys collect") do
many.times do
h.keys.collect(&:to_s)
end
end
GC.start
b.report("hash keys map") do
many.times do
h.keys.map(&:to_s)
end
end
GC.start
b.report("array collect") do
many.times do
a.collect(&:to_s)
end
end
GC.start
b.report("array map") do
many.times do
a.map(&:to_s)
end
end
end
And the results I got were:
user system total real
hash keys collect 0.540000 0.000000 0.540000 ( 0.570994)
hash keys map 0.500000 0.010000 0.510000 ( 0.517126)
array collect 1.670000 0.020000 1.690000 ( 1.731233)
array map 1.680000 0.020000 1.700000 ( 1.744398)
Perhaps an alias isn't free?
Specify /D
to change the drive also.
CD /D %root%
Toggle between two classes 'A' and 'B' with Jquery.
$('#selecor_id').toggleClass("A B");