I know late but @TadasPa's answer can be adjusted a little by using
TCreator: new() => T
instead of
TCreator: { new (): T; }
so the result should look like this
class A {
}
class B<T> {
Prop: T;
constructor(TCreator: new() => T) {
this.Prop = new TCreator();
}
}
var test = new B<A>(A);
Within your onDropDownChange
handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success
and error
options. In the success
option, use the data contained in the data
argument to do whatever rendering you need to do. Remember these are asynchronous by default!
function onDropDownChange(e) {
var url = '/Home/Index/' + e.value;
$.ajax({
url: url,
data: {}, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function(data) { alert('got here with data'); },
error: function() { alert('something bad happened'); }
});
}
jQuery's AJAX documentation is here.
You can add it programmatically or in the markup, but if you add it programmatically, rather than Add
the item, you should Insert
it as position zero so that it is the first item:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
The default item is expected to be the first item in the list. If you just Add
it, it will be on the bottom and will not be selected by default.
Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine
(e.g. VirtualPathProviderViewEngine
) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.
System.Web.Mvc.WebFormViewEngine
Design Goals:
A view engine that is used to render a Web Forms page to the response.
Pros:
Cons:
Example:
<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
<% foreach(var p in model){%>
<li><%=p.Name%></li>
<%}%>
</ul>
<%}else{%>
<p>No products available</p>
<%}%>
Design Goals:
Pros:
Cons:
Con Example #1 (notice the placement of "string[]..."):
@{
<h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
Design goals:
- Respect HTML as first-class language as opposed to treating it as "just text".
- Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
- Enforce strict Model-View separation
Design Goals:
The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.
Pros:
Cons:
Example:
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>The following items are in the list:</p>
<ul><%for element in list: output "<li>${element}</li>"%></ul>
<p>I hope that you would like Brail</p>
</body>
</html>
Hasic uses VB.NET's XML literals instead of strings like most other view engines.
Pros:
Cons:
Example:
Protected Overrides Function Body() As XElement
Return _
<body>
<h1>Hello, World</h1>
</body>
End Function
Design Goals:
NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.
Pros:
WebFormViewEngine
Design Goals:
.NET port of Rails Haml view engine. From the Haml website:
Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.
Pros:
Cons:
Example:
@type=IEnumerable<Product>
- if(model.Any())
%ul
- foreach (var p in model)
%li= p.Name
- else
%p No products available
NVelocityViewEngine (MvcContrib)
Design Goals:
A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.
Pros:
Cons:
Example:
#foreach ($p in $viewdata.Model)
#beforeall
<ul>
#each
<li>$p.Name</li>
#afterall
</ul>
#nodata
<p>No products available</p>
#end
Design Goals:
SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).
Pros:
Cons:
Example:
<c:if test="${not fn:empty(Page.Tiles)}">
<p class="note">
<fmt:message key="page.tilesSupport"/>
</p>
</c:if>
Design Goals:
The idea is to allow the html to dominate the flow and the code to fit seamlessly.
Pros:
Cons:
Example:
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
<Form style="background-color:olive;">
<Label For="username" />
<TextBox For="username" />
<ValidationMessage For="username" Message="Please type a valid username." />
</Form>
StringTemplate View Engine MVC
Design Goals:
- Lightweight. No page classes are created.
- Fast. Templates are written to the Response Output stream.
- Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
- Dynamic. Templates can be generated on the fly in code.
- Flexible. Templates can be nested to any level.
- In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.
Pros:
Cons:
Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.
Pros:
Cons:
Design Goals:
Builds views from familiar XSLT
Pros:
Cons:
Here is a class I wrote to do this for ASP.NETCore RC2. I use it so I can generate html email using Razor.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System.IO;
using System.Threading.Tasks;
namespace cloudscribe.Web.Common.Razor
{
/// <summary>
/// the goal of this class is to provide an easy way to produce an html string using
/// Razor templates and models, for use in generating html email.
/// </summary>
public class ViewRenderer
{
public ViewRenderer(
ICompositeViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IHttpContextAccessor contextAccesor)
{
this.viewEngine = viewEngine;
this.tempDataProvider = tempDataProvider;
this.contextAccesor = contextAccesor;
}
private ICompositeViewEngine viewEngine;
private ITempDataProvider tempDataProvider;
private IHttpContextAccessor contextAccesor;
public async Task<string> RenderViewAsString<TModel>(string viewName, TModel model)
{
var viewData = new ViewDataDictionary<TModel>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = model
};
var actionContext = new ActionContext(contextAccesor.HttpContext, new RouteData(), new ActionDescriptor());
var tempData = new TempDataDictionary(contextAccesor.HttpContext, tempDataProvider);
using (StringWriter output = new StringWriter())
{
ViewEngineResult viewResult = viewEngine.FindView(actionContext, viewName, true);
ViewContext viewContext = new ViewContext(
actionContext,
viewResult.View,
viewData,
tempData,
output,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return output.GetStringBuilder().ToString();
}
}
}
}
We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good
Many of us get this error after setting up the eclipse and server for first time. This solution is -
go to server tab
select the properties option of your respective server and expand it
in the properties window , select general tab -> click Switch Location -> click apply ->click ok.
This may work .
20090320093349
SELECT CONVERT(VARCHAR,@date,112) +
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)
The answer is no longer valid. Since I have encountered the issue with older Windows ruby right now I'll post the answer.
When I wanted to install an activesupport gem:
gem in activesupport --version 5.1.6
ERROR: Could not find a valid gem 'activesupport' (= 5.1.6), here is why:
Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B
: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)
The following steps need to copy only the certificates from newer windows ruby. Take the latest ruby (or at least ruby 2.4.0) and do the following:
copy certificates from these directories (adjust to your needs):
C:\prg_sdk\rubies\Ruby-2.4\lib\ruby\2.4.0\rubygems\ssl_certs\rubygems.org
C:\prg_sdk\rubies\Ruby-2.4\lib\ruby\2.4.0\rubygems\ssl_certs\index.rubygems.org
to destination (again adjust to what you need):
C:\prg_sdk\rubies\Ruby231-p112-x64\lib\ruby\2.3.0\rubygems\ssl_certs
This example has a number of different aspects to it. I will mention a couple of points that I don't think have been explicitly covered elsewhere.
Protecting the secret in transit
The first thing to note is that accessing the dropbox API using their app authentication mechanism requires you to transmit your key and secret. The connection is HTTPS which means that you can't intercept the traffic without knowing the TLS certificate. This is to prevent a person intercepting and reading the packets on their journey from the mobile device to the server. For normal users it is a really good way of ensuring the privacy of their traffic.
What it is not good at, is preventing a malicious person downloading the app and inspecting the traffic. It is really easy to use a man-in-the-middle proxy for all traffic into and out of a mobile device. It would require no disassembly or reverse engineering of code to extract the app key and secret in this case due to the nature of the Dropbox API.
You could do pinning which checks that the TLS certificate you receive from the server is the one you expect. This adds a check to the client and makes it more difficult to intercept the traffic. This would make it harder to inspect the traffic in flight, but the pinning check happens in the client, so it would likely still be possible to disable the pinning test. It does make it harder though.
Protecting the secret at rest
As a first step, using something like proguard will help to make it less obvious where any secrets are held. You could also use the NDK to store the key and secret and send requests directly, which would greatly reduce the number of people with the appropriate skills to extract the information. Further obfuscation can be achieved by not storing the values directly in memory for any length of time, you can encrypt them and decrypt them just before use as suggested by another answer.
More advanced options
If you are now paranoid about putting the secret anywhere in your app, and you have time and money to invest in more comprehensive solutions, then you might consider storing the credentials on your servers (presuming you have any). This would increase the latency of any calls to the API, as it will have to communicate via your server, and might increase the costs of running your service due to increased data throughput.
You then have to decide how best to communicate with your servers to ensure they are protected. This is important to prevent all of the same problems coming up again with your internal API. The best rule of thumb I can give is to not transmit any secret directly because of the man-in-the-middle threat. Instead you can sign the traffic using your secret and verify the integrity of any requests that come to your server. One standard way of doing this is to compute an HMAC of the message keyed on a secret. I work at a company that has a security product that also operates in this field which is why this sort of stuff interests me. In fact, here is a blog article from one of my colleagues that goes over most of this.
How much should I do?
With any security advice like this you need to make a cost/benefit decision about how hard you want to make it for someone to break in. If you are a bank protecting millions of customers your budget is totally different to someone supporting an app in their spare time. It is virtually impossible to prevent someone from breaking your security, but in practice few people need all of the bells and whistles and with some basic precautions you can get a long way.
I'm surprised anyone hasn't said this yet.
Since the asker came from a Java background (and so did I), here's an analogy that helps.
Classes are simply like Java classes.
Modules are like Java static classes. Think about Math
class in Java. You don't instantiate it, and you reuse the methods in the static class (eg. Math.random()
).
Your test cases where you cannot connect with "ServerName\Instance" but ARE able to connect to the server via "ServerName,Port" is what happens when you VPN into a network with Microsoft VPN. (I had this issue). For my VPN Issue I simply use the static port numbers to get around it.
This is appearently due to VPN not forwarding UDP Packets, allowing only TCP Connections.
In your case your firewall or security settings or antivirus or whatever may be blocking UDP.
I would suggest you check your firewall setting to specifically allow for UDP.
On startup, SQL Server Browser starts and claims UDP port 1434. SQL Server Browser reads the registry, identifies all SQL Server instances on the computer, and notes the ports and named pipes that they use. When a server has two or more network cards, SQL Server Browser will return all ports enabled for SQL Server. SQL Server 2005 and SQL Server Browser support ipv6 and ipv4.
When SQL Server 2000 and SQL Server 2005 clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance.
Using a Firewall
To communicate with the SQL Server Browser service on a server behind a firewall, open UDP port 1434 in addition to the TCP port used by SQL Server (for example, 1433).
OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.
There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.
@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.
That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.
The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.
Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:
It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)
It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)
The result using initialized data:
The result using uninitialized data (this is what Mysticial tested):
And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:
Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.
UPDATE: for rxjs > v5.5
As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json()
method anymore.
import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
export interface Order {
// Properties
}
interface ResponseOrders {
results: Order[];
}
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get<ResponseOrders >(this.baseUrl,{
params
}).pipe(
map(res => res.results || []),
catchError(error => _throwError(error.message || error))
);
}
Notice that you could easily transform the returned Observable
to a Promise
by simply invoking toPromise()
.
ORIGINAL ANSWER:
In your case, you can
Assumming that your backend returns something like:
{results: [{},{}]}
in JSON format, where every {} is a serialized object, you would need the following:
// Somewhere in your src folder
export interface Order {
// Properties
}
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Order } from 'somewhere_in_src';
@Injectable()
export class FooService {
ctor(private http: HttpClient){}
fetch(startIndex: number, limit: number): Observable<Order[]> {
let params = new HttpParams();
params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
// base URL should not have ? in it at the en
return this.http.get(this.baseUrl,{
params
})
.map(res => res.results as Order[] || []);
// in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
}
}
I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:
https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90
And to consume you just need to call it like:
// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]
This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.
As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.
Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
You're looking for a query such as:
DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)
INSERT INTO @table1
(
test
)
SELECT 1
UNION ALL SELECT 2
INSERT INTO @table2
(
test
)
SELECT 1
UNION ALL SELECT 3
-- Here's the important part
SELECT a.*
FROM @table1 a
LEFT join @table2 b on a.test = b.test -- this will return all rows from a
WHERE b.test IS null -- this then excludes that which exist in both a and b
-- Returned results:
2
You can use a very nice tool called Stetho
by adding this to build.gradle
file:
compile 'com.facebook.stetho:stetho:1.4.1'
And initialized it inside your Application
or Activity
onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
}
Then you can view the db records in chrome in the address:
chrome://inspect/#devices
For more details you can read my post: How to view easily your db records
Actually your command line arguments are practically like an array already. At least, you can treat the $@
variable much like an array. That said, you can convert it into an actual array like this:
myArray=( "$@" )
If you just want to type some arguments and feed them into the $@
value, use set
:
$ set -- apple banana "kiwi fruit"
$ echo "$#"
3
$ echo "$@"
apple banana kiwi fruit
Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.
It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.
Here’s how you can find the details of your transaction:
Sign in to your Google Payments account at https://payments.google.com.
On the left menu, select the “Subscriptions and services” page.
On the “Other purchase activity” card, click View purchases.
Click the “Google Play” registration transaction to see your payment method.
You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.
To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).
var date=new Date();
//here I am using "-30" to subtract 30 minutes from the current time.
var minute=date.setMinutes(date.getMinutes()-30);
console.log(minute) //it will print the time and date according to the above condition in Unix-timestamp format.
you can convert Unix timestamp into conventional time by using new Date()
.for example
var extract=new Date(minute)
console.log(minute)//this will print the time in the readable format.
Most preferably you might want to use AVFoundation. It provides all the essentials for working with audiovisual media.
Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error {
print(error.localizedDescription)
}
}
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Make sure to change the name of your tune as well as the extension. The file needs to be properly imported (
Project Build Phases
>Copy Bundle Resources
). You might want to place it inassets.xcassets
for greater convenience.
For short sound files you might want to go for non-compressed audio formats such as .wav
since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3
etc. pp. Check the compatible audio formats of CoreAudio
.
Fun-fact: There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound
It might be useful to debug the client, turn off Tools\Options\Debugging\General\'Enable Just My Code', click Debug\Exceptions\'catch all first-chance exceptions' for managed CLR exceptions, and see if there is an exception under-the-hood on the client before the protocol exception and before the message hits the wire. (My guess would be some kind of serialization failure.)
Let arrList
be the ArrayList
and newValue
the new String
, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.
So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.
To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"
Then will generate directly p8 file.
I hope this will solve your issue.
Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/
Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,
$('.button').click(function() {
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$('html[manifest=saveappoffline.appcache]').attr('content', '');
$(this).html(s);
}
});
});
NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.
The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.
Beware: The correct answer is below. This no longer works
Create a file called .ember-cli
in your project, and include in it these contents:
{
"output-path": "./location/to/your/dist/"
}
UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'
How about onblur event :
<input type="text" name="name" value="value" onblur="alert(1);"/>
First of all, Relax.
"Nothing is under our control. Our control is mere illusion.", "To err is human"
I get that you've unintentionally pushed your code to remote-master
. THIS is going to be alright.
1. At first, get the SHA-1
value of the commit you are trying to return, e.g. commit to master branch. run this:
git log
you'll see bunch of 'f650a9e398ad9ca606b25513bd4af9fe...' like strings along with each of the commits. copy that number from the commit that you want to return back.
2. Now, type in below command:
git reset --hard your_that_copied_string_but_without_quote_mark
you should see message like "HEAD is now at ". you are on clear. What it just have done is to reflect that change locally.
3. Now, type in below command:
git push -f
you should see like
"warning: push.default is unset; its implicit value has changed in..... ... Total 0 (delta 0), reused 0 (delta 0) ... ...your_branch_name -> master (forced update)."
Now, you are all clear. Check the master with "git log" again, your fixed_destination_commit should be on top of the list.
You are welcome (in advance ;))
UPDATE:
Now, the changes you had made before all these began, are now gone. If you want to bring those hard-works back again, it's possible. Thanks to git reflog, and git cherry-pick commands.
For that, i would suggest to please follow this blog or this post.
var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { document.write("Your html for IE") }
However -just for the record- this is invalid:
<address class="vcard">
<svg viewBox="0 0 800 400">
<rect width="800" height="400" fill="#000">
</svg>
</address>
And a slash here would make it valid again:
<rect width="800" height="400" fill="#000"/>
You can get the single value for the attribute with below code:
$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);
Open Storage Management
Storage Management
.Select Applications
on left pane.
Xcode
on the right pane and select delete.This will remove XCode from the installed applications list of your Mac's App Store.
Update: This worked for me on macOS Sierra 10.12.1
.
You can't do this with HTML. It's a server-based solution. You have to stream the file so that the browser than triggers the save dialog.
I'd advise not doing this. How a user interacts with a PDF should be left up to the user.
UPDATE (2014):
So...this answer still gets plenty of downvotes. I assume part of that is that this was answered 4 years ago and as Sarim points out, there is now the HTML 5 download
attribute that can handle this.
I agree, and think Sarim's answer is good (it probably should be the chosen answer if the OP ever returns). However, this answer is still the reliable way to handle it (as Yigit Yener's answer points out and--oddly--people agree with). While the download attribute has gained support, it's still spotty:
Base64 overhead is 33%.
BaseXML for XML1.0 overhead is only 20%. But it's not a standard and only have a C implementation yet. Check it out if you're concerned with data size. Note that however browsers tends to implement compression so that it is less needed.
I developed it after the discussion in this thread: Encoding binary data within XML : alternatives to base64.
I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:
\includegraphics[height=60mm, width=100mm]{number2.png}
works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.
Incidentally, you can change this in TexShop from the "Typeset" menu.
Hope this helps.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
printf("%9.6f", myFloat)
specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.
The below snippet examines EAX using GDB.
(gdb) info register eax
eax 0xaa55 43605
(gdb) info register ax
ax 0xaa55 -21931
(gdb) info register ah
ah 0xaa -86
(gdb) info register al
al 0x55 85
There are different types of users behind the Internet, so we want to catch the IP address from different portions. Those are:
1. $_SERVER['REMOTE_ADDR']
-
This contains the real IP address of the client. That is the most reliable value you can find from the user.
2. $_SERVER['REMOTE_HOST']
-
This will fetch the host name from which the user is viewing the current page. But for this script to work, hostname lookups on inside httpd.conf must be configured.
3. $_SERVER['HTTP_CLIENT_IP']
-
This will fetch the IP address when the user is from shared Internet services.
4. $_SERVER['HTTP_X_FORWARDED_FOR']
- This will fetch the IP address from the user when he/she is behind the proxy.
So we can use this following combined function to get the real IP address from users who are viewing in diffrent positions,
// Function to get the user IP address
function getUserIP() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.
public class MyClass<T>
{
etc
This is worked for me
I used Entity framework in my application and had this problem,I seted any permission in folders and windows services and not work, after that I start my application as administrator (right click in exe file and select "run as admin") and that works fine.
>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…
you can try just add
network_mode: "host"
example :
version: '2'
services:
feedx:
build: web
ports:
- "127.0.0.1:8000:8000"
network_mode: "host"
list option available
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.
If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.
If they are not present, make blindly builds everything under the rule.
Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!
I find converting to the binary representation easier to grasp this problem.
float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;
System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));
You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.
111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000
That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:
public class GenericList <T> extends ArrayList<T>
{
private Class<T> genericType;
public GenericList(Class<T> c)
{
this.genericType = c;
}
public Class<T> getGenericType()
{
return genericType;
}
}
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
I was having the same issue with ghost and heroku.
heroku config:set NODE_ENV=production
solved it!
Check your config and env that the server is running on.
Warning: Use the below steps at your own risk. You may receive different results as indicated in the comments. Please exercise caution and have a full backup prior to doing this.
Below is a list of steps used to solve the issue:
Remove Docker (this won't delete images, containers, volumes, or customized configuration files):
sudo apt-get purge docker-engine
Remove the Docker apt key:
sudo apt-key del 58118E89F3A912897C070ADBF76221572C52609D
Delete the docker.list file:
sudo rm /etc/apt/sources.list.d/docker.list
Manually delete apt cache files:
sudo rm /var/lib/apt/lists/apt.dockerproject.org_repo_dists_ubuntu-xenial_*
Delete apt-transport-https and ca-certificates:
sudo apt-get purge apt-transport-https ca-certificates
Clean apt and perform autoremove:
sudo apt-get clean && sudo apt-get autoremove
Reboot Ubuntu:
sudo reboot
Run apt-get update:
sudo apt-get update
Install apt-transport-https and ca-certificates again:
sudo apt-get install apt-transport-https ca-certificates
Add the apt key:
> sudo apt-key adv \
--keyserver hkp://ha.pool.sks-keyservers.net:80 \
--recv-keys 58118E89F3A912897C070ADBF76221572C52609D
> echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" |
sudo tee /etc/apt/sources.list.d/docker.list
> sudo apt-get update
> sudo apt-get install docker-engine
Granted, there are plenty of variables and your results may vary. However, these steps cover as many areas as possible to ensure potential problem spots are scrubbed so that the likelihood of success is higher.
Update 7/6/2017
It appears newer versions of Docker are using a different installation process which should eliminate many of these problems. Be sure to check out https://docs.docker.com/engine/installation/linux/ubuntu/.
Syntax:
CASE value WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
mysql> SELECT CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END;
+-------------------------------------------------------------+
| CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false |
+-------------------------------------------------------------+
I am use:
SELECT act.*,
CASE
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND lises.session_date >= now()
LEFT JOIN session AS ses ON ses.activity_id = act.id AND ses.session_date >= now()
WHERE act.id
Set the insetForSectionAt
property of the UICollectionViewFlowLayout
object attached to your UICollectionView
Make sure to add this protocol
UICollectionViewDelegateFlowLayout
Swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
}
Objective - C
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(top, left, bottom, right);
}
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
def remove_chars(line):
line7=line[7].translate(None,'abcd')
return line[:7]+[line7]+line[8:]
line= ['ad','da','sdf','asd',
'3424','342sfas','asdfaf','sdfa',
'afase']
print line[7]
line = remove_chars(line)
print line[7]
From later versions, there is no need to manually install gulp-util.
Check the new getting started page.
If you still hit this problem try reinstalling your project's local packages:
rm -rf node_modules/
npm install
npm install gulp-util --save-dev
Install gulp and gulp-util in your project devDependencies
An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:
SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)
LEN becomes LENGTH and ISNULL becomes IFNULL.
It worked with ASP.NET only after adding the pragma:no-cache
header in IIS. Cache-Control: no-cache
was not enough.
This is what you want:
>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))
I will go there
I will go now
great
The following is not really close to what you get from C++'s dynamic_cast
in terms of type checking but maybe it will help you understand its purpose a little bit better:
struct Animal // Would be a base class in C++
{
enum Type { Dog, Cat };
Type type;
};
Animal * make_dog()
{
Animal * dog = new Animal;
dog->type = Animal::Dog;
return dog;
}
Animal * make_cat()
{
Animal * cat = new Animal;
cat->type = Animal::Cat;
return cat;
}
Animal * dyn_cast(AnimalType type, Animal * animal)
{
if(animal->type == type)
return animal;
return 0;
}
void bark(Animal * dog)
{
assert(dog->type == Animal::Dog);
// make "dog" bark
}
int main()
{
Animal * animal;
if(rand() % 2)
animal = make_dog();
else
animal = make_cat();
// At this point we have no idea what kind of animal we have
// so we use dyn_cast to see if it's a dog
if(dyn_cast(Animal::Dog, animal))
{
bark(animal); // we are sure the call is safe
}
delete animal;
}
Yes you can check below is the code:
public boolean isGPSEnabled(Context mContext)
{
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
with the permission in the manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The view itself, has it's own life cycle which is basically as follows:
Attached
Measured
Layout
Draw
So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout, and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
you can populate the data you want with a simple callback function,
let's say we have a list named lst
that we want to populate,
we have a function that pupulates pupulates list,
const lst = [];
const populateData = (data) => {lst.push(data)}
now we can pass the callback function to the function which is making the axios call and we can pupulate the list when we get data from response.
now we make our function that makes the request and pass populateData
as a callback function.
function axiosTest (populateData) {
axios.get(url)
.then(function(response){
populateData(response.data);
})
.catch(function(error){
console.log(error);
});
}
for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM
<script language="javascript"> <!--
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
alert("MOBILE DEVICE DETECTED");
document.write("<b>------------------------------------------<br>")
document.write("<b>" + navigator.userAgent + "<br>")
document.write("<b>------------------------------------------<br>")
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
document.write("<b> ANDROID MOBILE <br>")
else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
document.write("<b> ANDROID TABLET <br>")
else if ((userAgent.search("blackberry") > -1))
document.write("<b> BLACKBERRY DEVICE <br>")
else if ((userAgent.search("iphone") > -1))
document.write("<b> IPHONE DEVICE <br>")
else if ((userAgent.search("ipod") > -1))
document.write("<b> IPOD DEVICE <br>")
else if ((userAgent.search("ipad") > -1))
document.write("<b> IPAD DEVICE <br>")
else
document.write("<b> UNKNOWN DEVICE <br>")
}
else
alert("NO MOBILE DEVICE DETECTED"); //--> </script>
I'm not sure that you're creating a set with this ([1, 2])
syntax, rather a list. To create a set, you should use set([1, 2])
.
These brackets are just envelopping your expression, as if you would have written:
if (condition1
and condition2 == 3):
print something
There're not really ignored, but do nothing to your expression.
Note: (something, something_else)
will create a tuple (but still no list).
Thread
When you start an app, a process is created to execute the code. To efficiently use computing resource, threads can be started within the process so that multiple tasks can be executed at the time. So threads allow you to build efficient apps by utilizing cpu efficiently without idle time.
In Android, all components execute on a single called main thread. Android system queue tasks and execute them one by one on the main thread. When long running tasks are executed, app become unresponsive.
To prevent this, you can create worker threads and run background or long running tasks.
Handler
Since android uses single thread model, UI components are created non-thread safe meaning only the thread it created should access them that means UI component should be updated on main thread only. As UI component run on the main thread, tasks which run on worker threads can not modify UI components. This is where Handler comes into picture. Handler with the help of Looper can connect to new thread or existing thread and run code it contains on the connected thread.
Handler makes it possible for inter thread communication. Using Handler, background thread can send results to it and the handler which is connected to main thread can update the UI components on the main thread.
AsyncTask
AsyncTask provided by android uses both thread and handler to make running simple tasks in the background and updating results from background thread to main thread easy.
Please see android thread, handler, asynctask and thread pools for examples.
I wrote up some code that will sort a table by a row, assuming only one <tbody>
and cells don't have a colspan.
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
// sortTable(tableNode, columId, false);
If you don't want to make the assumptions above, you'd need to consider how you want to behave in each circumstance. (e.g. put everything into one <tbody>
or add up all the preceeding colspan values, etc.)
You could then attach this to each of your tables, e.g. assuming titles are in <thead>
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
and then invoking makeAllSortable
onload.
Example fiddle of it working on a table.
Example in Swift 3, with a previous and a next button in the top right.
let prevButtonItem = UIBarButtonItem(title: "\u{25C0}", style: .plain, target: self, action: #selector(prevButtonTapped))
let nextButtonItem = UIBarButtonItem(title: "\u{25B6}", style: .plain, target: self, action: #selector(nextButtonTapped))
self.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]
Here is settings.xml
--> C:\maven\conf\settings.xml
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
Just adding on to carlpett's answer. For a much useful view of the files, you could pipe the output to ls.
find . -maxdepth 1 -type f|ls -lt|less
Shows the most recently modified files in a list format, quite useful when you have downloaded a lot of files, and want to see a non-cluttered version of the recent ones.
It happens more often than not, I am on a slow internet connection and I have to clone a decently-huge git repository. The most common issue is that the connection closes and the whole clone is cancelled.
Cloning into 'large-repository'...
remote: Counting objects: 20248, done.
remote: Compressing objects: 100% (10204/10204), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
After a lot of trial and errors and a lot of “remote end hung up unexpectedly” I have a way that works for me. The idea is to do a shallow clone first and then update the repository with its history.
$ git clone http://github.com/large-repository --depth 1
$ cd large-repository
$ git fetch --unshallow
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
Try white-space: nowrap;
Documentation: https://developer.mozilla.org/docs/Web/CSS/white-space
Note:
Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.
While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.
names=[line.strip() for line in open('names.txt')]
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute
Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.
FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!
You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:
Please check the example: http://jsfiddle.net/xLA4q/
HTML:
<div class="nav-content-wrapper">
<div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
<div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>
CSS:
.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}
I know this is old but you could create a custom extension if you needed to create that form over and over:
public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post,
new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}
Usage then just becomes
<% using(Html.BeginMultipartForm()) { %>
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
This worked for me while the other solutions were not!
This is stopping to need to be connected to your EC2 instance all the time. Therefore even if you loose connection due to internet connection loss, whenever you gain a new wifi access it automatically re-connects to the actively working kernel.
Also, don't forget to start your jupyter in a tmux account or a ngnix or other environments like that.
Hope this helps!
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
json.dump() will preserve the ordder of your dictionary. Open the file in a text editor and you will see. It will preserve the order regardless of whether you send it an OrderedDict.
But json.load() will lose the order of the saved object unless you tell it to load into an OrderedDict(), which is done with the object_pairs_hook parameter as J.F.Sebastian instructed above.
It would otherwise lose the order because under usual operation, it loads the saved dictionary object into a regular dict and a regular dict does not preserve the oder of the items it is given.
I found that starting the emulator with 'wipe user data' checked cleared this problem up for me after I rebuilt my dev machine from Vista x64 to Win7 x64.
sudo cp hello.php /var/www/
What output do you get?
Your query is very close. You should be able to use the following which includes the subject
in the final select list:
select u.name, u.subject, u.marks
from student s
unpivot
(
marks
for subject in (Maths, Science, English)
) u;
Up above, you mention having compiling your as part of your steps to reproduce, but then below you made an edit saying,
"is there a way to see on which distro a shared library was compiled on?"
Whether or not you compiled this on the same distro, and even a different version of the same distro is an important detail, especially for c++ applications.
Linking to c++ libraries, including libstdc++ can have mixed results, as far as I can tell. Here is a related question about recompiling with different versions of c++.
do we need to recompile libraries with c++11?
Basically, if you compiled against c++ on a different distro (and possibly different gcc version), this may be causing your trouble.
I think you have two options:
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
PS: For the record, it was actually the original question. It was already edited :)
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);
You print Float here
, that has no format at all.
To print formatted float, just use
String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);
There are several solutions:
psql
commandpsql -d dbname -t -A -F"," -c "select * from users" > output.csv
This has the big advantage that you can using it via SSH, like ssh postgres@host command
- enabling you to get
copy
commandCOPY (SELECT * from users) To '/tmp/output.csv' With CSV;
>psql dbname
psql>\f ','
psql>\a
psql>\o '/tmp/output.csv'
psql>SELECT * from users;
psql>\q
All of them can be used in scripts, but I prefer #1.
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
Using Streams :
If let say result is list of integers (List<Integer> result
) then :
List<String> ids = (List<String>) result.stream().map(intNumber -> Integer.toString(intNumber)).collect(Collectors.toList());
One of the ways to solve it. Hope this helps.
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Table rows cannot have margin values. Can you increase the padding? That would work. Otherwise you could insert a <tr class="spacer"></tr>
before and after the class="highlighted"
rows.
Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.
<div class="container-fluid w-100 h-auto m-0 p-0">
<img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">
</div>
There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.
QA1942 - iOS Wi-Fi Management APIs
This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.
These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.
These APIs come close to what you want, but they're Apple-to-Apple only.
Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.
in java you can replace with
getChildFragmentManager()
in kotlin, make it simple by
childFragmentManager
hope it help :)
Set the buildToolsVersion '26.0.2'
then change classpath 'com.android.tools.build:gradle:3.0.1'
.
Make sure you set compileSdkVersion
to 26
whiles targetSdkVersion
is also set 26
.
It is also appropriate to sent set compile 'com.android.support:appcompat-v7:26.0.2'
.
There are two obvious points, as well as the points in the other answer:
They are exactly equivalent when using sub queries:
SELECT * FROM table
WHERE column IN(subquery);
SELECT * FROM table
WHERE column = ANY(subquery);
On the other hand:
Only the IN
operator allows a simple list:
SELECT * FROM table
WHERE column IN(… , … , …);
Presuming they are exactly the same has caught me out several times when forgetting that ANY
doesn’t work with lists.
You can use subList(int fromIndex, int toIndex)
method on your integers arr, something like this:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
List<Integer> partialArr = arr.subList(1, 3);
// print the subArr
for (Integer i: partialArr)
System.out.println(i + " ");
}
}
Output will be: 2 3
.
Note that subList(int fromIndex, int toIndex)
method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.
Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third
Assuming both arrays are of the same length
Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant
arr1() = Array("A", 1, "B", 2)
arr2() = Array("C", 3, "D", 4)
ReDim arr3(UBound(arr1) + UBound(arr2) + 1)
Dim i As Integer
For i = 0 To UBound(arr1)
arr3(i * 2) = arr1(i)
arr3(i * 2 + 1) = arr2(i)
Next i
Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.
You can use model.predict()
to predict the class of a single image as follows [doc]:
# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os
def load_image(img_path, show=False):
img = image.load_img(img_path, target_size=(150, 150))
img_tensor = image.img_to_array(img) # (height, width, channels)
img_tensor = np.expand_dims(img_tensor, axis=0) # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
img_tensor /= 255. # imshow expects values in the range [0, 1]
if show:
plt.imshow(img_tensor[0])
plt.axis('off')
plt.show()
return img_tensor
if __name__ == "__main__":
# load model
model = load_model("model_aug.h5")
# image path
img_path = '/media/data/dogscats/test1/3867.jpg' # dog
#img_path = '/media/data/dogscats/test1/19.jpg' # cat
# load a single image
new_image = load_image(img_path)
# check prediction
pred = model.predict(new_image)
In this example, a image is loaded as a numpy
array with shape (1, height, width, channels)
. Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).
Check this:
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
x.Text = "";
}
}
A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it
In Virtual Box "Settings" > System Settings > Processor > Enable the PAE/NX option. It resolved my issue.
You can try to use CDATA to put all your symbols that don't work.
An example of something that will work in XML:
<![CDATA[
function matchwo(a,b) {
if (a < b && a < 0) {
return 1;
} else {
return 0;
}
}
]]>
And of course you can use <
and >
.
Another possible solution if you own the website is to use inline installation.
if (chrome.app.isInstalled) {
// extension is installed.
}
I know this an old question but this way was introduced in Chrome 15 and so I thought Id list it for anyone only now looking for an answer.
if you build the source files with lower version of Java (example Java1.5) and trying to run that program/application with higher version of Java (example java 1.6) you will get this problem. for better explanation see this link. click here
You can use jspdf to capture a canvas into an image or pdf like this:
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
More info: https://github.com/MrRio/jsPDF
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
I have a little extension to the solutions.
Using a recursive generic declaration and a deriving subclass you can better concentrate on your actual target.
Notice, it's different from a non generic implementation, you don`t need to cast 'node' in 'NodeWorker'.
Here's my example:
public class GenericTree<T> where T : GenericTree<T> // recursive constraint
{
// no specific data declaration
protected List<T> children;
public GenericTree()
{
this.children = new List<T>();
}
public virtual void AddChild(T newChild)
{
this.children.Add(newChild);
}
public void Traverse(Action<int, T> visitor)
{
this.traverse(0, visitor);
}
protected virtual void traverse(int depth, Action<int, T> visitor)
{
visitor(depth, (T)this);
foreach (T child in this.children)
child.traverse(depth + 1, visitor);
}
}
public class GenericTreeNext : GenericTree<GenericTreeNext> // concrete derivation
{
public string Name {get; set;} // user-data example
public GenericTreeNext(string name)
{
this.Name = name;
}
}
static void Main(string[] args)
{
GenericTreeNext tree = new GenericTreeNext("Main-Harry");
tree.AddChild(new GenericTreeNext("Main-Sub-Willy"));
GenericTreeNext inter = new GenericTreeNext("Main-Inter-Willy");
inter.AddChild(new GenericTreeNext("Inter-Sub-Tom"));
inter.AddChild(new GenericTreeNext("Inter-Sub-Magda"));
tree.AddChild(inter);
tree.AddChild(new GenericTreeNext("Main-Sub-Chantal"));
tree.Traverse(NodeWorker);
}
static void NodeWorker(int depth, GenericTreeNext node)
{ // a little one-line string-concatenation (n-times)
Console.WriteLine("{0}{1}: {2}", String.Join(" ", new string[depth + 1]), depth, node.Name);
}
I don't try changing sequence via setval
. But using ALTER
I was issued how to write sequence name properly. And this only work for me:
Check required sequence name using SELECT * FROM information_schema.sequences;
ALTER SEQUENCE public."table_name_Id_seq" restart {number};
In my case it was ALTER SEQUENCE public."Services_Id_seq" restart 8;
Also there is a page on wiki.postgresql.org where describes a way to generate sql script to fix sequences in all database tables at once. Below the text from link:
Save this to a file, say 'reset.sql'
SELECT 'SELECT SETVAL(' || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';' FROM pg_class AS S, pg_depend AS D, pg_class AS T, pg_attribute AS C, pg_tables AS PGT WHERE S.relkind = 'S' AND S.oid = D.objid AND D.refobjid = T.oid AND D.refobjid = C.attrelid AND D.refobjsubid = C.attnum AND T.relname = PGT.tablename ORDER BY S.relname;
Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:
psql -Atq -f reset.sql -o temp psql -f temp rm temp
And the output will be a set of sql commands which look exactly like this:
SELECT SETVAL('public."SocialMentionEvents_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."SocialMentionEvents";
SELECT SETVAL('public."Users_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."Users";
You can call the functions from inside another function
<input id ="btn" type="button" value="click" onclick="todo()"/>
function todo(){
pay(); cls();
}
PHP does not yet support multiple class inheritance, it does however support multiple interface inheritance.
See http://www.hudzilla.org/php/6_17_0.php for some examples.
The answers provided are not the solution. The .NET 6# stuff is pretty different from what we used to. A lot has changed, from having to deal with portable libraries to Visual Studio 2015 installing an old compiler (it cost me four hours cracking my head).
The long story short: Stack Overflow question How do I use C# 6 with a Web Site project type?
You need to install the C# .NET compiler (now runs as a service bla bla bla). and you need to run updates on NuGet to get the latest everything (before trying anything else).
The compiler must be installed on the project your solution runs from (so your website or your main project your application starts from (if you have multiple projects)).
Once you install that then sort out your web.config referencing any portable libraries, and delete both the bin
and obj
folder (to avoid works on my computer nightmare), It should just run. But be patient; what happens on your machine may vary as much as the answers above. Most of the answers above hide other problems. It may work for a while, then boom: compiler error. I had a few pages working, then some pages started failing because of some packages that have started using portable libraries.
Here is a slightly different approach to read-only properties, which perhaps should be called write-once properties since they do have to get initialized, don't they? For the paranoid among us who worry about being able to modify properties by accessing the object's dictionary directly, I've introduced "extreme" name mangling:
from uuid import uuid4
class ReadOnlyProperty:
def __init__(self, name):
self.name = name
self.dict_name = uuid4().hex
self.initialized = False
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.dict_name]
def __set__(self, instance, value):
if self.initialized:
raise AttributeError("Attempt to modify read-only property '%s'." % self.name)
instance.__dict__[self.dict_name] = value
self.initialized = True
class Point:
x = ReadOnlyProperty('x')
y = ReadOnlyProperty('y')
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
try:
p = Point(2, 3)
print(p.x, p.y)
p.x = 9
except Exception as e:
print(e)
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:
$_SERVER['DOCUMENT_ROOT']
The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
There is an additional architecture that wasn't mentioned - SQL-based database services that enable horizontal scaling without the complexity of manual sharding. These services do the sharding in the background, so they enable you to run a traditional SQL database and scale out like you would with NoSQL engines like MongoDB or CouchDB. Two services I am familiar with are EnterpriseDB for PostgreSQL and Xeround for MySQL. I saw an in-depth post by Xeround which explains why scale-out on SQL databases is difficult and how they do it differently - treat this with a grain of salt as it is a vendor post. Also check out Wikipedia's Cloud Database entry, there is a nice explanation of SQL vs. NoSQL and service vs. self-hosted, a list of vendors and scaling options for each combination. ;)
The JavaScript style names are WebkitTransformOrigin
and WebkitTransform
element.style.webkitTransform = "rotate(-2deg)";
Check the DOM extension reference for WebKit here.
// original_x000D_
var arr = [{_x000D_
key: '11',_x000D_
value: '1100',_x000D_
$$hashKey: '00X'_x000D_
},_x000D_
{_x000D_
key: '22',_x000D_
value: '2200',_x000D_
$$hashKey: '018'_x000D_
}_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"
There are great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here
rmdir "$LINK_OR_DIR"
fi
fi
will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.
I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:
dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d
This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to standard output (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.
I had this issue where on a screen orientation change, the activity finished before the AsyncTask with the progress dialog completed. I seemed to resolve this by setting the dialog to null onPause()
and then checking this in the AsyncTask before dismissing.
@Override
public void onPause() {
super.onPause();
if ((mDialog != null) && mDialog.isShowing())
mDialog.dismiss();
mDialog = null;
}
... in my AsyncTask:
protected void onPreExecute() {
mDialog = ProgressDialog.show(mContext, "", "Saving changes...",
true);
}
protected void onPostExecute(Object result) {
if ((mDialog != null) && mDialog.isShowing()) {
mDialog.dismiss();
}
}
java provides support for Unicode i.e it supports all world wide alphabets. Hence the size of char in java is 2 bytes. And range is 0 to 65535.
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
if(x==15)
break;
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
other alternative is using math operation by dividing it, for example:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
But, as you can see this can only be used when the range is fixed in each case.
You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:
$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();
It works with the hide before the click()
but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.
UPDATE OCTOBER 2017 I never knew this feature existed in Sublime Text, but the interface appears to have changed slightly from the previous answer - at least on OS X. Here are the detailed steps I followed:
This opens a new tab showing the comparison. The first file in red, the second in green.
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
To plot multiple categorical features as bar charts on the same plot, I would suggest:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
"direction": ["up", "up", "down", "left", "right", "down", "down"],
}
)
categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()
TryGetValue
will already assign the default value for the type to the dictionary, so you can just use:
dictionary.TryGetValue(key, out value);
and just ignore the return value. However, that really will just return default(TValue)
, not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> defaultValueProvider)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value
: defaultValueProvider();
}
(You may want to put argument checking in, of course :)
I'm a rebel.
Solution: don't use jQuery. jQuery is a library to abstract the DOM inconcistencies across the browsers. Since you're in your own console, you don't need this kind of abstraction.
For your example:
$$('element').length
($$
is an alias to document.querySelectorAll
in the console.)
For any other example: I'm sure I can find anything. Especially if you're using a modern browser (Chrome, FF, Safari, Opera).
Besides, knowing how the DOM works wouldn't hurt anyone, it would only increase your level of jQuery (yes, learning more about javascript makes you better at jQuery).
This worked for me (though it's for reactjs & tachyons used as inline CSS)
<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}>
........
</div>
This takes in css as height: 100vh
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
I was able to do this on .net c# with PhantomJSDriver with selenium web driver 3.1
[TestMethod]
public void headless()
{
var driverService = PhantomJSDriverService.CreateDefaultService(@"C:\Driver\phantomjs\");
driverService.SuppressInitialDiagnosticInformation = true;
driverService.AddArgument("--web-security=no");
driverService.AddArgument("--ignore-ssl-errors=yes");
driver = new PhantomJSDriver(driverService);
driver.Navigate().GoToUrl("XXXXXX.aspx");
Thread.Sleep(6000);
}
I think you are looking for instance_of?
. is_a?
and kind_of?
will return true for instances from derived classes.
class X < String
end
foo = X.new
foo.is_a? String # true
foo.kind_of? String # true
foo.instance_of? String # false
foo.instance_of? X # true
In your index.php
file add the line:
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
Another way to detect the bitness of Office is to find out the typelib.
For example, to detect Outlook's bitness, write a .JS file as following:
function detectVersion()
var outlooktlib = "TypeLib\\{00062FFF-0000-0000-C000-000000000046}";
var HKCR = 0x80000000;
var loc = new ActiveXObject("WbemScripting.SWbemLocator");
var svc = loc.ConnectServer(null,"root\\default");
var reg = svc.Get("StdRegProv");
var method = reg.Methods_.Item("EnumKey");
var inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib;
var outparam = reg.ExecMethod_(method.Name,inparam);
tlibver = outparam.sNames.toArray()[0];
method = reg.Methods_.Item("GetStringValue");
inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win32";
inparam.sValueName = "";
outparam = reg.ExecMethod_(method.Name,inparam);
if(outparam.sValue) return "32 bit";
method = reg.Methods_.Item("GetStringValue");
inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win64";
inparam.sValueName = "";
outparam = reg.ExecMethod_(method.Name,inparam);
if(outparam.sValue) return "64 bit";
return "Not installed or unrecognizable";
}
You could find out other Office component's typelib id, and replace the first line of the function for it. Here is a brief list of interesting IDs:
{4AFFC9A0-5F99-101B-AF4E-00AA003F0F07} - Access
{00020905-0000-0000-C000-000000000046} - Word
{00020813-0000-0000-C000-000000000046} - Excel
{91493440-5A91-11CF-8700-00AA0060263B} - Powerpoint
{0002123C-0000-0000-C000-000000000046} - Publisher
{0EA692EE-BB50-4E3C-AEF0-356D91732725} - OneNote 2010+
{F2A7EE29-8BF6-4A6D-83F1-098E366C709C} - OneNote 2007
All above lib id were found through the Windows SDK tool OLE-COM Object Viewer
, you could find out more lib id's by using it.
The benefit of this approach is that it works for all versions of office, and provides control on every single component in you interest. Furthermore, those keys are in the HKEY_CLASSES_ROOT and deeply integrated into the system, so it is highly unlikely they were not accessible even in a sandbox environment.
This doesn't answer how to add them to your POM, and may be a no brainer, but would just adding the lib dir to your classpath work? I know that is what I do when I need an external jar that I don't want to add to my Maven repos.
Hope this helps.
The simplest possible solution I found was:
In your markup:
<a [href]="location.path()">Reload</a>
and in your component typescript file:
constructor(
private location: Location
) { }
The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:
<propertyfile file="build.properties">
<entry key="build_number"
type="int"
operation="+"
value="1"/>
</propertyfile>
I've incremented my build_number
by one. I have no idea what the value was, but it's now one greater than what it was before.
<echo>
task to build a property file instead of <propertyfile>
. You can easily layout the content and then use <propertyfile>
to edit that content later on.Example:
<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
Example:
<propertyfile file="default.properties"
comment="Default Configuration">
<entry key="source.dir" value="1"/>
<entry key="dir.publish" value="1"/>
<propertyfile>
<propertyfile file="source.properties"
comment="Source Configuration">
<entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</concat>
<delete>
<fileset dir="${basedir}">
<include name="default.properties"/>
<include name="source.properties"/>
</fileset>
</delete>
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
in my case the right server name was the name of my computer. for example John-PC, or somth
Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.
If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".
$('body').on("click", ".dropdown-menu", function (e) {
$(this).parent().is(".open") && e.stopPropagation();
});
This may work for any conditions.
try this:
$('.nav a').on('click', function(){
$('.btn-navbar').click(); //bootstrap 2.x
$('.navbar-toggle').click(); //bootstrap 3.x by Richard
$('.navbar-toggler').click(); //bootstrap 4.x
});
The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":
A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.
Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.
I can be forgiven for being against converting a java program to a .exe Application and I have My reasons. the Major one being that a java program can be compiled to a jar file from A lot of IDE's. When the program is in .jar format, it can run in Multiple Platforms as opposed to .exe which would run Only in very limited Environment. I am for the Idea that Java Programs shoudl not be converted to Exe unless it is very neccesary. One can always write .bat files that runs the Java program while it is a jar file.
if it is really neccesary to convert it to exe, Jar2Exe converter silently does that and one can also attach Libraries that are compiled together with the Main Application.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
In Python:
# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M)
or more rigorous:
# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()
You can simply write:
char c = (char) 2;
or
char c = Convert.ToChar(2);
or more complex option for ASCII encoding only
char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];
The javax.naming
package comprises the JNDI API. Since it's just an API, rather than an implementation, you need to tell it which implementation of JNDI to use. The implementations are typically specific to the server you're trying to talk to.
To specify an implementation, you pass in a Properties
object when you construct the InitialContext
. These properties specify the implementation to use, as well as the location of the server. The default InitialContext
constructor is only useful when there are system properties present, but the properties are the same as if you passed them in manually.
As to which properties you need to set, that depends on your server. You need to hunt those settings down and plug them in.
I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:
find . -type d -exec chmod 755 {} \+
but this also does the same thing:
chmod 755 `find . -type d`
and so does this:
chmod 755 $(find . -type d)
The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.
So I think in your case that the following will do what you want.
chmod 777 $(find "/Users/Test/Desktop/PATH")
In a bash-like environment you can use:
keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo
This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep
.
In Python 2.x, make sure to have at least one operand of your division in float
. Multiple ways you may achieve this as the following examples:
20. / 15
20 / float(15)
'start /w' does NOT work in all cases. The original solution works great. However, on some machines, it is wise to put a delay immediately after starting the executable. Otherwise, the task name may not appear in the task list yet, and the loop will not work as expected (someone pointed that out). The 2 delays can be combined and put at the top of the loop. Can also get rid of the 'else' just to shorten. Example of 2 programs running sequentially:
c:\prog1.exe
:loop1
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog1.exe" >nul 2>&1
if errorlevel 1 goto cont1
goto loop1
:cont1
c:\prog2.exe
:loop2
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog2.exe" >nul 2>&1
if errorlevel 1 goto cont2
goto loop2
:cont2
john refling
return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".
Encrypt something with the public key, and see which private key decrypts it.
This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.
step 1: run this script
SET FOREIGN_KEY_CHECKS=0;
step 2: add column
ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
step 3: add foreign key to the added column
ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
step 4: run this script
SET FOREIGN_KEY_CHECKS=1;
You can view any messages logged to the console if you use a tool such as Firebug to inspect your code. Let's say you do this:
console.log('Testing console');
When you access the console in Firebug (or whichever tool you decide to use to inspect your code), you will see whatever message you told the function to log. This is particularly useful when you want to see if a function is executing, or if a variable is being passed/assigned properly. It's actually rather valuable for figuring out just what went wrong with your code.
In my case, I was linking to a third-party library that was a bit old (developed for iOS 6, on XCode 5 / iOS 7). Therefore, I had to update the third-party library, do a Clean and Build, and it now builds successfully.
From docs.microsoft.com:
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
The type or member can only be accessed by code in the same class or struct.
The type or member can only be accessed by code in the same class or struct, or in a derived class.
private protected
(added in C# 7.2)The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly.
The type or member can be accessed by any code in the same assembly, but not from another assembly.
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
When no access modifier is set, a default access modifier is used. So there is always some form of access modifier even if it's not set.
static
modifierThe static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:
static class Foo()
{
static Foo()
{
Bar = "fubar";
}
public static string Bar { get; set; }
}
Static classes are often used as services, you can use them like so:
MyStaticClass.ServiceMethod(...);
I am facing the same issue on Xcode 7.3 and my device version is iOS 10
.
This error is shown when your Xcode
is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.
We can solve this issue by following the below steps:-
- Open Finder select Applications
- Right click on Xcode 8, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
- Copy the 10.0 folder (or above for later version).
- Back in Finder select Applications again
- Right click on Xcode 7.3, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
- Paste the 10.0 folder
If everything worked properly, your Xcode
has a new developer disk image. Close the finder now, and quit your Xcode
. Open your Xcode
and the error will be gone. Now you can connect your latest device to old Xcode
versions.
Thanks
<form action="mailto:[email protected]" method="post" enctype="text/plain">
Name:<br>
<input type="text" name="name"><br>
E-mail:<br>
<input type="text" name="mail"><br>
Comment:<br>
<input type="text" name="comment" size="50"><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.
don't recommend Beta or Canary
channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.
Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.
Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.
On Windows there is a very useful tool you can use : git extensions. It's a gui tool and makes git operations very easy.
Also it's open sourced.
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
Well, if one needs a long whitespace in the beginning of one line only out of the whole paragraph, then this may be a solution:
<span style='display:inline-block;height:1em;width:4em;'> </span>
If that is too much to write or one needs such tabs in many places, then you can do this
<span class='tab'> </span>
Then include this into CSS:
span.tab {display:inline-block;height:1em;width:4em;}
In python, A dynamic array is an 'array' from the array module. E.g.
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
Why is everyone trying to do it the hard way? Sure, some of these approaches will work, but they're more complicated than is necessary.
OK, first - you need an image that will fit within your navbar. You can adjust your image via css height attribute (allowing width to scale) or you can just use an appropriately sized image. Whatever you decide to do - the way this looks will depend on how well you size your image.
For some reason, everyone wants to stick the image inside of an anchor with navbar-brand
, and this isn't necessary. navbar-brand
applies text styles that aren't necessary to an image, as well as the navbar-left
class (just like pull-left, but for use in a navbar). All you really need is to add navbar-left
.
<a href="#" class="navbar-left"><img src="/path/to/image.png"></a>
You can even follow this with a navbar-brand item, which will appear to the right of the image.
The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
The problem with the PHP $_SERVER['HTTP_REFFERER'] is that it gives the fully qualified page url of the page that brought you to the parent page. That's not the same as the parent page, itself. Worse, sometimes there is no http_referer, because the person typed in the url of the parent page. So, if I get to your parent page from yahoo.com, then yahoo.com becomes the http_referer, not your page.
More detailed information are available in the platform
module.
This isn't appropriate in all situations but you can conditionally return false
inside the component itself if a certain criteria is or isn't met.
It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.
import React, { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
hideComponent: false
}
}
closeThis = () => {
this.setState(prevState => ({
hideComponent: !prevState.hideComponent
})
});
render() {
if (this.state.hideComponent === true) {return false;}
return (
<div className={`content`} onClick={() => this.closeThis}>
YOUR CODE HERE
</div>
);
}
}
The current (2015) way to do this is using the JavaScript pushState method.
PushState changes the URL in the top browser bar without reloading the page. Say you have a page containing tabs. The tabs hide and show content, and the content is inserted dynamically, either using AJAX or by simply setting display:none and display:block to hide and show the correct tab content.
When the tabs are clicked, use pushState to update the url in the address bar. When the page is rendered, use the value in the address bar to determine which tab to show. Angular routing will do this for you automatically.
There are two ways to hit a PushState Single Page App (SPA)
The initial hit on the site will involve hitting the URL directly. Subsequent hits will simply AJAX in content as the PushState updates the URL.
Crawlers harvest links from a page then add them to a queue for later processing. This means that for a crawler, every hit on the server is a direct hit, they don't navigate via Pushstate.
Precomposition bundles the initial payload into the first response from the server, possibly as a JSON object. This allows the Search Engine to render the page without executing the AJAX call.
There is some evidence to suggest that Google might not execute AJAX requests. More on this here:
Google has been able to parse JavaScript for some time now, it's why they originally developed Chrome, to act as a full featured headless browser for the Google spider. If a link has a valid href attribute, the new URL can be indexed. There's nothing more to do.
If clicking a link in addition triggers a pushState call, the site can be navigated by the user via PushState.
PushState is currently supported by Google and Bing.
Here's Matt Cutts responding to Paul Irish's question about PushState for SEO:
Here is Google announcing full JavaScript support for the spider:
http://googlewebmastercentral.blogspot.de/2014/05/understanding-web-pages-better.html
The upshot is that Google supports PushState and will index PushState URLs.
See also Google webmaster tools' fetch as Googlebot. You will see your JavaScript (including Angular) is executed.
Here is Bing's announcement of support for pretty PushState URLs dated March 2013:
http://blogs.bing.com/webmaster/2013/03/21/search-engine-optimization-best-practices-for-ajax-urls/
Hashbang urls were an ugly stopgap requiring the developer to provide a pre-rendered version of the site at a special location. They still work, but you don't need to use them.
Hashbang URLs look like this:
domain.com/#!path/to/resource
This would be paired with a metatag like this:
<meta name="fragment" content="!">
Google will not index them in this form, but will instead pull a static version of the site from the _escaped_fragments_ URL and index that.
Pushstate URLs look like any ordinary URL:
domain.com/path/to/resource
The difference is that Angular handles them for you by intercepting the change to document.location dealing with it in JavaScript.
If you want to use PushState URLs (and you probably do) take out all the old hash style URLs and metatags and simply enable HTML5 mode in your config block.
Google Webmaster tools now contains a tool which will allow you to fetch a URL as google, and render JavaScript as Google renders it.
https://www.google.com/webmasters/tools/googlebot-fetch
To generate real URLs in Angular, rather than # prefixed ones, set HTML5 mode on your $locationProvider object.
$locationProvider.html5Mode(true);
Since you are using real URLs, you will need to ensure the same template (plus some precomposed content) gets shipped by your server for all valid URLs. How you do this will vary depending on your server architecture.
Your app may use unusual forms of navigation, for example hover or scroll. To ensure Google is able to drive your app, I would probably suggest creating a sitemap, a simple list of all the urls your app responds to. You can place this at the default location (/sitemap or /sitemap.xml), or tell Google about it using webmaster tools.
It's a good idea to have a sitemap anyway.
Pushstate works in IE10. In older browsers, Angular will automatically fall back to hash style URLs
The following content is rendered using a pushstate URL with precomposition:
http://html5.gingerhost.com/london
As can be verified, at this link, the content is indexed and is appearing in Google.
Because the search engine will always hit your server for every request, you can serve header status codes from your server and expect Google to see them.
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="
This would be written into your form like so:
<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>
The best way to protect against this is to use htmlspecialchars()
to secure your input. This encodes characters such as <
into <
. For example:
<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>
You can read more about XSS here: https://www.owasp.org/index.php/XSS
Form Modification
If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg
with ../index.php
or ../db-connect.php
).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
edit/addition:
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
I add a new column with ones to a matrix array in this way:
Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T
Maybe it is not that efficient?
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
-- Disable the constraints on a table called tableName:
ALTER TABLE tableName NOCHECK CONSTRAINT ALL
-- Re-enable the constraints on a table called tableName:
ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL
---------------------------------------------------------
-- Disable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
-- Re-enable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
---------------------------------------------------------
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
You can use lynx with -stdin and -dump options to achieve that:
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/htmp2txt.log", "a") // stderr is a file to write to
);
$process = proc_open('lynx -stdin -dump 2>&1', $descriptorspec, $pipes, '/tmp', NULL);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to htmp2txt.log
$stdin = $pipes[0];
fwrite($stdin, <<<'EOT'
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TEST</title>
</head>
<body>
<h1><span>Lorem Ipsum</span></h1>
<h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
<h5>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et sapien ut erat porttitor suscipit id nec dui. Nam rhoncus mauris ac dui tristique bibendum. Aliquam molestie placerat gravida. Duis vitae tortor gravida libero semper cursus eu ut tortor. Nunc id orci orci. Suspendisse potenti. Phasellus vehicula leo sed erat rutrum sed blandit purus convallis.
</p>
<p>
Aliquam feugiat, neque a tempus rhoncus, neque dolor vulputate eros, non pellentesque elit lacus ut nunc. Pellentesque vel purus libero, ultrices condimentum lorem. Nam dictum faucibus mollis. Praesent adipiscing nunc sed dui ultricies molestie. Quisque facilisis purus quis felis molestie ut accumsan felis ultricies. Curabitur euismod est id est pretium accumsan. Praesent a mi in dolor feugiat vehicula quis at elit. Mauris lacus mauris, laoreet non molestie nec, adipiscing a nulla. Nullam rutrum, libero id pellentesque tempus, erat nibh ornare dolor, id accumsan est risus at leo. In convallis felis at eros condimentum adipiscing aliquam nisi faucibus. Integer arcu ligula, porttitor in fermentum vitae, lacinia nec dui.
</p>
</body>
</html>
EOT
);
fclose($stdin);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.
Use a JavaScript file and then use module exports.
Example:
var Globals = {
'domain':'www.MrGlobal.com';
}
module.exports = Globals;
Then if you want to use these, use require.
var globals = require('globals'); // << globals.js path
globals.domain // << Domain.
Python has a stable sort, so provided that performance isn't an issue the simplest way is to sort it by field 2 and then sort it again by field 1.
That will give you the result you want, the only catch is that if it is a big list (or you want to sort it often) calling sort twice might be an unacceptable overhead.
list1 = sorted(csv1, key=operator.itemgetter(2))
list1 = sorted(list1, key=operator.itemgetter(1))
Doing it this way also makes it easy to handle the situation where you want some of the columns reverse sorted, just include the 'reverse=True' parameter when necessary.
Otherwise you can pass multiple parameters to itemgetter or manually build a tuple. That is probably going to be faster, but has the problem that it doesn't generalise well if some of the columns want to be reverse sorted (numeric columns can still be reversed by negating them but that stops the sort being stable).
So if you don't need any columns reverse sorted, go for multiple arguments to itemgetter, if you might, and the columns aren't numeric or you want to keep the sort stable go for multiple consecutive sorts.
Edit: For the commenters who have problems understanding how this answers the original question, here is an example that shows exactly how the stable nature of the sorting ensures we can do separate sorts on each key and end up with data sorted on multiple criteria:
DATA = [
('Jones', 'Jane', 58),
('Smith', 'Anne', 30),
('Jones', 'Fred', 30),
('Smith', 'John', 60),
('Smith', 'Fred', 30),
('Jones', 'Anne', 30),
('Smith', 'Jane', 58),
('Smith', 'Twin2', 3),
('Jones', 'John', 60),
('Smith', 'Twin1', 3),
('Jones', 'Twin1', 3),
('Jones', 'Twin2', 3)
]
# Sort by Surname, Age DESCENDING, Firstname
print("Initial data in random order")
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred''')
DATA.sort(key=lambda row: row[1])
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.''')
DATA.sort(key=lambda row: row[2], reverse=True)
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
''')
DATA.sort(key=lambda row: row[0])
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
This is a runnable example, but to save people running it the output is:
Initial data in random order
Jones Jane 58
Smith Anne 30
Jones Fred 30
Smith John 60
Smith Fred 30
Jones Anne 30
Smith Jane 58
Smith Twin2 3
Jones John 60
Smith Twin1 3
Jones Twin1 3
Jones Twin2 3
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred
Smith Anne 30
Jones Anne 30
Jones Fred 30
Smith Fred 30
Jones Jane 58
Smith Jane 58
Smith John 60
Jones John 60
Smith Twin1 3
Jones Twin1 3
Smith Twin2 3
Jones Twin2 3
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.
Smith John 60
Jones John 60
Jones Jane 58
Smith Jane 58
Smith Anne 30
Jones Anne 30
Jones Fred 30
Smith Fred 30
Smith Twin1 3
Jones Twin1 3
Smith Twin2 3
Jones Twin2 3
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
Jones John 60
Jones Jane 58
Jones Anne 30
Jones Fred 30
Jones Twin1 3
Jones Twin2 3
Smith John 60
Smith Jane 58
Smith Anne 30
Smith Fred 30
Smith Twin1 3
Smith Twin2 3
Note in particular how in the second step the reverse=True
parameter keeps the firstnames in order whereas simply sorting then reversing the list would lose the desired order for the third sort key.
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
The best option according to me is to have key/value pairs file as it could be read from other scripting languages.
Other thing is I would prefer to have an option for comments in the values file - which can be easy achieved with eol
option in for /f
command.
Here's the example
values file:
;;;;;; file with example values ;;;;;;;;
;; Will be processed by a .bat file
;; ';' can be used for commenting a line
First_Value=value001
;;Do not let spaces arround the equal sign
;; As this makes the processing much easier
;; and reliable
Second_Value=%First_Value%_test
;;as call set will be used in reading script
;; refering another variables will be possible.
Third_Value=Something
;;; end
Reading script:
@echo off
:::::::::::::::::::::::::::::
set "VALUES_FILE=E:\scripts\example.values"
:::::::::::::::::::::::::::::
FOR /F "usebackq eol=; tokens=* delims=" %%# in (
"%VALUES_FILE%"
) do (
call set "%%#"
)
echo %First_Value% -- %Second_Value% -- %Third_Value%
The following formula determines if the text "CHECK" appears in cell C10. If it does not, the result is blank. If it does, the result is the work "CHECK".
=IF(ISERROR(FIND("CHECK",C10,1)),"","CHECK")
It really depends on the kind of classes as not all classes are created equal.
As general guideline I would suggest 2 options:
Use String.equalsIgnoreCase()
.
Use the Java API reference to find answers like these:
As a workaround you can use the fact percent vertical padding and margin are computed from the container width. It's quite a ugly solution and I don't know if you'll be able to use it but well, it works: http://jsfiddle.net/bFWT9/
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>It works!</div>
</body>
</html>
html, body, div {
height: 100%;
}
body {
margin: 0;
}
div {
box-sizing: border-box;
margin-top: -75%;
padding-top: 75%;
background: #d35400;
color: #fff;
}
In your connection string replace server=localhost
with "server = Paul-PC\\SQLEXPRESS;
"
I'd just like to add, and please correct me if I'm wrong, that when I embed the HTML5 version of the videos, it doesn't play ads on top.
Not sure if this will ever change. They're probably just trying to work out the best way to show ads on the HTML5 player.
{% if profile.user.first_name %}
works (assuming you also don't want to accept ''
).
if
in Python in general treats None
, False
, ''
, []
, {}
, ... all as false.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:
CREATE PROCEDURE dept_count
(
-- Add input and output parameters for the stored procedure here
@dept_name varchar(20), --Input parameter
@d_count int OUTPUT -- Output parameter declared with the help of OUTPUT/OUT keyword
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Statements for procedure here
SELECT @d_count = count(*)
from instructor
where instructor.dept_name=@dept_name
END
GO
and to execute above procedure we can write as:
Declare @dept_name varchar(20), -- Declaring the variable to collect the dept_name
@d_count int -- Declaring the variable to collect the d_count
SET @dept_name = 'Test'
Execute dept_count @dept_name,@d_count output
SELECT @d_count -- "Select" Statement is used to show the output