Simple using jquery
<script>
$(document).ready(function() {
$('#loginLink').click(function() {
$('#loginTable').toggle('slow');
});
})
</script>
I'm not entirely sure what you're after but this sounds like it can be achieved by storing the state of the input elements (or the div?) as a variable:
$('div').each(function(){
var childInputHasFocus = false;
$(this).hover(function(){
if (childInputHasFocus) {
// do something
} else { }
}, function() {
if (childInputHasFocus) {
// do something
} else { }
});
$('input', this)
.focus(function(){
childInputHasFocus = true;
})
.blur(function(){
childInputHasFocus = false;
});
});
MDN suggests that there's a much cleaner way of doing this in modern browsers:
// Assuming we're listening for e.g. a 'change' event on `element`
// Create a new 'change' event
var event = new Event('change');
// Dispatch it.
element.dispatchEvent(event);
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:
$someElement.on('event', function() {
$('#myDiv').addClass('submission-ok').trigger('classChange');
});
// in another js file, far, far away
$('#myDiv').on('classChange', function() {
// do stuff
});
UPDATE
This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver
:
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
mutations.forEach(function(mutation) {_x000D_
if (mutation.attributeName === "class") {_x000D_
var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
console.log("Class attribute changed to:", attributeValue);_x000D_
}_x000D_
});_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
Be aware that the MutationObserver
is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.
If the this
value you want is the just the object that you bound the event handler to, then addEventListener()
already does that for you. When you do this:
productLineSelect.addEventListener('change', getSelection, false);
the getSelection
function will already be called with this
set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.
function getSelection(event) {
// this will be set to the object that the event handler was bound to
// event is all the detailed information about the event
}
If the desired this
value is some other value than the object you bound the event handler to, you can just do this:
var self = this;
productLineSelect.addEventListener('change',function() {
getSelection(self)
},false);
By way of explanation:
this
into a local variable in your other event handler.this
.This is what I've been using. Haven't seen any issues.
destroy: function(){
this.remove();
this.unbind();
}
Use That :
$(selector).trigger("change");
OR
$('#id').trigger("click");
OR
$('.class').trigger(event);
Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.
You should really use the following instead (works in all newer browsers):
window.addEventListener('DOMContentLoaded', init, false);
on your child page, put these:
<script type="text/javascript">
function refreshAndClose() {
window.opener.location.reload(true);
window.close();
}
</script>
and
<body onbeforeunload="refreshAndClose();">
but as a good UI design, you should use a Close button
because it's more user friendly. see code below.
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
window.opener.location.reload(true);
window.close();
});
});
</script>
<input type='button' id='btn' value='Close' />
onblur
is the opposite of onfocus
.
Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.
But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.
$("#google").click(function() {
if (situation) {
// ...
} else {
// ...
}
});
I'm not sure I understand your question. But there are two approaches to making the image invisible...
Pure HTML
<img src="a.gif" style="display: none;" />
Or...
HTML + Javascript
<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>
<img id="myImage" src="a.gif" />
You might want to do one of the following:
Several libraries let you do that easily. Example below is written using my NoException library.
// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));
// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));
// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback
function getData(callbackData){
var http = require('http');
var str = '';
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
callbackData(str);
});
//return str;
}
var req = http.request(options, callback).end();
// These just return undefined and empty
console.log(req.data);
console.log(str);
}
somewhere else
getData(function(data){
// YOUR CODE HERE!!!
})
Base on accepted answer, I made an extension method to check column exist in table as
I shared for whom concern.
public static class DatatableHelper
{
public static bool ContainColumn(this DataTable table, string columnName)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
return true;
}
return false;
}
}
And use as dtTagData.ContainColumn("SystemName")
Arguments
property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR
and not DT_STR
.
Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx
. Create a package variable with the following information.
Name Scope Data Type Value
------ ------------ ---------- -----
IdVar SO_13177007 Int32 123
Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments
Double-click the Execute Process Task to open the Execute Process Task Editor
. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor
.
On the Property Expression Editor, select the property Arguments
and click the Ellipsis button against the property to open the Expression Builder
.
On the Expression Builder, enter the following expression and click Evaluate Expression
. This expression tries to convert the integer value in the variable IdVar
to string data type.
(DT_STR, 10, 1252) @[User::IdVar]
Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR
.
To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR
. Clicking Evaluate Expression will display the value in the Evaluated value text area.
(DT_WSTR, 10) @[User::IdVar]
To understand the differences between the data types DT_STR
and DT_WSTR
in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.
A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
for bootstrap 3, this is what i used
.carousel-fade .carousel-inner .item {
opacity: 0;
-webkit-transition-property: opacity;
-moz-transition-property: opacity;
-o-transition-property: opacity;
transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-control {
z-index: 2;
}
To create a clickable reference to a channel in a Slack conversation, just type #
followed by the channel name. For example: #general
.
To share the channel URL externally, you can grab its link by control-clicking (Mac) or right-clicking (Windows) on the channel name:
The link would look like this:
https://yourteam.slack.com/messages/C69S1L3SS
Note that this link doesn't change even if you change the name of the channel. So, it is better to use this link rather than the one based on channel's name.
https://yourteam.slack.com/channels/<channel_name>
Opening the above URL from a browser would launch the Slack client (if available) or open the slack channel on the browser itself.
https://yourteam.slack.com/channels/<username>
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:
echo "`date` User `whoami` started the script."$'\r' >> output.log
(where the $'\r'
at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).
Based on my observations:
$request->request->add(['variable' => 'value']);
will (mostly) work in POST, PUT & DELETE methods, because there is value(s) passed, one of those is _token
. Like example below.
<form action="{{ route('process', $id) }}" method="POST">
@csrf
</form>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
But [below code] won't work because there is no value(s) passed, it doesn't really add.
<a href='{{ route('process', $id) }}'>PROCESS</a>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
public function process($id){
$request = new Request(['id' => $id]);
}
Or you can use merge
. This is better actually than $request->request->add(['variable' => 'value']);
because can initialize, and add request values that will work for all methods (GET, POST, PUT, DELETE)
public function process(Request $request, $id){
$request->merge(['id' => $id]);
}
Tag: laravel5.8.11
It appears that SSRS has an issue(at leastin version 2008) - I'm studying this website that explains it
Where it says if you have two columns(from 2 diff. tables) with the same name, then it'll cause that problem.
From source:
SELECT a.Field1, a.Field2, a.Field3, b.Field1, b.field99 FROM TableA a JOIN TableB b on a.Field1 = b.Field1
SQL handled it just fine, since I had prefixed each with an alias (table) name. But SSRS uses only the column name as the key, not table + column, so it was choking.
The fix was easy, either rename the second column, i.e. b.Field1 AS Field01 or just omit the field all together, which is what I did.
Both PUT and POST are Rest Methods .
PUT - If we make the same request twice using PUT using same parameters both times, the second request will not have any effect. This is why PUT is generally used for the Update scenario,calling Update more than once with the same parameters doesn't do anything more than the initial call hence PUT is idempotent.
POST is not idempotent , for instance Create will create two separate entries into the target hence it is not idempotent so CREATE is used widely in POST.
Making the same call using POST with same parameters each time will cause two different things to happen, hence why POST is commonly used for the Create scenario
You might have pressed 0
(also used for insert, shortcut INS
) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
Loop through and print all the values of an associative array, you could use a foreach
loop, like this:
foreach($results as $x => $value) {
echo $value;
}
If you like entering arcane operators from the command line, you’ll love these manual container backup techniques. Keep in mind, there’s a faster and more efficient way to backup containers that’s just as effective. I've written instructions here: https://www.morpheusdata.com/blog/2017-03-02-how-to-create-a-docker-backup-with-morpheus
Step 1: Add a Docker Host to Any Cloud As explained in a tutorial on the Morpheus support site, you can add a Docker host to the cloud of your choice in a matter of seconds. Start by choosing Infrastructure on the main Morpheus navigation bar. Select Hosts at the top of the Infrastructure window, and click the “+Container Hosts” button at the top right.
To back up a Docker host to a cloud via Morpheus, navigate to the Infrastructure screen and open the “+Container Hosts” menu.
Choose a container host type on the menu, select a group, and then enter data in the five fields: Name, Description, Visibility, Select a Cloud and Enter Tags (optional). Click Next, and then configure the host options by choosing a service plan. Note that the Volume, Memory, and CPU count fields will be visible only if the plan you select has custom options enabled.
Here is where you add and size volumes, set memory size and CPU count, and choose a network. You can also configure the OS username and password, the domain name, and the hostname, which by default is the container name you entered previously. Click Next, and then add any Automation Workflows (optional).Finally, review your settings and click Complete to save them.
Step 2: Add Docker Registry Integration to Public or Private Clouds Adam Hicks describes in another Morpheus tutorial how simple it is to integrate with a private Docker Registry. (No added configuration is required to use Morpheus to provision images with Docker’s public hub using the public Docker API.)
Select Integrations under the Admin tab of the main navigation bar, and then choose the “+New Integration” button on the right side of the screen. In the Integration window that appears, select Docker Repository in the Type drop-down menu, enter a name and add the private registry API endpoint. Supply a username and password for the registry you’re using, and click the Save Changes button.
Integrate a Docker Registry with a private cloud via the Morpheus “New Integration” dialog box.
To provision the integration you just created, choose Docker under Type in the Create Instance dialog, select the registry in the Docker Registry drop-down menu under the Configure tab, and then continue provisioning as you would any Docker container.
Step 3: Manage Backups Once you’ve added the Docker host and integrated the registry, a backup will be configured and performed automatically for each instance you provision. Morpheus support provides instructions for viewing backups, creating an instance backup, and creating a server backup.
I would suggest to pass the JSON data in the body as a POST
request.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-
for ex json is :->{"name":"ABC","id":"1"}
testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D
for more information on URL encoding refer below
SELECT ProductID, ProductName, OrderQuantity, SUM(OrderQuantity) FROM OrderDetails WHERE(OrderQuantity) IN(SELECT SUM(OrderQuantity) FROM OrderDetails GROUP BY OrderDetails) GROUP BY ProductID, ProductName, OrderQuantity;
I used the above solution to solve a similar problem in Oracle12c.
Alternative solution that doesn't use position absolute:
I see a lot of position absolute answers. I couldn't use position absolute without breaking something else. So for those that couldn't as well, here is what I did:
https://stackoverflow.com/a/58622840/6546317 (posted in response to another question).
The solution only focuses on vertically centering because my children elements were already horizontally centered but same could be applied if you couldn't horizontally center them in another way.
For some databases, you can just explicitly insert a NULL
into the auto_increment
column:
INSERT INTO table_name VALUES (NULL, 'my name', 'my group')
Give an ID to uniquely identify the button, lets say myBtn
// when DOM is ready
$(document).ready(function () {
// Attach Button click event listener
$("#myBtn").click(function(){
// show Modal
$('#myModal').modal('show');
});
});
See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.
Quoting only the relevant definitions from that RFC for brevity:
Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).
First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]
There is another way of using Uri
and we can achieve the same goal
http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
To build the Uri you can use this:
final String FORECAST_BASE_URL =
"http://api.example.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
You can declare all this the above way or even inside the Uri.parse()
and appendQueryParameter()
Uri builtUri = Uri.parse(FORECAST_BASE_URL)
.buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, "json")
.appendQueryParameter(UNITS_PARAM, "metric")
.appendQueryParameter(DAYS_PARAM, Integer.toString(7))
.build();
At last
URL url = new URL(builtUri.toString());
It works with Spring Boot 2.1.0 and Hibernate 5
@PersistenceContext
private EntityManager entityManager;
Then you can create new Session by using entityManager.unwrap(Session.class)
Session session = null;
if (entityManager == null
|| (session = entityManager.unwrap(Session.class)) == null) {
throw new NullPointerException();
}
example create query:
session.createQuery("FROM Student");
application.properties:
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
In case you were struggling to change linetypes
, the following answer should be helpful. (This is an addition to the solution by Andy W.)
We will try to extend the learned pattern:
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) + #red
geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) + #blue
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_linetype_manual(values=line_types)+
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
However, what we get is the following result:
The problem is that the linetype
is not merged in the main legend.
Note that we did not give any name to the method scale_linetype_manual
.
The trick which works here is to give it the same name as what you used for naming scale_colour_manual
.
More specifically, if we change the corresponding line to the following we get the desired result:
scale_linetype_manual(name="Error Bars",values=line_types)
Now, it is easy to change the size of the line with the same idea.
Note that the geom_bar
has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar
with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.
You need to know the chunk size by which you're dividing your list. Say you have a list of 108 entries
and you need a chunk size of 25
. Thus you will end up with 5 lists
:
25 entries
each;8 elements
. Code:
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i=0; i<108; i++){
list.add(i);
}
int size= list.size();
int j=0;
List< List<Integer> > splittedList = new ArrayList<List<Integer>>() ;
List<Integer> tempList = new ArrayList<Integer>();
for(j=0;j<size;j++){
tempList.add(list.get(j));
if((j+1)%25==0){
// chunk of 25 created and clearing tempList
splittedList.add(tempList);
tempList = null;
//intializing it again for new chunk
tempList = new ArrayList<Integer>();
}
}
if(size%25!=0){
//adding the remaining enteries
splittedList.add(tempList);
}
for (int k=0;k<splittedList.size(); k++){
//(k+1) because we started from k=0
System.out.println("Chunk number: "+(k+1)+" has elements = "+splittedList.get(k).size());
}
}
I found this link useful.
Here is the paragraph highlighting some of the pros/cons of each approach.
The most commonly seen design is to imitate the many Boolean-like flags that Oracle's data dictionary views use, selecting 'Y' for true and 'N' for false. However, to interact correctly with host environments, such as JDBC, OCCI, and other programming environments, it's better to select 0 for false and 1 for true so it can work correctly with the getBoolean and setBoolean functions.
Basically they advocate method number 2, for efficiency's sake, using
getBoolean()
etc.) with a check constraintTheir example:
create table tbool (bool char check (bool in (0,1)); insert into tbool values(0); insert into tbool values(1);`
It's also possible to do something like this with ng-style
:
ng-style="image_path != '' && {'background-image':'url('+image_path+')'}"
which would not attempt to fetch a non-existing image.
I was having this problem, I had configured my site for global require https in FilterConfig.cs.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new RequireHttpsAttribute());
}
I had forgotten to change the project url to https: from this tutorial http://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/ under ENABLE SSL part 4. This caused the errors you were getting.
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
Some general constructor tips:
Know the order of initialization rules for constructors. It's basically:
The overall flow ends up being:
For a nice example of evil, try figuring out what the following will print, then run it
package com.javadude.sample;
/** THIS IS REALLY EVIL CODE! BEWARE!!! */
class A {
private int x = 10;
public A() {
init();
}
protected void init() {
x = 20;
}
public int getX() {
return x;
}
}
class B extends A {
private int y = 42;
protected void init() {
y = getX();
}
public int getY() {
return y;
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
System.out.println("x=" + b.getX());
System.out.println("y=" + b.getY());
}
}
I'll add comments describing why the above works as it does... Some of it may be obvious; some is not...
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
Very quickly and sortly-code implementation by using the lambda operator.
In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75
Because constructing your subclass object may be done in a different way from how your superclass is constructed. You may not want clients of the subclass to be able to call certain constructors available in the superclass.
A silly example:
class Super {
protected final Number value;
public Super(Number value){
this.value = value;
}
}
class Sub {
public Sub(){ super(Integer.valueOf(0)); }
void doSomeStuff(){
// We know this.value is an Integer, so it's safe to cast.
doSomethingWithAnInteger((Integer)this.value);
}
}
// Client code:
Sub s = new Sub(Long.valueOf(666L)): // Devilish invocation of Super constructor!
s.doSomeStuff(); // throws ClassCastException
Or even simpler:
class Super {
private final String msg;
Super(String msg){
if (msg == null) throw new NullPointerException();
this.msg = msg;
}
}
class Sub {
private final String detail;
Sub(String msg, String detail){
super(msg);
if (detail == null) throw new NullPointerException();
this.detail = detail;
}
void print(){
// detail is never null, so this method won't fail
System.out.println(detail.concat(": ").concat(msg));
}
}
// Client code:
Sub s = new Sub("message"); // Calling Super constructor - detail is never initialized!
s.print(); // throws NullPointerException
From this example, you see that you'd need some way of declaring that "I want to inherit these constructors" or "I want to inherit all constructors except for these", and then you'd also have to specify a default constructor inheritance preference just in case someone adds a new constructor in the superclass... or you could just require that you repeat the constructors from the superclass if you want to "inherit" them, which arguably is the more obvious way of doing it.
I got the same issue and It got solved by installing Oracle 11g client in my machine..
I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it
You can use int()
function to convert float64
type data to an int
. Similarly you can use float64()
Example:
func check(n int) bool {
// count the number of digits
var l int = countDigit(n)
var dup int = n
var sum int = 0
// calculates the sum of digits
// raised to power
for dup > 0 {
**sum += int(math.Pow(float64(dup % 10), float64(l)))**
dup /= 10
}
return n == sum
}
2018 already... I've found this fantastic online tool http://mapshaper.org/ to convert from ESRI shapefiles to SVG, TopoJSON, GeoJSON.
Here is the explanation of how to use it https://www.statsilk.com/maps/convert-esri-shapefile-map-geojson-format
Fast and straightforward! :)
In general you can concatenate a whole sequence of arrays along any axis:
numpy.concatenate( LIST, axis=0 )
but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.
As Jorge's answer points out, there is also the function stack
, introduced in numpy 1.10:
numpy.stack( LIST, axis=0 )
This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n
-element 1D array becomes a 1-by-n
2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.
vstack
(or equivalently row_stack
) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:
numpy.vstack( LIST )
This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ]
(note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST
.
There is also an analogous function column_stack
and shortcut c_[...]
, for horizontal (column-wise) stacking, as well as an almost-analogous function hstack
—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).
Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:
numpy.array( LIST )
...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.
You can even try below option:
<a href="javascript:show_more_menu();">More >>></a>
Since getText()
is non-static you cannot call it from a static method.
To understand why, you have to understand the difference between the two.
Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:
SomeClass myObject = new SomeClass();
To call an instance method, you call it on the instance (myObject
):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod()
but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
And the two cannot work together as they operate on different data spaces (instance data and class data)
Let me try and explain. Consider this class (psuedocode):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
Now I have the following use case:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What are the values?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
In other words, TTT
is a datum that is shared by all the instances of the type. So it make no sense to say
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
So the question is why is TTT static or why is getText() not static?
Remove the static
and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText()
that require it to be non-static?
you may try this one, used CONCAT
WHERE LastName LIKE Concat('%',@LastName,'%')
Another alternative is
npm install react-favicon
And in your application you would just do:
import Favicon from 'react-favicon';
//other codes
ReactDOM.render(
<div>
<Favicon url="/path/to/favicon.ico"/>
// do other stuff here
</div>
, document.querySelector('.react'));
A nice and clean solution
npm install jquery --save
)<script> let $ = require("jquery") </script>
In Android Studio 3.3 it is here:
According to the answer https://stackoverflow.com/a/49576954/2914140 in Android Studio 3.1 it is here:
This command is moved to File > Sync Project with Gradle Files
.
I also ran into this problem. I solved the problem by going to the Application Pools > Application Pool Name and changed the .NET Framework from version v.2.0.50727 to v4.0.30319.
Here is an interesting library: https://github.com/Flipboard/FLAnimatedImage
I tested the demo example and it's working great. It's a child of UIImageView. So I think you can use it in your Storyboard directly as well.
Cheers
You can use the condition if x is not null then...
. It's not a function. There's also the NVL()
function, a good example of usage here: NVL function ref.
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
Give the form
an id
, and then:
document.getElementById("yourFormId").submit();
Best practice would probably be to give your link an id
too, and get rid of the event handler:
document.getElementById("yourLinkId").onclick = function() {
document.getElementById("yourFormId").submit();
}
You can use the conditional system that best fits your needs.
Dockerfile
ARG ENV
FROM foo as base
ARG ENV
# run common
RUN ...
# For long running tasks that would slow down deployments
RUN if [[ "$ENV" == "dev" ]] ; then \
yum install -y lots of big dev packages ; \
fi
# Build dev image
FROM base as image-dev
RUN ...
COPY ...
# Build prod image
FROM base as image-prod
RUN ...
COPY ...
FROM image-$ENV AS final
Note that we define ENV twice - you need to define ENV globally, and in each image where it is used.
Use docker:
docker build -t my_docker . --build-arg ENV="dev"
Use docker-compose:
version: '3'
services:
dev:
container_name: dev
ports:
- 3000:8080
volumes:
- ./:/var/task
tty: true
build:
context: .
dockerfile: Dockerfile
args:
ENV: dev
docker-compose build --no-cache dev && docker-compose up dev
I wish AngularJS had a built in confirmation dialog. Often, it is nicer to have a customized dialog than using the built in browser one.
I briefly used the twitter bootstrap until it was discontinued with version 6. I looked around for alternatives, but the ones I found were complicated. I decided to try the JQuery UI one.
Here is my sample that I call when I am about to remove something from ng-grid;
// Define the Dialog and its properties.
$("<div>Are you sure?</div>").dialog({
resizable: false,
modal: true,
title: "Modal",
height: 150,
width: 400,
buttons: {
"Yes": function () {
$(this).dialog('close');
//proceed with delete...
/*commented out but left in to show how I am using it in angular
var index = $scope.myData.indexOf(row.entity);
$http['delete']('/EPContacts.svc/json/' + $scope.myData[row.rowIndex].RecordID).success(function () { console.log("groovy baby"); });
$scope.gridOptions.selectItem(index, false);
$scope.myData.splice(index, 1);
*/
},
"No": function () {
$(this).dialog('close');
return;
}
}
});
I hope this helps someone. I was pulling my hair out when I needed to upgrade ui-bootstrap-tpls.js but it broke my existing dialog. I came into work this morning, tried a few things and then realized I was over complicating.
SELECT @myDate - DAY(@myDate) + 1
<div class="centered">
<p style="text-align: justify;">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque</p>nisl consectetur et.</div>
I was able to achieve the result by wrapping the content in a div tag and applying the attribute text-align: center. Immediately after the div tag I wrapped the content in a paragraph tag and applied attribute, text-align: justify. To make the last line centered, I excluded it from the paragraph tag, which then falls back to attribute applied in the div tag. You just have to strategic about how many words you want on the last line. I've included a demo from fiddle. Hope this helps.
This script is about creating tables with foreign key and I added referential integrity constraint sql-server.
create table exams
(
exam_id int primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id int primary key,
question_exam_id int not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id_fk
foreign key references exams(exam_id)
ON DELETE CASCADE
);
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
use the .not() method and check for an attribute:
$('p').not('[class]');
Check it here: http://jsfiddle.net/AWb79/
A really fast way to solve this problem is to make a database link from the Oracle database to the MySQL database. You can create database links to non-Oracle databases. After you have created the database link you can retrieve your data from the MySQL database with a ... create table mydata as select * from ... statement. This is called heterogeneous connectivity. This way you don't have to do anything in your .net application to move the data.
Another way is to use ODP.NET. In ODP.NET you can use the OracleBulkCopy-class.
But I don't think that inserting 160k records in an Oracle table with System.Data.OracleClient should take 25 minutes. I think you commit too many times. And do you bind your values to the insert statement with parameters or do you concatenate your values. Binding is much faster.
Use this code in your .cshtml file.
@{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var val = jss.Serialize(ViewBag.somevalue);
}
<script>
$(function () {
var val = '@Html.Raw(val)';
var obj = $.parseJSON(val);
console.log(0bj);
});
</script>
Step 1: See all your databases:
show dbs
Step 2: Select the database
use your_database_name
Step 3: Show the collections
show collections
This will list all the collections in your selected database.
Step 4: See all the data
db.collection_name.find()
or
db.collection_name.find().pretty()
Using this code to multiple order by in single query.
$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get();
return $query->result();
Select * from Table name ..i.e(are you save table name in sql(TEST) k.
Select * from TEST then you will execute your project.
If you want to use something that is more descriptive than a dumb array without resorting to using a DataSet then the following might prove useful. It still isn't strongly-typed, but at least it is checked by the compiler and will handle being refactored quite well.
Dim previousAllowUserToAddRows = dgvHistoricalInfo.AllowUserToAddRows
dgvHistoricalInfo.AllowUserToAddRows = True
Dim newTimeRecord As DataGridViewRow = dgvHistoricalInfo.Rows(dgvHistoricalInfo.NewRowIndex).Clone
With record
newTimeRecord.Cells(dgvcDate.Index).Value = .Date
newTimeRecord.Cells(dgvcHours.Index).Value = .Hours
newTimeRecord.Cells(dgvcRemarks.Index).Value = .Remarks
End With
dgvHistoricalInfo.Rows.Add(newTimeRecord)
dgvHistoricalInfo.AllowUserToAddRows = previousAllowUserToAddRows
It is worth noting that the user must have AllowUserToAddRows
permission or this won't work. That is why I store the existing value, set it to true, do my work, and then reset it to how it was.
You can try ezxml -- it's a lightweight parser written entirely in C.
For C++ you can check out TinyXML++
I faced a similar problem today, where I have a struct that I want to fill with test data which will be passed as arguments to a function I'm testing. I wanted to have a vector of these structs and was looking for a one-liner method to initialize each struct.
I ended up going with a constructor function in the struct, which I believe was also suggested in a few answers to your question.
It's probably bad practice to have the arguments to the constructor have the same names as the public member variables, requiring use of the this
pointer. Someone can suggest an edit if there is a better way.
typedef struct testdatum_s {
public:
std::string argument1;
std::string argument2;
std::string argument3;
std::string argument4;
int count;
testdatum_s (
std::string argument1,
std::string argument2,
std::string argument3,
std::string argument4,
int count)
{
this->rotation = argument1;
this->tstamp = argument2;
this->auth = argument3;
this->answer = argument4;
this->count = count;
}
} testdatum;
Which I used in in my test function to call the function being tested with various arguments like this:
std::vector<testdatum> testdata;
testdata.push_back(testdatum("val11", "val12", "val13", "val14", 5));
testdata.push_back(testdatum("val21", "val22", "val23", "val24", 1));
testdata.push_back(testdatum("val31", "val32", "val33", "val34", 7));
for (std::vector<testdatum>::iterator i = testdata.begin(); i != testdata.end(); ++i) {
function_in_test(i->argument1, i->argument2, i->argument3, i->argument4m i->count);
}
If you want to fully copy properties of an object in a different instance, you may want to use this technique:
Serialize it to JSON and then de-serialize it back to Object.
I had this problem before and to fix this, Just make sure :
My problem (before) :
I had class : Core, Router, Permissions and Render
Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.
Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...
Try this:
$(function () {
$('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
$('#type').change(function () {
$('#row_dim').hide();
if (this.options[this.selectedIndex].value == 'parcel') {
$('#row_dim').show();
}
});
});
From ISO14882:2011(e) 5.6-4:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
The rest is basic math:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
Note that
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
from ISO14882:2003(e) is no longer present in ISO14882:2011(e)
<style>
p{
width: 70%
word-wrap: break-word;
}
</style>
This wasn't working in my case. It worked fine after adding following style.
<style>
p{
width: 70%
word-break: break-all;
}
</style>
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
This is just to help somebody in future. When we initiate InternetExplorerDriver() instance in a java project it uses IEDriver.exe (downloaded by individuals) which tries to extract temporary files in user's TEMP folder when it's not in path then ur busted.
Safest way is to provide your own extract path as shown below
System.setProperty("webdriver.ie.driver.extractpath", "F:\\Study\\");
System.setProperty("webdriver.ie.driver", "F:\\Study\\IEDriverServer.exe");
System.setProperty("webdriver.ie.logfile", "F:\\Study\\IEDriverServer.log");
InternetExplorerDriver d = new InternetExplorerDriver();
d.get("http://www.google.com");
d.quit();
Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so
let markdown = `
1. Apple
2. Mango
this is juicy
3. Orange
`
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
I will say no.
But the only proof that I have is personal experience and the fact that documentation on line continuation doesn't have anything else in it.
http://msdn.microsoft.com/en-us/library/aa711641(VS.71).aspx
I had the same problem. Installed mingw using the installer provided at http://tdm-gcc.tdragon.net/ . It adds the correct environment variables to path when installing mingw (No need to edit the path variable manually). That did the trick for me.
Don't reinvent the wheel. Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary
:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
Just a quick note. It is DbContext, not DBContext. i.e. with a lowercase 'B'. I discovered this because I had the same problem while intelesense was not working until I tried typing the full name space System.Data.Entity... and name and finally it suggested the lowercase 'b' option:-
System.Data.Entity.DbContext
My suggestion would be to get the book Programming From Ground Up:
http://nongnu.askapache.com/pgubook/ProgrammingGroundUp-1-0-booksize.pdf
That is a very good starting point for getting into assembler programming under linux and it explains a lot of the basics you need to understand to get started.
You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:
<div id='parent' style='width: 100%;'>
<div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>
SQLFiddle will let you test out your queries, while it doesn't explicitly correct syntax etc. per se it does let you play around with the script and will definitely let you know if things are working or not.
For Python 3, this is a much safer and Pythonic approach to convert from byte
to string
:
def byte_to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes): # Check if it's in bytes
print(bytes_or_str.decode('utf-8'))
else:
print("Object not of byte type")
byte_to_str(b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n')
Output:
total 0
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
You can use the Grid CSS properties, is the most clear, clean and intuitive way structure your boxes.
#container{_x000D_
display: grid;_x000D_
grid-template-columns: 100px auto;_x000D_
color:white;_x000D_
}_x000D_
#fixed{_x000D_
background: red;_x000D_
grid-column: 1;_x000D_
}_x000D_
#remaining{_x000D_
background: green;_x000D_
grid-column: 2;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="fixed">Fixed</div>_x000D_
<div id="remaining">Remaining</div>_x000D_
</div>
_x000D_
For Mac:
Quick Text Search: Shift + Cmd + L
All other search (like File Search, Git Search, Java Search etc): Ctrl + H
This is a feature called template literals.
They were called "template strings" in prior editions of the ECMAScript 2015 specification.
Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.
Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:
var a = 123, str = `---
a is: ${a}
---`;
console.log(str);
Output:
---
a is: 123
---
What is more important, they can contain not just a variable name, but any JavaScript expression:
var a = 3, b = 3.1415;
console.log(`PI is nearly ${Math.max(a, b)}`);
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " (" + TASK_ID
+ " integer primary key autoincrement, " + TASK_TITLE
+ " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";
Where I put the TASK_DATE_TIME after the foreign key line.
From Reddit:
https://www.reddit.com/r/Windows10/comments/39af75/for_my_win10_companions_heres_how_to_get/
I can't see the original source in this thread, although I would like to.
I am using these instructions with a laptop that upgraded from windows 8 to windows 10. I have to repeat the last instructions after rebooting.
I have test an get solution for my self and want to share my solution. - Host Only worked - Bridge Adapter worked
My Configuration is - Surface Pro 1 - Clean install Windows 10 x64 build 10130 - VirtualBox-5.0.0_RC1-100731-Win.exe
(this is my opinion but not tested on how to remove previous version by install VirtualBox-5.0.0_RC1-100731-Win.exe with select all function to install its will fault and rollback all, then its same as uninstall)
Install Step - Right Click on VirtualBox-5.0.0_RC1-100731-Win.exe and select "Run as Administrator" - "Unselect" option bridge network
next until finish
Open "Device Manager", you can use search bar to get this, under "Network adapters" then Right Click "VirtualBox Host-Only Ethernet Adapter" select "Update Driver Software" select "Search automactic" wait until its finish
- Open "Network Connections", you can use search bar to get this, at here you should find VirtualBox Host-Only Ethernet Adapter
- Open "CMD", you can use search bar to get this, Right Click and Select Run as Administrator
- cd to your install path and run command "VirtualBox-5.0.0_RC1-100731-Win.exe -extract" its will return pop-up tell where is extracted folder
- in extracted folder extract "VirtualBox-5.0.0_RC1-r100731-MultiArch_amd64.msi" by 7-Zip or any similar
- in msi extracted folder rename all files by remove file_ in front of them
- copy "VBoxNetFltNobj.sys" and "VBoxNetFlt.sys" to C:\Windows\System32\
- Open "CMD", you can use search bar to get this, Right Click and Select Run as Administrator run command "regsvr32.exe /s VBoxNetFltNobj.sys" run command "regsvr32.exe /s VBoxNetFlt.sys"
- Open "Network Connections", you can use search bar to get this, Right Click on any real network adapter select Properties select Install select Service select "Have Disk" and browse to "VBoxDrv.inf" select "VirtualBox NDIS6 Bridged Networking Driver" after finish install you should see its avaliable in this connection
On Start Menu Right Click on "Orcle VM VirtualBox" select open file location
Right Click on Shortcut then select properties on tab "Compatibility" checked "Run this Program as Administrator"
!!! this very important to run application with adminstrator if not you will lose host-only network adapter
- Open "Virtual Box" select file > preference select network then select Host On Network select edit change ip to 192.168.56.1 and netmask to 255.255.255.0
- Now you can use both host-only and bridge network on your guest
I think reason why normal installation was error is about Administrator access level when regis service and run application
Sorry for my bad english and this is so long procedure
Hope this will work for you too. ^_^!
Adding to the evolving nature of the answer to this question, starting with r2016b, MATLAB will implicitly expand singleton dimensions, removing the need for bsxfun
in many cases.
From the r2016b release notes:
Implicit Expansion: Apply element-wise operations and functions to arrays with automatic expansion of dimensions of length 1
Implicit expansion is a generalization of scalar expansion. With scalar expansion, a scalar expands to be the same size as another array to facilitate element-wise operations. With implicit expansion, the element-wise operators and functions listed here can implicitly expand their inputs to be the same size, as long as the arrays have compatible sizes. Two arrays have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. See Compatible Array Sizes for Basic Operations and Array vs. Matrix Operations for more information.
Element-wise arithmetic operators — +, -, .*, .^, ./, .\ Relational operators — <, <=, >, >=, ==, ~= Logical operators — &, |, xor Bit-wise functions — bitand, bitor, bitxor Elementary math functions — max, min, mod, rem, hypot, atan2, atan2d
For example, you can calculate the mean of each column in a matrix A, and then subtract the vector of mean values from each column with A - mean(A).
Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed, better memory usage, and improved readability of code.
Use java.util.regex.Pattern class's static method matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9
String obj : String object you want to check either it contain special character or not.
It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false
Example.
String isin = "12GBIU34RT12";<br>
if(Pattern.matches("[a-zA-Z0-9]+", isin)<br>{<br>
System.out.println("Valid isin");<br>
}else{<br>
System.out.println("Invalid isin");<br>
}
Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
I develop a library that serves this purpose: galimatias. It parses URL the same way web browsers do. That is, if a URL works in a browser, it will be correctly parsed by galimatias.
In this case:
// Parse
io.mola.galimatias.URL.parse(
"http://search.barnesandnoble.com/booksearch/first book.pdf"
).toString()
Will give you: http://search.barnesandnoble.com/booksearch/first%20book.pdf
. Of course this is the simplest case, but it'll work with anything, way beyond java.net.URI
.
You can check it out at: https://github.com/smola/galimatias
You don't need to uninstall WebDAV, just add these lines to the web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.
You could always use a regular expression though:
if SomeString.match(/^abc/)
# SomeString starts with abc
^
means "start of string" in regular expressions
Here are the PHP mail settings I use:
//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "[email protected]";
//data
$msg = "Your MSG <br>\n";
//Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;
mail($to,$subject,$msg,$headers);
echo "Mail Sent.";
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
Check the value of "views" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.
if (isset($_SESSION['views'])) {
if (!is_numeric($_SESSION['views'])) {
echo "CRAP!";
}
++$_SESSION['views'];
} else {
$_SESSION['views'] = 1;
}
Assuming your div has some CSS classes already...
<div id="classMe" CssClass="first"></div>
The following won't replace existing definitions:
ClassMe.CssClass += " second";
And if you are not sure until the very last moment...
string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";
Try that:
var defaultEmailNews = "Email address";
$('input[name=email]').focus(function() {
if($(this).val() == defaultEmailNews) $(this).val("");
});
$('input[name=email]').focusout(function() {
if($(this).val() == "") $(this).val(defaultEmailNews);
});
To make a single icon be usable by all your action bars you can do this in your Android Manifest.
<application
android:logo="@drawable/Image">
...
</application>
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
For sure it is important to understand the behavior of interface and abstract class in OOP (and how languages handle them), but I think it is also important to understand what exactly each term means. Can you imagine the if
command not working exactly as the meaning of the term? Also, actually some languages are reducing, even more, the differences between an interface and an abstract... if by chance one day the two terms operate almost identically, at least you can define yourself where (and why) should any of them be used for.
If you read through some dictionaries and other fonts you may find different meanings for the same term but having some common definitions. I think these two meanings I found in this site are really, really good and suitable.
Interface:
A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively.
Abstract:
Something that concentrates in itself the essential qualities of anything more extensive or more general, or of several things; essence.
Example:
You bought a car and it needs fuel.
Your car model is XYZ
, which is of genre ABC
, so it is a concrete car, a specific instance of a car. A car is not a real object. In fact, it is an abstract set of standards (qualities) to create a specific object. In short, Car is an abstract class, it is "something that concentrates in itself the essential qualities of anything more extensive or more general".
The only fuel that matches the car manual specification should be used to fill up the car tank. In reality, there is nothing to restrict you to put any fuel but the engine will work properly only with the specified fuel, so it is better to follow its requirements. The requirements say that it accepts, as other cars of the same genre ABC
, a standard set of fuel.
In an Object Oriented view, fuel for genre ABC
should not be declared as a class because there is no concrete fuel for a specific genre of car out there. Although your car could accept an abstract class Fuel or VehicularFuel, you must remember that your only some of the existing vehicular fuel meet the specification, those that implement the requirements in your car manual. In short, they should implement the interface ABCGenreFuel
, which "... enables separate and sometimes incompatible elements to coordinate effectively".
In addition, I think you should keep in mind the meaning of the term class, which is (from the same site previously mentioned):
Class:
A number of persons or things regarded as forming a group by reason of common attributes, characteristics, qualities, or traits; kind;
This way, a class (or abstract class) should not represent only common attributes (like an interface), but some kind of group with common attributes. An interface doesn't need to represent a kind. It must represent common attributes. This way, I think classes and abstract classes may be used to represent things that should not change its aspects often, like a human being a Mammal, because it represents some kinds. Kinds should not change themselves that often.
function(url,callback){
request(url).on('data',(data) => {
try{
var json = JSON.parse(data);
}
catch(error){
callback("");
}
callback(json);
})
}
You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .
You can try using this code:
protected ServiceConnection mServerConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "onServiceDisconnected");
}
}
public void start() {
// mContext is defined upper in code, I think it is not necessary to explain what is it
mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
mContext.startService(intent);
}
public void stop() {
mContext.stopService(new Intent(mContext, ServiceRemote.class));
mContext.unbindService(mServerConn);
}
It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser;
<?php
header('Content-Type:text/html');
?>
<p>Hello</p>
You will see:
hello
(note that you will get the same results if you miss off the header line in this case - text/html is php's default)
Change it to text/plain
<?php
header('Content-Type:text/plain');
?>
<p>Hello</p>
You will see:
<p>Hello</p>
Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request:
<?php
header('Content-Type:text/html');
print "Your name is " . $_GET['name']
Someone can put a link to a URL like http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe.
Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.
Please use below command to change heap size to 6GB
export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:
namespace X
{
namespace Y
{
class A;
void func(A* a) { ... } // incomplete type here!
}
}
...but, in class A was defined like this:
namespace X
{
class A { ... };
}
Thus, A was defined as X::A
, but I was using it as X::Y::A
.
The fix obviously is to move the forward reference to its proper place like so:
namespace X
{
class A;
namespace Y
{
void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
}
}
In my case I ran the following command and it worked (not that I was expecting it to):
sudo pip uninstall pip
Which resulted in:
Uninstalling pip-6.1.1:
/Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
/Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
/Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
<and all the other stuff>
...
/usr/local/bin/pip
/usr/local/bin/pip2
/usr/local/bin/pip2.7
Proceed (y/n)? y
Successfully uninstalled pip-6.1.1
You could subtract the total length from the count of non-nan values:
count_nan = len(df) - df.count()
You should time it on your data. For small Series got a 3x speed up in comparison with the isnull
solution.
To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");
Best way is to update the serve script command in your package.json
file. Just append --port 3000
like so:
"scripts": {
"serve": "vue-cli-service serve --port 3000",
"build": "vue-cli-service build",
"inspect": "vue-cli-service inspect",
"lint": "vue-cli-service lint"
},
If there are up to 10 strings then you should use a list in order to iterate through all values.
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
In Python 3.x, 5 / 2
will return 2.5
and 5 // 2
will return 2
. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division
, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, 5.0 // 2
will return 2.0
since that's the floor division result of the operation.
You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator
Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:
pd.read_csv('../../../data_folder/data.csv')
Will go 3 levels up and then into a data_folder (assuming it's there) Or
pd.read_csv('data_folder/data.csv')
assuming your data_folder is in the same directory as your .py file.
Thanks - this helped me to understand better ansd solve a problem I had. The JQuery provided to get the text of selectedItem did NOT wwork for me I changed it to
$(function () {
$("#SelectedVender").on("change", function () {
$("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
});
});
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
You can update all outdated packages like so:
brew install `brew outdated`
or
brew outdated | xargs brew install
or
brew upgrade
This is from the brew site..
for upgrading individual formula:
brew install formula-name && brew cleanup formula-name
I'd highly suggest you use this instead of creating the animation file because it's a much better solution. Android Studio already provides default animation
you can use without creating any new XML file. The animations' names are android.R.anim.slide_in_left and android.R.anim.slide_out_right and you can use them as follows:
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();
Output:
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.
http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx
There is Prometheus GPU Metrics Exporter (PGME) that leverages the nvidai-smi binary. You may try this out. Once you have the exporter running, you can access it via http://localhost:9101/metrics. For two GPUs, the sample result looks like this:
temperature_gpu{gpu="TITAN X (Pascal)[0]"} 41
utilization_gpu{gpu="TITAN X (Pascal)[0]"} 0
utilization_memory{gpu="TITAN X (Pascal)[0]"} 0
memory_total{gpu="TITAN X (Pascal)[0]"} 12189
memory_free{gpu="TITAN X (Pascal)[0]"} 12189
memory_used{gpu="TITAN X (Pascal)[0]"} 0
temperature_gpu{gpu="TITAN X (Pascal)[1]"} 78
utilization_gpu{gpu="TITAN X (Pascal)[1]"} 95
utilization_memory{gpu="TITAN X (Pascal)[1]"} 59
memory_total{gpu="TITAN X (Pascal)[1]"} 12189
memory_free{gpu="TITAN X (Pascal)[1]"} 1738
memory_used{gpu="TITAN X (Pascal)[1]"} 10451
best easy and working solution i have found is, working on following browsers
Safari
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h2>Poly Filler Script for Date/Time</h2>
<form method="post" action="">
<input type="date" />
<br/><br/>
<input type="time" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
webshims.setOptions('waitReady', false);
webshims.setOptions('forms-ext', {type: 'date'});
webshims.setOptions('forms-ext', {type: 'time'});
webshims.polyfill('forms forms-ext');
</script>
</body>
</html>
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
git stash
is your friend.
If you have not made the commit yet, just run git stash
. This will save away all of your changes.
Switch to the branch you want the changes on and run git stash pop
.
There are lots of uses for git stash. This is certainly one of the more useful reasons.
An example:
# work on some code
git stash
git checkout correct-branch
git stash pop
Try to look at the following link: Python | change text color in shell
Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines
In general solution is to use ANSI codes while printing your string.
There is a solution that performs exactly what you need.
I was getting the same issue in windows. I fixed it by
You can select the shapes within a slide (Word Art also) and right click on the selection and choose "Save As Picture". It will save as a transparent PNG.
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel
constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
also has setHorizontalAlignment
:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout
:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
docker rm $(docker ps -a | awk '/myimage:mytag/{print $1}')
func sum(array : [Int]) -> Int{
var sum = 0
array.forEach { (item) in
sum = item + sum
}
return sum
}
func susetNumbers(array :[Int], target : Int, subsetArray: [Int],result : inout [[Int]]) -> [[Int]]{
let s = sum(array: subsetArray)
if(s == target){
print("sum\(subsetArray) = \(target)")
result.append(subsetArray)
}
for i in 0..<array.count{
let n = array[i]
let remaning = Array(array[(i+1)..<array.count])
susetNumbers(array: remaning, target: target, subsetArray: subsetArray + [n], result: &result)
}
return result
}
var resultArray = [[Int]]()
let newA = susetNumbers(array: [1,2,3,4,5], target: 5, subsetArray: [],result:&resultArray)
print(resultArray)
You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:
credits: {
enabled: false
},
Well there are a bunch of different utilities for this, e.g. Apache Commons Lang String Utils
but in the end, it has to loop over the string to count the occurrences one way or another.
Note also that the countMatches
method above has the following signature so will work for substrings as well.
public static int countMatches(String str, String sub)
The source for this is (from here):
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
I was curious if they were iterating over the string or using Regex.
You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation
They use JQuery validation.
jquery.validate.js
jquery.validate.min.js
jquery-1.7.1.min.js
And you'll get the source code there.
<form id="registration-form" class="form-horizontal">
<h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
<div class="form-control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">User Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="username" id="username"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="password" id="password">
</div>
</div>
<div class="form-control-group">
<label class="control-label" for="name"> Retype Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message">Your Address</label>
<div class="controls">
<textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
<input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-large">Register</button>
<button type="reset" class="btn">Cancel</button></div>
</form>
And The JQuery :
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/
Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/
happy coding.
Another example using Blob()
Code:
function save(url, params, fileName){
$http.get(url, {params: params}).success(function(exporter) {
var blob = new Blob([exporter], {type: "text/plain;charset=utf-8;"});
saveAs(blob, fileName);
}).error(function(err) {
console.log('err', err);
});
};
// Save as Code
function saveAs(blob, fileName){
var url = window.URL.createObjectURL(blob);
var doc = document.createElement("a");
doc.href = url;
doc.download = fileName;
doc.click();
window.URL.revokeObjectURL(url);
}
iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.
Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.
This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.
#import <AVFoundation/AVFoundation.h>
- (void) turnTorchOn:(BOOL)on {
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
torchIsOn = YES;
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}
First you are not in current folder...
Please use Cd to join to the folder name to access in project folder requeried...
Then use the code
A simple  
; between input fields would do the job easily...
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)
CSS
div.places {
width : 100px;
}
div.places span {
white-space:nowrap;
overflow:hidden;
}
HTML
<div class="places">
<span>This is my house</span>
</div>
<div class="places">
<span>And my house are your house</span>
</div>
<div class="places">
<span>This placename is most certainly too wide to fit</span>
</div>
JavaScript (with jQuery)
// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
var obj = $(item).find("span");
if (obj.length) {
var placename = $(obj).text();
if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
var limit = 0;
do {
limit++;
placename = placename.substring(0, placename.length - 1);
$(obj).text(placename + "...");
} while ($(obj).width() > $(item).width() && limit < 1000)
}
}
});
You can also use npm for this by adding an entry to the scripts
element of your package.json
file. E.g.
"launch-ios": "react-native run-ios --simulator \"iPad Air 2\""
Then to use this: npm run launch-ios
I wrote this JS function dump()
to work like PHP's var_dump()
.
To show the contents of the variable in an alert window: dump(variable)
To show the contents of the variable in the web page: dump(variable, 'body')
To just get a string of the variable: dump(variable, 'none')
/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
out = '';
for (var i = 0; i < num; i++) {
out += str;
}
return out;
}
/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
v: The variable
howDisplay: "none", "body", "alert" (default)
recursionLevel: Number of times the function has recursed when entering nested
objects or arrays. Each level of recursion adds extra space to the
output to indicate level. Set to 0 by default.
Return Value:
A string of the variable's contents
Limitations:
Can't pass an undefined variable to dump().
dump() can't distinguish between int and float.
dump() can't tell the original variable type of a member variable of an object.
These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;
var vType = typeof v;
var out = vType;
switch (vType) {
case "number":
/* there is absolutely no way in JS to distinguish 2 from 2.0
so 'number' is the best that you can do. The following doesn't work:
var er = /^[0-9]+$/;
if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
out = 'int';
}
*/
break;
case "boolean":
out += ": " + v;
break;
case "string":
out += "(" + v.length + '): "' + v + '"';
break;
case "object":
//check if null
if (v === null) {
out = "null";
}
//If using jQuery: if ($.isArray(v))
//If using IE: if (isArray(v))
//this should work for all browsers according to the ECMAScript standard:
else if (Object.prototype.toString.call(v) === '[object Array]') {
out = 'array(' + v.length + '): {\n';
for (var i = 0; i < v.length; i++) {
out += repeatString(' ', recursionLevel) + " [" + i + "]: " +
dump(v[i], "none", recursionLevel + 1) + "\n";
}
out += repeatString(' ', recursionLevel) + "}";
}
else {
//if object
let sContents = "{\n";
let cnt = 0;
for (var member in v) {
//No way to know the original data type of member, since JS
//always converts it to a string and no other way to parse objects.
sContents += repeatString(' ', recursionLevel) + " " + member +
": " + dump(v[member], "none", recursionLevel + 1) + "\n";
cnt++;
}
sContents += repeatString(' ', recursionLevel) + "}";
out += "(" + cnt + "): " + sContents;
}
break;
default:
out = v;
break;
}
if (howDisplay == 'body') {
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
else if (howDisplay == 'alert') {
alert(out);
}
return out;
}
This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5
You can simply chain as many split-path
as you need:
$rootPath = $scriptPath | split-path | split-path
An int
array without elements is not necessarily null
. It will only be null
if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:
public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
}
When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.
Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:
public void IncreaseCapacity(int increment)
{
var itemsList = (List<T>)Items;
var total = itemsList.Count + increment;
if (itemsList.Capacity < total)
{
itemsList.Capacity = total;
}
}
Dynamic analysis methods
Here I describe a few dynamic analysis methods.
Dynamic methods actually run the program to determine the call graph.
The opposite of dynamic methods are static methods, which try to determine it from the source alone without running the program.
Advantages of dynamic methods:
Disadvantages of dynamic methods:
KcacheGrind
https://kcachegrind.github.io/html/Home.html
Test program:
int f2(int i) { return i + 2; }
int f1(int i) { return f2(2) + i + 1; }
int f0(int i) { return f1(1) + f2(2); }
int pointed(int i) { return i; }
int not_called(int i) { return 0; }
int main(int argc, char **argv) {
int (*f)(int);
f0(1);
f1(1);
f = pointed;
if (argc == 1)
f(1);
if (argc == 2)
not_called(1);
return 0;
}
Usage:
sudo apt-get install -y kcachegrind valgrind
# Compile the program as usual, no special flags.
gcc -ggdb3 -O0 -o main -std=c99 main.c
# Generate a callgrind.out.<PID> file.
valgrind --tool=callgrind ./main
# Open a GUI tool to visualize callgrind data.
kcachegrind callgrind.out.1234
You are now left inside an awesome GUI program that contains a lot of interesting performance data.
On the bottom right, select the "Call graph" tab. This shows an interactive call graph that correlates to performance metrics in other windows as you click the functions.
To export the graph, right click it and select "Export Graph". The exported PNG looks like this:
From that we can see that:
_start
, which is the actual ELF entry point, and contains glibc initialization boilerplatef0
, f1
and f2
are called as expected from one anotherpointed
is also shown, even though we called it with a function pointer. It might not have been called if we had passed a command line argument.not_called
is not shown because it didn't get called in the run, because we didn't pass an extra command line argument.The cool thing about valgrind
is that it does not require any special compilation options.
Therefore, you could use it even if you don't have the source code, only the executable.
valgrind
manages to do that by running your code through a lightweight "virtual machine". This also makes execution extremely slow compared to native execution.
As can be seen on the graph, timing information about each function call is also obtained, and this can be used to profile the program, which is likely the original use case of this setup, not just to see call graphs: How can I profile C++ code running on Linux?
Tested on Ubuntu 18.04.
gcc -finstrument-functions
+ etrace
https://github.com/elcritch/etrace
-finstrument-functions
adds callbacks, etrace parses the ELF file and implements all callbacks.
I couldn't get it working however unfortunately: Why doesn't `-finstrument-functions` work for me?
Claimed output is of format:
\-- main
| \-- Crumble_make_apple_crumble
| | \-- Crumble_buy_stuff
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | \-- Crumble_prepare_apples
| | | \-- Crumble_skin_and_dice
| | \-- Crumble_mix
| | \-- Crumble_finalize
| | | \-- Crumble_put
| | | \-- Crumble_put
| | \-- Crumble_cook
| | | \-- Crumble_put
| | | \-- Crumble_bake
Likely the most efficient method besides specific hardware tracing support, but has the downside that you have to recompile the code.
Try this one:
self.GetHierarchyNodeList = function (data, index, event)
{
debugger;
if (event.type != "change") {
return;
}
}
event.type == "change"
event.type == "load"
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notification
objects as SSEs stream into the browser:
var source = new EventSource('/events');
source.on('message', message => {
var notification = new Notification(message.title, {
body: message.body
});
});
A bit old, but this article by Eric Bidelman explains the basics of SSE and provides some server code examples as well.
in your you have capital letters for html.you wrote it as THIS IS NOT CORRECT!!! your browser will not understand it as html5.
Interestingly, a ComboBox with DropDownStyle=Simple has pretty much exactly the behaviour you are looking for, I think.
(If you reduce the height of the control to not show the list - and then by a couple of pixels more - there's no effective difference between the ComboBox and the TextBox.)
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
You can ssh
directly from the Terminal on Mac, but you need to use a .PEM
key rather than the putty
.PPK
key. You can use PuttyGen on Windows to convert from .PEM
to .PPK
, I'm not sure about the other way around though.
You can also convert the key using putty
for Mac via port
or brew
:
sudo port install putty
or
brew install putty
This will also install puttygen
. To get puttygen
to output a .PEM
file:
puttygen privatekey.ppk -O private-openssh -o privatekey.pem
Once you have the key, open a terminal window and:
ssh -i privatekey.pem [email protected]
The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.
chmod go-rw privatekey.pem
Implementing exceptions in c by Eric Roberts
Chapter 4 of C Interfaces and Implementations by Hanson.
A Discipline of Error Handling by Doug Moen
Implementing Exceptions in C (details the article of E Roberts)
I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an =
operator. This is the easiest way.
So basically:
If string1 = string2 Then
'do a thing
End If
strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$seconds_diff = $ts2 - $ts1;
First of all you need to create a surface once and keep it somewhere handy. Example:
var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);
domNode
is usually an unadorned <div>
, which is used as a placeholder for a surface.
You can clear everything on the surface in one go (all existing shape objects will be invalidated, don't use them after that):
surface.clear();
All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/
.
var server = app.listen();
server.setTimeout(500000);
inspired by https://github.com/expressjs/express/issues/3330
or
app.use(function(req, res, next){
res.setTimeout(500000, function(){
// call back function is called when request timed out.
});
next();
});
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever.
No. You should never just add a link to an external script like this in WordPress. Enqueuing them through the functions.php file ensures that scripts are loaded in the correct order.
Failure to enqueue them may result in your script not working, although it is written correctly.
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);?
Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
For those using python 3+
import requests
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
I can suggest the following method:
Convert the number to a string ? convert the string into an array of characters ? convert the array of characters into an array of integers
Here comes my code:
public class test {
public static void main(String[] args) {
int num1 = 123456; // Example 1
int num2 = 89786775; // Example 2
String str1 = Integer.toString(num1); // Converts num1 into String
String str2 = Integer.toString(num2); // Converts num2 into String
char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char
int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it
for(int i=0;i<ch1.length;i++) // Watch the ASCII table
t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want
for(int i=0;i<ch2.length;i++) // Watch the ASCII table
t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
}
}
Also, you can use bool method(s)
Query :
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()
select r;
DataTable newDT = query.CopyToDataTable();
Method:
bool isValid(string userName)
{
if(userName == "XXXX" || userName == "YYYY")
return false;
else return true;
}
This is probably desirable for backwards compatibility.
Python3 breaks backwards compatibility, and programs invoking 'python' probably expect python2. You probably have many programs and scripts which you are not even aware of which expect python=python2, and changing this would break those programs and scripts.
The answer you are probably looking for is You should not change this.
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
If you are confused about how to start the latest version of python, it is at least the case on Linux that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
Motivation
Many data sets are large enough that we need to concern ourselves with speed/efficiency. So I offer this solution in that spirit. It happens to also be succinct.
For the sake of comparison, let's drop the index
column
df = data_set.drop('index', 1)
Solution
I'll propose the use of zip
and map
list(zip(*map(df.get, df)))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
It happens to also be flexible if we wanted to deal with a specific subset of columns. We'll assume the columns we've already displayed are the subset we want.
list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))
[('2012-02-17', 24.75, 25.03),
('2012-02-16', 25.0, 25.07),
('2012-02-15', 24.99, 25.15),
('2012-02-14', 24.68, 25.05),
('2012-02-13', 24.62, 24.77),
('2012-02-10', 24.38, 24.61)]
Turn's out records
is quickest followed by asymptotically converging zipmap
and iter_tuples
I'll use a library simple_benchmarks
that I got from this post
from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()
import pandas as pd
import numpy as np
def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))
funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
b.add_function()(func)
def creator(n):
return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})
@b.add_arguments('Rows in DataFrame')
def argument_provider():
for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
yield n, creator(n)
r = b.run()
Check the results
r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))
tuple_comp iter_namedtuples iter_tuples records zipmap
100 2.905662 6.626308 3.450741 1.469471 1.000000
316 4.612692 4.814433 2.375874 1.096352 1.000000
1000 6.513121 4.106426 1.958293 1.000000 1.316303
3162 8.446138 4.082161 1.808339 1.000000 1.533605
10000 8.424483 3.621461 1.651831 1.000000 1.558592
31622 7.813803 3.386592 1.586483 1.000000 1.515478
100000 7.050572 3.162426 1.499977 1.000000 1.480131
r.plot()
Put the list numbers in parentheses instead of followed by a period.
(1) item 1
(2) item 2
code block
(3) item 3
Here's the technical answer (expanding on Rowland Shaw's answer).
The Is keyword checks whether the two operands are references to the same object memory, and only returns true if this is the case. I believe it is functionally equivalent to Object.ReferenceEquals. The IsNot keyword is simply shorthand syntax for writing Not ... Is ...
, nothing more.
The = (equality) operator compares values and in this case (as in many others) is equivalent to String.Equals. Now, the <> (inequality) operator does not quite have the same analogy as the Is and IsNot keywords, since it can be overriden separately from the = operator depending on the class. I believe the case should always be that it returns the logical inverse of the = operator (and certainly is in the case of String), and just allows for a more efficient comparison to made when testing for inequality rather than equality.
When dealing with strings, unless you actually mean to compare references, always use the = operator (or String.Equals I suppose). In your case, because you are testing for null (Nothing), it seems you need to use the Is or IsNot keyword (the equality operator will fail because it can't compare the values of null objects). Syntactically, the IsNot keyword is a bit nicer here, so go with that.
Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
let options = new RequestOptions({ headers: headers });
return this.http
.put(url, JSON.stringify(student), options)
There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.
keytool
ships with Android Studio as part of the JRE needed to run Android Studio.
On Windows its: C:\Program Files\Android\Android Studio\jre\bin\keytool.exe
On Mac its: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool
Add it to your environment variables then run the keytool command again.
To do something after certain div load from function .load()
.
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
Use widget as PasswordInput
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.
Then you controller is probably like this:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
@RequestParam Map<String, String> name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
...
PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
...
list = service.getPatient(patientProfileDto);
return list;
}
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
context.Widgets.RemoveRange(context.Widgets.Where(w => w.WidgetId == widgetId).ToList()); db.SaveChanges();
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.
The following sets the username and password if provided or just adds the host and port if no username and password is set.
task setHttpProxyFromEnv {
def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
for (e in System.getenv()) {
def key = e.key.toUpperCase()
if (key in map) {
def base = map[key]
//Get proxyHost,port, username, and password from http system properties
// in the format http://username:password@proxyhost:proxyport
def (val1,val2) = e.value.tokenize( '@' )
def (val3,val4) = val1.tokenize( '//' )
def(userName, password) = val4.tokenize(':')
def url = e.value.toURL()
//println " - systemProp.${base}.proxy=${url.host}:${url.port}"
System.setProperty("${base}.proxyHost", url.host.toString())
System.setProperty("${base}.proxyPort", url.port.toString())
System.setProperty("${base}.proxyUser", userName.toString())
System.setProperty("${base}.proxyPassword", password.toString())
}
}
}
Use .val()
to get value of textarea and use $.trim()
to empty spaces.
$(document).ready(function () {
if ($.trim($("textarea").val()) != "") {
alert($("textarea").val());
}
});
Or, Here's what I would do for clean code,
$(document).ready(function () {
var val = $.trim($("textarea").val());
if (val != "") {
alert(val);
}
});
Use c_str() to convert the std::string to const char *.
cout << "String is : " << text.c_str() << endl ;
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
Another gotcha for this kind of problem: avoid running pear within a Unix shell (e.g., Git Bash or Cygwin) on a Windows machine. I had the same problem and the path fix suggested above didn't help. Switched over to a Windows shell, and the pear command works as expected.
The warning is due to you attempting to add an integer (int shift = 3
) to a character value. You can change the data type to char
if you want to avoid that.
A char
is 16 bits, an int
is 32.
char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;
As an aside, you can simplify the following:
char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'};
To:
char[] message = "onceuponatime".toCharArray();
The only effective way I've found to wipe out the PHP_AUTH_DIGEST
or PHP_AUTH_USER
AND PHP_AUTH_PW
credentials is to call the header HTTP/1.1 401 Unauthorized
.
function clear_admin_access(){
header('HTTP/1.1 401 Unauthorized');
die('Admin access turned off');
}
You could also change the viewChild 'type' to NgForm as in:
@ViewChild('loginForm') loginForm: NgForm;
And then reference your controls in the same way @Julia mentioned:
private login(formData: any): void {
this.authService.login(formData).subscribe(res => {
alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
}, error => {
this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
this.loginForm.controls['email'].setErrors({ 'incorrect': true});
this.loginForm.controls['password'].setErrors({ 'incorrect': true});
});
}
Setting the Errors to null will clear out the errors on the UI:
this.loginForm.controls['email'].setErrors(null);
It's because there is no long
in javascript.
The possible values for page-break-after are: auto, always, avoid, left, right
I believe that you can’t use thie page-break-after property on absolutely positioned elements.
In my case, I was trying to build and get APK for an old Unity 3D project (so that I can play the game in my Android phone). I was using the most recent Android Studio version, and all the SDK packages I could download via SDK Manager in Android Studio. SDK Packages was located in
C:/Users/Onat/AppData/Local/Android/Sdk
And the error message I got was the same except the JDK (Java Development Kit) version "jdk-12.0.2" . JDK was located in
C:\Program Files\Java\jdk-12.0.2
And Environment Variable in Windows was JAVA_HOME : C:\Program Files\Java\jdk-12.0.2
After 3 hours of research, I found out that Unity does not support JDK 10. As told in https://forum.unity.com/threads/gradle-build-failed-error-could-not-determine-java-version-from-10-0-1.532169/
. My suggestion is:
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Computer/This PC>Properties>Advanced System Settings>Environment Variables>New>Variable Name: JAVA_HOME>Variable Value: [YOUR JDK Path, Mine was "C:\Program Files\Java\jdk1.8.0_221"]
Edit > Preferences > External Tools and fill in the JDK path (Mine was "C:\Program Files\Java\jdk1.8.0_221")
.Android Studio > SDK Manager > Android SDK > Android SDK Location
.)Using index
:
>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'
The index will give you the position of :
in string, then you can slice it.
If you want to use regex:
>>> import re
>>> re.match("(.*?):",string).group()
'Username'
match
matches from the start of the string.
you can also use itertools.takewhile
>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'