This worked for me in ASP.NET Core MVC.
<script type="text/javascript">
var ar = @Html.Raw(Json.Serialize(Model.Addresses));
</script>
You can also use this very simplified form:
@Html.ActionLink("Come back to Home", "Index", "Home")
Where :
Come back to Home
is the text that will appear on the page
Index
is the view name
Home
is the controller name
Html.CheckBoxFor
expects a Func<TModel, bool>
as the first parameter. Therefore your lambda must return a bool
, you are currently returning an instance of List<Checkboxes>
:
model => model.EmploymentType
You need to iterate over the List<Checkboxes>
to output each checkbox:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked,
new { id = string.Format("employmentType_{0}", i) })
}
In case the browser LAN proxy setting solution doesn't work for you:
As mentioned in this similar Q&A How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?
Simply changing the port number of your web project can be a quick fix.
Below are some of the way by which you can create a link button in MVC.
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
@Html.Action("Action", "Controller", new { area = "AreaName" })
@Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
Do you have a _ViewStart.cshtml
in this directory? I had the same problem you're having when I tried using _ViewStart. Then I renamed it _mydefaultview, moved it to the Views/Shared
directory, and switched to specifying no view in cshtml files where I don't want it, and specifying _mydefaultview for the rest. Don't know why this was necessary, but it worked.
Short:
In you have this problem with a pure Web API project (and thus don't need razor), try to add it anyway, rebuild, then remove it.
Long story:
I had this problem with a brand-new pure Web API project, except that the stacktrace pointed "System.Web.Mvc" as Calling assembly (see Darin's answer).
No reference to MVC, Razor or anything like that in my project though...
I decided to add the MVC packages (AspNet.Mvc, AspNet.WebPages and AspNet.Razor) to check if there was any subsequent problem.
The WebApi app then launched perfectly fine. Then I removed the exact same packages and everything was still OK.
Hope it helps someone.
@Html.Partial("nameOfPartial", Model)
Update
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter()) {
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
You can pass values by using the below .
@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )
Controller:
public ActionResult About(string name)
{
ViewBag.Message = "Your application description page.";
ViewBag.NameTransfer = name;
return View();
}
And the URL looks like
http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay
If you're doing the check inside the View, put the value in the ViewBag
.
In your controller:
ViewBag["parameterName"] = Request["parameterName"];
It's worth noting that the Request
and Response
properties are exposed by the Controller
class. They have the same semantics as HttpRequest
and HttpResponse
.
You are setting it't type
as submit
. That means that browser should post your <form>
data to the server.
In fact a tag has no type attribute according to w3schools.
So remote type
attribute and it should work for you.
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster")
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
else
cLayout = "~/Views/Shared/_Layout.cshtml";
Layout = cLayout;
}
Read Complete Article here "How to Render different Layout in ASP.NET MVC"
if you want to populate contents of your partial view inside your view you can use
@Html.Partial("PartialViewName")
or
{@Html.RenderPartial("PartialViewName");}
if you want to make server request and process the data and then return partial view to you main view filled with that data you can use
...
@Html.Action("Load", "Home")
...
public PartialViewResult Load()
{
return PartialView("_LoadView");
}
if you want user to click on the link and then populate the data of partial view you can use:
@Ajax.ActionLink(
"Click Here to Load the Partial View",
"ActionName",
"ControlerName",
null,
new AjaxOptions { UpdateTargetId = "toUpdate" }
)
Set this to False on your web.config
<compilation debug="false" targetFramework="4.6.1" />
You could use the Request.RawUrl
, Request.Url.OriginalString
, Request.Url.ToString()
or Request.Url.AbsoluteUri
.
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @
:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, .
, which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
In case you're using pure razor, i.e. no MVC controller:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
@if (IsPost)
{
<p>@Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.
You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step
geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
You mean inline helper?
@helper SayHello(string name)
{
<div>Hello @name</div>
}
@SayHello("John")
If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
var divLength = $('div').length;
alert(divLength);
});
</script>
I used the code below to create a Button and it worked for me.
<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>
Try this ,
<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>
(or)
<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.
For example, if your view model was:
public class SampleViewModel
{
public string SampleString { get; set; }
public MvcHtmlString SampleHtmlString { get; set; }
}
For Core 1.0+ (and MVC 5+) use HtmlString
public class SampleViewModel
{
public string SampleString { get; set; }
public HtmlString SampleHtmlString { get; set; }
}
then
<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>
Found that in .Net Core, placing the favicon.ico in /lib rather than wwwroot fixes the issue
I think a more elegant solution is to use the controller and the ViewData dictionary:
//Controller:
public ActionResult Action(int IFRAME)
{
ViewData["IsIframe"] = IFRAME == 1;
return View();
}
//view
@{
string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : "";
<div id="wrap" class='@classToUse'></div>
}
You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...
<input type="text" id="@strElementID" class="@strCSSClass" />
If strCSSClass is null then the class attribute won't render at all.
SSSHHH...don't tell. :)
IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.
You can do the same things with both, but you should use typed views and TextboxFor when possible.
This one worked for me, try this
[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/[email protected]">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!
<span style="white-space: pre-line">@Model.CommentText</span>
Everything is encoded by default!!! This is pretty huge.
Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.
You can make a section required which is nice.
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
I prefer to use the razor html helper from Client Dependency dll
Html.RequireCss("yourfile", 9999); // 9999 is loading priority
This is solution:
@item.Published.Value.ToString("dd. MM. yyyy")
Before ToString() use Value.
In Core 2.2 Razor pages this syntax works:
<button type="submit" name="Submit">Save</button>
<button type="submit" name="Cancel">Cancel</button>
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
return Page();
var sub = Request.Form["Submit"];
var can = Request.Form["Cancel"];
if (sub.Count > 0)
{
.......
The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName)
.
Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)
In this case you have to use @foreach
@foreach (var item in Model.Foos)
{
@Html.DisplayFor(x => item, "FooTemplate")
}
If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database. form of it:
@Html.CheckBox("NameOfVarInModel", true) ;
for you!
@Html.CheckBox("AllowRating", true) ;
In my case, I recently updated from MVC 4 to MVC 5, which screws up the web.config pretty badly. This article helped tremendously.
The bottom line is that you need to check all your version number references in your web.config and Views/web.config to make sure that they are referencing the correct upgraded versions associated with MVC 5.
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});
You must define states not equal to null..
@if (ViewBag.States!= null)
{
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
value="@de.Key">@de.Value
}
}
With credits to the previous answer by @Bronek and @Shimmy:
This is like I have done the same thing in ASP.NET Core:
<input asp-for="DisabledField" disabled="disabled" />
<input asp-for="DisabledField" class="hidden" />
The first input is readonly and the second one passes the value to the controller and is hidden. I hope it will be useful for someone working with ASP.NET Core.
When you are using foreach loop within view for binded model ... Your model is supposed to be in listed format.
i.e
@model IEnumerable<ViewModels.MyViewModels>
@{
if (Model.Count() > 0)
{
@Html.DisplayFor(modelItem => Model.Theme.FirstOrDefault().name)
@foreach (var theme in Model.Theme)
{
@Html.DisplayFor(modelItem => theme.name)
@foreach(var product in theme.Products)
{
@Html.DisplayFor(modelItem => product.name)
@foreach(var order in product.Orders)
{
@Html.TextBoxFor(modelItem => order.Quantity)
@Html.TextAreaFor(modelItem => order.Note)
@Html.EditorFor(modelItem => order.DateRequestedDeliveryFor)
}
}
}
}else{
<span>No Theam avaiable</span>
}
}
This worked for me
<img src="data:image;base64,@System.Convert.ToBase64String(Model.CategoryPicture.Content)" width="80" height="80"/>
This works for me, in MVC5:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "theID" , @Value="test" })
Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.
Create a view model class like this:
public class EmployeeAddViewModel
{
public Employee employee { get; set; }
public Dictionary<int, string> staffTypes { get; set; }
// really? a 1-to-many for genders
public Dictionary<int, string> genderTypes { get; set; }
public EmployeeAddViewModel() { }
public EmployeeAddViewModel(int id)
{
employee = someEntityContext.Employees
.Where(e => e.ID == id).SingleOrDefault();
// instantiate your dictionaries
foreach(var staffType in someEntityContext.StaffTypes)
{
staffTypes.Add(staffType.ID, staffType.Type);
}
// repeat similar loop for gender types
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
return View(new EmployeeAddViewModel());
}
[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View("Index"); // or wherever you go after successful add
}
return View(vm);
}
Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:
@Html.DropDownListFor(model => model.employee.staffTypeID,
new SelectList(model.staffTypes, "ID", "Type"))
and similarly for the gender dropdown
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(model.genderTypes, "ID", "Gender"))
Update per comments
For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList...
below, you would use your IEnumerable.
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(new SelectList()
{
new { ID = 1, Gender = "Male" },
new { ID = 2, Gender = "Female" }
}, "ID", "Gender"))
Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:
ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1 | Gender | 1 | Male | male gender | 1
2 | State | 50 | Hawaii | 50th state | 1
3 | Gender | 2 | Female | female gender | 1
4 | State | 49 | Alaska | 49th state | 1
5 | OrderType | 1 | Web | online order | 1
I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.
Hope this helps!
They should be under C:\Program Files\Microsoft ASP.Net
(or C:\Program Files (x86)\Microsoft ASP.Net
if you're on a 64-bit OS) in a subfolder for MVC3 or WebPages.
Use the parentesis syntax of Razor:
@(Model.address + " " + Model.city)
or
@(String.Format("{0} {1}", Model.address, Model.city))
Update: With C# 6 you can also use the $-Notation (officially interpolated strings):
@($"{Model.address} {Model.city}")
After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.
The Javascript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).
This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server gets a request.
The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)
the browser renders the page and executes all the Javascript
You'll need AJAX if you want to update a part of your page without reloading the entire page.
main cshtml view
<div id="refTable">
<!-- partial view content will be inserted here -->
</div>
@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>
<script>
$(document).ready(function() {
$("#pY").on("click", function() {
var val = $('#yearSelect3').val();
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
});
});
</script>
You'll need to add the fields I have omitted. I've used a <button>
instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.
The HolidayPartialView gets rendered into html and the jquery done
callback inserts that html fragment into the refTable div.
HolidayController Update action
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.
view model
public class HolidayViewModel
{
IEnumerable<DateTime> Dates { get; set; }
}
HolidayPartialView.csthml
@model Your.Namespace.HolidayViewModel;
<table class="tblHoliday">
@foreach(var date in Model.Dates)
{
<tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
}
</table>
This is the stuff that gets inserted into your div.
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:
https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:
yourRecord.FieldName = Request.Form["FieldNameInModel"];
As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.
No, I did not dig down to see how th4e magic works under the covers. I just know it works...
I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.
I think that the usage of @Html.LabelForModel()
should be explained in more detail.
The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.
You could refer to the following code:
Code in model:
using System.ComponentModel;
[DisplayName("MyModel")]
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
Code in view:
@Html.LabelForModel()
<div class="form-group">
@Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Test)
@Html.ValidationMessageFor(model => model.Test)
</div>
</div>
The output screenshot:
I found that putting this section in my web.config for each view folder solved it.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
Try adding the namespace your MyClasses
is in to the web.config under
<pages>
<namespaces></namespaces>
</pages>
Try the out-of-the-box solution (ASP.NET MVC 4 or later):
@{
var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");
bundle.Include("~/Scripts/myFile.js");
}
The following solution works only for single page reports. Refer to comments for more details.
ReportViewer is a server control and thus can not be used within a razor view. However you can add a ASPX view page, view user control or traditional web form that containing a ReportViewer into the application.
You will need to ensure that you have added the relevant handler into your web.config.
If you use a ASPX view page or view user control you will need to set AsyncRendering to false to get the report to display properly.
Update:
Added more sample code. Note there are no meaningful changes required in Global.asax.
Web.Config
Mine ended up as follows:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Controller
The controller actions are very simple.
As a bonus the File() action returns the output of "TestReport.rdlc" as a PDF file.
using System.Web.Mvc;
using Microsoft.Reporting.WebForms;
...
public class PDFController : Controller
{
public ActionResult Index()
{
return View();
}
public FileResult File()
{
ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
rv.ProcessingMode = ProcessingMode.Local;
rv.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
rv.LocalReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return File(streamBytes, mimeType, "TestReport.pdf");
}
public ActionResult ASPXView()
{
return View();
}
public ActionResult ASPXUserControl()
{
return View();
}
}
ASPXView.apsx
The ASPXView is as follows.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ASPXView</title>
</head>
<body>
<div>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
ReportViewer1.LocalReport.Refresh();
}
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<rsweb:reportviewer id="ReportViewer1" runat="server" height="500" width="500" AsyncRendering="false"></rsweb:reportviewer>
</form>
</div>
</body>
</html>
ViewUserControl1.ascx
The ASPX user control looks like:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
ReportViewer1.LocalReport.Refresh();
}
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" AsyncRendering="false"></rsweb:ReportViewer>
</form>
ASPXUserControl.cshtml
Razor view. Requires ViewUserControl1.ascx.
@{
ViewBag.Title = "ASPXUserControl";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ASPXUserControl</h2>
@Html.Partial("ViewUserControl1")
References
Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
Results in
(<b><script>console.log('insert')</script>Hello</b>)
When you're doing this
var model = @Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
@Html.Raw("@")
seems to me to be even more reliable than @@
, since not in all cases @@
will escape.
Therefore:
<meta name="twitter:site" content="@twitterSite">
would be:
<meta name="twitter:site" content="@Html.Raw("@")twitterSite">
Here is a good eplanation: ASP.NET MVC – Multiple buttons in the same form
In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute
(which I personaly prefer and suggest).
Simply Try this
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })
But if you want a default value or no option value then you must have to try this one, because String.Empty
will select that no value for you which will work as a -select-
as default option
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, String.Empty, new { @class="dropdown" })
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
A simpler version, for easy eyes!
@(true?"yes":"no")
In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DtCadastro)
</td>
<td style="width:50%">
@Html.DisplayFor(modelItem => item.DsLembrete)
</td>
<td>
@Html.DisplayFor(modelItem => item.DtLembrete)
</td>
<td>
@{
var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
}
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
<button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
</td>
<td class="text-right">
<button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
</td>
</tr>
}
do as coded:
@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}
and use it like this:
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.
How are you running the application? Are you just hitting the website or are you building and running from within Visual Studio? If you are building and running you may want to tell it to use the local IIS web server. This would make sure it is using the App Pool you have set up to run with v4.0/integrated.
I am guessing that it is using the Visual Studio Development Server when running. This server is probably trying to run with the 2.0 framework. This then causes your error to be thrown.
Edit: To note, I normally just build my website application and then I attach to process w3wp when I want to debug. I do not use the publishing tool. Of course this means my local working directory is within the web root.
As GvS said, but I also find it useful to use strongly typed views so that I can write something like
@Html.Partial(MVC.Student.Index(), model)
without magic strings.
The model (@Model
) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.
What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor
will suffice.
However, you will want to change your foreach loop to a for loop. The final solution will look something like this:
for (int i = 0 ; i < Model.Post; i++)
{
<br/>
<b>Posted by :</b> @Model.Post[i].Username <br/>
<span>@Model.Post[i].Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.HiddenFor(model => model.Post[i].PostID)
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit">Add Comment</button>
}
}
Solved
Model
public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}
Controller
public class BookController : Controller
{
[HttpPost]
public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
{
throw new NotImplementedException();
}
}
And View
@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.EditorFor(m => m)
<input type="file" name="fileUpload[0]" /><br />
<input type="file" name="fileUpload[1]" /><br />
<input type="file" name="fileUpload[2]" /><br />
<input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}
Note title of parameter from controller action must match with name of input elements
IEnumerable<HttpPostedFileBase> fileUpload
-> name="fileUpload[0]"
fileUpload
must match
If you don't use html helpers you may use simple ternary expression like this:
<input name="Field"
value="@Model.Field" tabindex="0"
@(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>
If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.
This comment syntax should work for you:
@* enter comments here *@
While the syntax is certainly different between Razor (.cshtml
/.vbhtml
) and WebForms (.aspx
/.ascx
), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
Apparently you have created an 'Empty' project type without 'Scripts' folder. My advice -create a 'Basic' project type with full 'Scripts' folder.
With respect to all developers.
Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.
For example
public class MyViewModel
{
public MyViewModel()
{
Gender = "Male";
}
}
<table>_x000D_
<tr>_x000D_
<td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
<td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
</tr>_x000D_
</table>
_x000D_
I think you were pretty close, try this:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
</div>
}
@Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })
or type = "time"
it will display a calendar
it will not work if you give @Html.EditorFor()
Use <text>
:
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
<text>
data.push([ @r.UnixTime * 1000, @r.Value ]);
</text>
}
</script>
SelectListItem
has a Selected
property. If you are creating the SelectListItem
s dynamically, you can just set the one you want as Selected = true
and it will then be the default.
SelectListItem defaultItem = new SelectListItem()
{
Value = 1,
Text = "Default Item",
Selected = true
};
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
To use BeginForm
, here's the way to use it:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
This would be work very fine
<a href="<%:Url.Action("Edit","Account",new { id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.
[ChildActionOnly]
public ActionResult Results()
{
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
bool anyRows = custs.Any();
if(anyRows == false)
{
return View("NoResults");
}
else
{
return View("OtherView");
}
}
Modify NoResults.cshtml to a Partial.
And call this as a Partial view in the parent view
@Html.Partial("Results")
You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3
The ChildActionOnly
attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
and in your controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Categories = Repository.GetCategories()
}
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was a validation error =>
// rebind categories and redisplay view
model.Categories = Repository.GetCategories();
return View(model);
}
// At this stage the model is OK => do something with the selected category
return RedirectToAction("Success");
}
}
and then in your strongly typed view:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
Also if you want client side validation don't forget to reference the necessary scripts:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.
A simple and a good straight-forward example:
<script>
// This gets the username from the Razor engine and puts it
// in JavaScript to create a variable I can access from the
// client side.
//
// It's an odd workaraound, but it works.
@{
var outScript = "var razorUserName = " + "\"" + @User.Identity.Name + "\"";
}
@MvcHtmlString.Create(outScript);
</script>
This creates a script in your page at the location you place the code above which looks like the following:
<script>
// This gets the username from the Razor engine and puts it
// in JavaScript to create a variable I can access from
// client side.
//
// It's an odd workaraound, but it works.
var razorUserName = "daylight";
</script>
Now you have a global JavaScript variable named razorUserName
which you can access and use on the client. The Razor engine has obviously extracted the value from @User.Identity.Name
(server-side variable) and put it in the code it writes to your script tag.
Complicating a primitive with hidden fields to clarify whether False or Null is not recommended.
Checkbox isn't what you should be using -- it really only has one state: Checked. Otherwise, it could be anything.
When your database field is a nullable boolean (bool?
), the UX should use 3-Radio Buttons, where the first button represents your "Checked", the second button represents "Not Checked" and the third button represents your null, whatever the semantics of null means. You could use a <select><option>
drop down list to save real estate, but the user has to click twice and the choices aren't nearly as instantaneously clear.
1 0 null
True False Not Set
Yes No Undecided
Male Female Unknown
On Off Not Detected
The RadioButtonList, defined as an extension named RadioButtonForSelectList, builds the radio buttons for you, including the selected/checked value, and sets the <div class="RBxxxx">
so you can use css to make your radio buttons go horizontal (display: inline-block), vertical, or in a table fashion (display: inline-block; width:100px;)
In the model (I'm using string, string for the dictionary definition as a pedagogical example. You can use bool?, string)
public IEnumerable<SelectListItem> Sexsli { get; set; }
SexDict = new Dictionary<string, string>()
{
{ "M", "Male"},
{ "F", "Female" },
{ "U", "Undecided" },
};
//Convert the Dictionary Type into a SelectListItem Type
Sexsli = SexDict.Select(k =>
new SelectListItem
{
Selected = (k.Key == "U"),
Text = k.Value,
Value = k.Key.ToString()
});
<fieldset id="Gender">
<legend id="GenderLegend" title="Gender - Sex">I am a</legend>
@Html.RadioButtonForSelectList(m => m.Sexsli, Model.Sexsli, "Sex")
@Html.ValidationMessageFor(m => m.Sexsli)
</fieldset>
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues,
String rbClassName = "Horizontal")
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = String.Empty;
if (item.Selected == true)
{
radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id, @checked = "checked" }).ToHtmlString();
}
else
{
radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
}// Create the html string to return to client browser
// e.g. <input data-val="true" data-val-required="You must select an option" id="RB_1" name="RB" type="radio" value="1" /><label for="RB_1">Choice 1</label>
sb.AppendFormat("<div class=\"RB{2}\">{0}{1}</div>", radio, label, rbClassName);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
combining all edge-cases together from above:
Equals
, ToString
)Display
attributehere is my code:
public enum Enum
{
[Display(Name = "What a weird name!")]
ToString,
Equals
}
public static class EnumHelpers
{
public static string GetDisplayName(this Enum enumValue)
{
var enumType = enumValue.GetType();
return enumType
.GetMember(enumValue.ToString())
.Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == enumType)
.First()
.GetCustomAttribute<DisplayAttribute>()?.Name ?? enumValue.ToString();
}
}
void Main()
{
Assert.Equals("What a weird name!", Enum.ToString.GetDisplayName());
Assert.Equals("Equals", Enum.Equals.GetDisplayName());
}
This is one of the basic differences not mentioned in previous comments:
Readonly
property will work with textbox for and it will not work with EditorFor
.
@Html.TextBoxFor(model => model.DateSoldOn, new { @readonly = "readonly" })
Above code works, where as with following you can't make control to readonly.
@Html.EditorFor(model => model.DateSoldOn, new { @readonly = "readonly" })
This one can also be used with less effort I believe (but I am in MVC 5)
@Html.Description(model => model.Story, 20, 50, new { })
I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.
First we create "Parent" object function
function Parent(){
}
Then add a prototype to "Parent" object function
Parent.prototype = {
primitive : 1,
object : {
one : 1
}
}
Create "Child" object function
function Child(){
}
Assign child prototype (Make child prototype inherit from parent prototype)
Child.prototype = Object.create(Parent.prototype);
Assign proper "Child" prototype constructor
Child.prototype.constructor = Child;
Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects
Child.prototype.changeProps = function(){
this.primitive = 2;
this.object.one = 2;
};
Initiate Parent (dad) and Child (son) objects.
var dad = new Parent();
var son = new Child();
Call Child (son) changeProps method
son.changeProps();
Check the results.
Parent primitive property did not change
console.log(dad.primitive); /* 1 */
Child primitive property changed (rewritten)
console.log(son.primitive); /* 2 */
Parent and Child object.one properties changed
console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */
Working example here http://jsbin.com/xexurukiso/1/edit/
More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create
There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released
https://github.com/Kotlin/kotlinx.serialization
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")
fun main(args: Array<String>) {
// serializing objects
val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
println(jsonData) // {"a": 42, "b": "42"}
// serializing lists
val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
println(jsonList) // [{"a": 42, "b": "42"}]
// parsing data back
val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
println(obj) // MyModel(a=42, b="42")
}
The result integer value is out of the range which an integer data type can hold.
Try using Int64
This Works Better and Faster For Me
<html>
<head>
<script>
function showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
<option value="job">Job</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
**The Backend File **
<?php
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google") {
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
$xml=("https://www.zdnet.com/news/rss.xml");
}elseif($q == "job"){
$xml=("https://ngcareers.com/feed");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
$count = $x->length;
// print_r( $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue);
// return;
for ($i=0; $i <= $count; $i++) {
//Title
$item_title = $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue;
//Link
$item_link = $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue;
//Description
$item_desc = $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
//Category
$item_cat = $x->item(0)->getElementsByTagName('category')->item(0)->nodeValue;
echo ("<p>Title: <a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ("Desc: ".$item_desc);
echo ("<br>");
echo ("Category: ".$item_cat . "</p>");
}
?>
Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL
. If you don't allow NULL
, and don't have a default
, what is the value going to be?
Since SQL Server supports ADD CONSTRAINT
, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL
constraint after you've filled it with non-NULL
values.
Another javascript library worth mentioning is pdfmake.
The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.
You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.
Given a form like:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
The straight DOM way:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
Simple DOM way. This may not work in older browsers that don't like file inputs:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
The jQuery way:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947
You can either user STR_TO_DATE function and pass your own date parameters based on the format you have posted :
select * from hockey_stats where game_date
between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s')
order by game_date desc;
Or just use the format which MySQL handles dates YYYY:MM:DD HH:mm:SS and have the query as
select * from hockey_stats where game_date between '2012-03-11 00:00:00' and'2012-05-11 23:59:00' order by game_date desc;
$host = $request->server->get('HTTP_HOST');
$base = (!empty($request->server->get('BASE'))) ? $request->server->get('BASE') : '';
$getBaseUrl = $host.$base;
If you are using bootstrap and font-awesome then it is easy, no need to write a single line of new code, just add fa-Nx, as big you want, See the demo
<span class="glyphicon glyphicon-globe"></span>
<span class="glyphicon glyphicon-globe fa-lg"></span>
<span class="glyphicon glyphicon-globe fa-2x"></span>
<span class="glyphicon glyphicon-globe fa-3x"></span>
<span class="glyphicon glyphicon-globe fa-4x"></span>
<span class="glyphicon glyphicon-globe fa-5x"></span>
Mustache templates are, by design, very simple; the homepage even says:
Logic-less templates.
So the general approach is to do your logic in JavaScript and set a bunch of flags:
if(notified_type == "Friendship")
data.type_friendship = true;
else if(notified_type == "Other" && action == "invite")
data.type_other_invite = true;
//...
and then in your template:
{{#type_friendship}}
friendship...
{{/type_friendship}}
{{#type_other_invite}}
invite...
{{/type_other_invite}}
If you want some more advanced functionality but want to maintain most of Mustache's simplicity, you could look at Handlebars:
Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.
Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.
While inserting the data, we have to used character string delimiter (' '
). And, you missed it (' '
) while inserting values which is the reason of your error message. The correction of code is given below:
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
If on MacOSx try
xcode-select --install
This complies subprocess 32
, the reason for the failure.
They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.
If you want to test for value equality should use the handy comparison functions in java.util.Arrays
e.g.
import java.util.Arrays;
'''''
Arrays.equals(a,b);
It's working for me:
File file = path.toFile();
String mimeType = Files.probeContentType(path);
DiskFileItem fileItem = new DiskFileItem("file", mimeType, false, file.getName(), (int) file.length(),
file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
I think that I also faced this problem, and the best solution I found was to look at my console and figure out the error that was being thrown. So, I read it carefully and found that the problem was that I didn't specify my repo, description, and valid name in my package.json
. I added those pieces of information and everything was okay.
Before proceeding further with the fuss of immutability, let's just take a look into the String
class and its functionality a little before coming to any conclusion.
This is how String
works:
String str = "knowledge";
This, as usual, creates a string containing "knowledge"
and assigns it a reference str
. Simple enough? Lets perform some more functions:
String s = str; // assigns a new reference to the same string "knowledge"
Lets see how the below statement works:
str = str.concat(" base");
This appends a string " base"
to str
. But wait, how is this possible, since String
objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str
, i.e. "knowledge"
and appends " base"
, giving us the value "knowledge base"
. Now, since String
s are immutable, the VM can't assign this value to str
, so it creates a new String
object, gives it a value "knowledge base"
, and gives it a reference str
.
An important point to note here is that, while the String
object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String
object.
At this point in the example above, we have two String
objects: the first one we created with value "knowledge"
, pointed to by s
, and the second one "knowledge base"
, pointed to by str
. But, technically, we have three String
objects, the third one being the literal "base"
in the concat
statement.
What if we didn't have another reference s
to "knowledge"
? We would have lost that String
. However, it still would have existed, but would be considered lost due to having no references.
Look at one more example below
String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1); // Yes, s1 still refers to "java"
What's happening:
String
"java"
and refer s1
to it.String
"java rules"
, but nothing
refers to it. So, the second String
is instantly lost. We can't reach
it.The reference variable s1
still refers to the original String
"java"
.
Almost every method, applied to a String
object in order to modify it, creates new String
object. So, where do these String
objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.
As applications grow, it's very common for String
literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".
When the compiler sees a String
literal, it looks for the String
in the pool. If a match is found, the reference to the new literal is directed to the existing String
and no new String
object is created. The existing String
simply has one more reference. Here comes the point of making String
objects immutable:
In the String
constant pool, a String
object is likely to have one or many references. If several references point to same String
without even knowing it, it would be bad if one of the references modified that String
value. That's why String
objects are immutable.
Well, now you could say, what if someone overrides the functionality of String
class? That's the reason that the String
class is marked final
so that nobody can override the behavior of its methods.
I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:
We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Great guide, thank you. Given most instructions here, it almost built for me but I did have one remaining error.
/usr/bin/ld: //usr/local/lib/libglfw3.a(glx_context.c.o): undefined reference to symbol 'dlclose@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libdl.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
After searching for this error, I had to add -ldl
to the command line.
g++ main.cpp -lglfw3 -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -lGL -lpthread -ldl
Then the "hello GLFW" sample app compiled and linked.
I am pretty new to linux so I am not completely certain what exactly this extra library does... other than fix my linking error. I do see that cmd line switch in the post above, however.
i used following links in my wordpress website for sharing my blogs,they work fine:
whatsapp share : https://wa.me/?text=(some-text)(your-link)
facebook share: https://www.facebook.com/sharer/sharer.php?u=(your-link)
linkedin share: http://www.linkedin.com/shareArticle?mini=true&url=(your-link)
google-plus : https://plus.google.com/share?url=(your-link)
twitter share: http://www.twitter.com/share?url=(your-link)
It's been a while since the last time i touch swing but in general is a bad practice to do this. Some of the main disadvantages that comes to mind:
It's more expensive: you will have to allocate way more resources to draw a JFrame that other kind of window container, such as Dialog or JInternalFrame.
Not user friendly: It is not easy to navigate into a bunch of JFrame stuck together, it will look like your application is a set of applications inconsistent and poorly design.
It's easy to use JInternalFrame This is kind of retorical, now it's way easier and other people smarter ( or with more spare time) than us have already think through the Desktop and JInternalFrame pattern, so I would recommend to use it.
In doubt change your editor to make tabs and spaces visible. It is also a very good idea to have the editor resolve all tabs to 4 spaces.
The following example shows benchmarks for a few alternatives.
library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
## test replications elapsed relative user.self sys.self
## 2 (0:5e+05) * 2 100 0.587 3.536145 0.344 0.244
## 1 seq(0, 1e6, by = 2) 100 2.760 16.626506 1.832 0.900
## 3 seq.int(0, 1e6, by = 2) 100 0.166 1.000000 0.056 0.096
In this case, seq.int
is the fastest method and seq
the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq
as the most readable solution.
val lines = scala.io.Source.fromFile("file.txt").mkString
By the way, "scala.
" isn't really necessary, as it's always in scope anyway, and you can, of course, import io's contents, fully or partially, and avoid having to prepend "io." too.
The above leaves the file open, however. To avoid problems, you should close it like this:
val source = scala.io.Source.fromFile("file.txt")
val lines = try source.mkString finally source.close()
Another problem with the code above is that it is horrible slow due to its implementation nature. For larger files one should use:
source.getLines mkString "\n"
As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.
If you want to actually have a program that does it, you should look into some of the automated installers out there.
Here is a way I've found:
[code]
import java.io.*;
import java.util.jar.*;
class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}
@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}
public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);
FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}
public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}
}
[/code]`
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';
See this live example of a canvas that is zoomed in by 4x.
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle = '#eff';_x000D_
_x000D_
ctx.fillRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect( 70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
The replaceAll method is attempting to match the String literal []
which does not exist within the String
try replacing these items separately.
String str = "[Chrissman-@1]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");
I would use datetime.date
data type instead, as it is simpler when it comes to checking how many years, months and days have passed:
now = date.today()
birthday = date(1993, 4, 4)
print("you are", now.year - birthday.year, "years,", now.month - birthday.month, "months and",
now.day - birthday.day, "days old")
Output:
you are 27 years, 7 months and 11 days old
I use timedelta
when I need to perform arithmetic on a specific date:
age = now - birthday
print("addition of days to a date: ", birthday + timedelta(days=age.days))
Output:
addition of days to a date: 2020-11-15
If you not use -
in id's names then you can do this
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
<span>Foo</span>_x000D_
<b>Bar</b>_x000D_
Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
There is no way to skip a check if it exists.
Starting with PHP 8 (2020-11-24), you can use str_contains:
if (str_contains('www.domain.com/car/', 'car')) {
echo 'car is exist';
} else {
echo 'no cars';
}
You could also check if the id element is used by doing so:
if(typeof $(.div).attr('id') == undefined){
//element has no id
} else {
//element has id selector
}
I use this method for global dataTables and specific ordered dataTables
In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.
You should create a function inside activity to open new fragment and pass the activity reference to the fragment and on some event inside fragment call this function.
Option Explicit
Public myarray (1 To 10)
Public Count As Integer
myarray(1) = "A"
myarray(2) = "B"
myarray(3) = "C"
myarray(4) = "D"
myarray(5) = "E"
myarray(6) = "F"
myarray(7) = "G"
myarray(8) = "H"
myarray(9) = "I"
myarray(10) = "J"
Private Function unwrapArray()
For Count = 1 to UBound(myarray)
MsgBox "Letters of the Alphabet : " & myarray(Count)
Next
End Function
UPDATE: I modified my code using this fork
also instead of using $.each I changed to $.map as suggested by Tomislav Markovski
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data, item){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
}
});
However I am encountering some problems by getting
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
as you can see on a newer post I am trying to figure out here
hope this update is of any help to you...
Here are all the Rails 4 (ActiveRecord migration) datatypes:
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:bigint
:primary_key
:references
:string
:text
:time
:timestamp
Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column
These are the same as with Rails 3.
If you use PostgreSQL, you can also take advantage of these:
:hstore
:json
:jsonb
:array
:cidr_address
:ip_address
:mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
Edit, 2016-Sep-19:
There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.
My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:
For eg. consider a slight modification of your case:
@JsonProperty("fileName")
private String fileName;
@JsonProperty("fileName")
public String getFileName()
{
return fileName;
}
@JsonProperty("fileName1")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Both fileName
field, and method getFileName
, have the correct property name of fileName
and setFileName
has a different one fileName1
, in this case Jackson will look for a fileName1
attribute in json at the point of deserialization and will create a attribute called fileName1
at the point of serialization.
Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName
, it would just pick one of them as the attribute(FILENAME
), and had any on of the three differed, it would have thrown an exception:
java.lang.IllegalStateException: Conflicting property name definitions
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat
that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat
that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat
like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
Ok - thanks to all of you - let me wrap this up:
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
go to build path and check for errors in the jar files, they might be moved to somewhere else. if you have errors on the jar files. Remove them and locate them by clicking add external jars.
-cnufederer
Maybe something like this (just add your style):
<input type="text"
size="35"
value="Job Title e.g. Assistant Manager"
style="background-color:white;
border: solid 1px #6E6E6E;
height: 30px;
font-size:18px;
vertical-align:9px;color:#bbb"
onfocus="if(this.value == 'Job Title e.g. Assistant Manager') {
this.value = '';
this.style.color='#000';
}" />
<input type="text"
name="searchterm" size="35"
style="background-color:white;
border: solid 1px #6E6E6E;
height: 30px;
font-size:18px;
vertical-align:9px" />
UPDATE: Since placeholder attribute is very well supported on all major browsers, there is no need to do anything manually. Its possible to achieve the same thing with this:
<input type="text"
size="35"
placeholder="Job Title e.g. Assistant Manager" />
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli] # This line is vital
I just ran into this issue while working with Eclipse. In my case, I had the correct Hadoop version downloaded (hadoop-2.5.0-cdh5.3.0.tgz), I extracted the contents and placed it directly in my C drive. Then I went to
Eclipse->Debug/Run Configurations -> Environment (tab) -> and added
variable: HADOOP_HOME
Value: C:\hadoop-2.5.0-cdh5.3.0
Use options(scipen=5)
or some other high enough number. The scipen option determines how likely R is to switch to scientific notation, the higher the value the less likely it is to switch. Set the option before making your plot, if it still has scientific notation, set it to a higher number.
Let us take an example of dictionary:
numbers = {'first':0, 'second':1, 'third':3}
When I did
numbers.values()[index]
I got an error:'dict_values' object does not support indexing
When I did
numbers.itervalues()
to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'
Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.
tuple(numbers.items())[key_index][value_index]
for example:
tuple(numbers.items())[0][0] gives 'first'
if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use
list(list(numbers.items())[index])
JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.
You can use exec.java
.
The current answers are outdated. You should be able to use #error version
(at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:
error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.
Here's another Python one-liner that takes into account the user's default group membership (from /etc/passwd
)as well as from the group database (/etc/group
)
python -c "import grp,pwd; print set(grp.getgrnam('mysupercoolgroup')[3]).union([u[0] for u in pwd.getpwall() if u.pw_gid == grp.getgrnam('mysupercoolgroup')[2]])"
mkmf
is part of the ruby1.9.1-dev
package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev
package by doing:
sudo apt-get install ruby1.9.1-dev
Then you can install Rails as per normal.
Generally it's easier to just do:
sudo apt-get install ruby-dev
You can't have optional path variables, but you can have two controller methods which call the same service code:
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return getTestBean(type);
}
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
HttpServletRequest req,
@RequestParam("track") String track) {
return getTestBean();
}
Answer is very simple use the .NET Framework tools sn.exe
. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,
Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.
Example
C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Public key token is b77a5c561934e089
the method TextView.setTextSize(int unit , float size);
takes two parameters .
Try this :
text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
UPDATE:
Now the setTextSize(float size)
will set the text size automatically in "scaled pixel
" units. no need to mention the COMPLEX_UNIT_SP manually.
Refer to the documentation.
also try this
$.ajax({
url: url,
data:datas,
success:function(datas, textStatus, jqXHR){
var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};
in my case server responds with unknow character before '{'
To attempt command line arguments directly is not possible.
One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).
This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html
so sudo systemctl restart myprog -v
-- systemctl will think you're trying to set one of its flags, not myprog's flag.
sudo systemctl restart myprog someotheroption
-- systemctl will restart myprog and the someotheroption service, if it exists.
Here's a different way of doing it.
If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.
filepath = 'textfile.txt'
import os
os.startfile(filepath)
Example:
import os
os.startfile('textfile.txt')
This will open textfile.txt with Notepad if Notepad is associated with .txt files.
I would like to cite a paragraph which describes the major difference between greedy algorithms and dynamic programming algorithms stated in the book Introduction to Algorithms (3rd edition) by Cormen, Chapter 15.3, page 381:
One major difference between greedy algorithms and dynamic programming is that instead of first finding optimal solutions to subproblems and then making an informed choice, greedy algorithms first make a greedy choice, the choice that looks best at the time, and then solve a resulting subproblem, without bothering to solve all possible related smaller subproblems.
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change
event handler to inputs in the form, if any of them change it uses .data()
to set a changed
value to true
, then we just check for that value on the click, this assumes that #mybutton
is inside the form (if not just replace $(this).closest('form')
with $('#myForm')
), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
NameValueCollection nvclc = Request.Form;
string uName= nvclc ["txtUserName"];
string pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);
Just Select App from dropdown menu with Run(green play icon). it will run the whole the App not the specific Activity. if it doesn't help try to use in that activity in ManiFest.xml file. thankyou
import datetime
import calendar
day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])
08 05 2015
Friday
Forget about using success
and error
method.
Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.
With the following example, I'll try to demonstrate what I mean about success
and error
being not chainable-friendly. Suppose we call an API that returns a user object with an address:
User object:
{name: 'Igor', address: 'San Francisco'}
Call to the API:
$http.get('/user')
.success(function (user) {
return user.address; <---
}) | // you might expect that 'obj' is equal to the
.then(function (obj) { ------ // address of the user, but it is NOT
console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
});
};
What happened?
Because success
and error
return the original promise, i.e. the one returned by $http.get
, the object passed to the callback of the then
is the whole user object, that is to say the same input to the preceding success
callback.
If we had chained two then
, this would have been less confusing:
$http.get('/user')
.then(function (user) {
return user.address;
})
.then(function (obj) {
console.log(obj); // -> 'San Francisco'
});
};
You can use File.AppendAllText
for that:
File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
Try this
SELECT
object_name(parent_object_id) ParentTableName,
object_name(referenced_object_id) RefTableName,
name
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Tablename')
In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.
System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.
Using relational operators:
SELECT * FROM TableA
UNION
SELECT * FROM TableB
EXCEPT
SELECT * FROM TableA
INTERSECT
SELECT * FROM TableB;
Change EXCEPT
to MINUS
for Oracle.
Slightly picky point: the above relies on operator precedence, which according to the SQL Standard is implementation dependent, so YMMV. It works for SQL Server, for which the precedence is:
INTERSECT
EXCEPT
and UNION
evaluated from left to right.SQL Server is not able to access (write) the backup into the location specified.
First you need to verify the service account on which the Sql server is running. This can be done by using Configuration manager or Services.msc.
or
Use below query :
SELECT DSS.servicename, DSS.startup_type_desc, DSS.status_desc, DSS.last_startup_time, DSS.service_account, DSS.is_clustered, DSS.cluster_nodename, DSS.filename, DSS.startup_type, DSS.status, DSS.process_id FROM sys.dm_server_services AS DSS;
Now look at the column service_account and note it down.
Go to the location where you are trying to take the backup.In your case : C:\Users\Me\Desktop\Backup
Right click--> Properties --> Security -->
Add the service account and provide read/write permissions. This will resolve the issue.
The minimum requirements are based on the Express edition you're attempting to install:
Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8
It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.
The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
Here's what I use and will only take a few seconds to run:
ffmpeg -i input.mp4 -ss 01:19:27 -to 02:18:51 -c:v copy -c:a copy output.mp4
Reference: https://www.arj.no/2018/05/18/trimvideo
Generated mp4
files could also be used in iMovie
. More info related to get the full duration using get_duration(input_video) modele.
If you want to concatenate multiple cut scenes you can use following Python script:
#!/usr/bin/env python3
import subprocess
def get_duration(input_video):
cmd = ["ffprobe", "-i", input_video, "-show_entries", "format=duration",
"-v", "quiet", "-sexagesimal", "-of", "csv=p=0"]
return subprocess.check_output(cmd).decode("utf-8").strip()
if __name__ == "__main__":
name = "input.mkv"
times = []
times.append(["00:00:00", "00:00:10"])
times.append(["00:06:00", "00:07:00"])
# times = [["00:00:00", get_duration(name)]]
if len(times) == 1:
time = times[0]
cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", "output.mp4"]
subprocess.check_output(cmd)
else:
open('concatenate.txt', 'w').close()
for idx, time in enumerate(times):
output_filename = f"output{idx}.mp4"
cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", output_filename]
subprocess.check_output(cmd)
with open("concatenate.txt", "a") as myfile:
myfile.write(f"file {output_filename}\n")
cmd = ["ffmpeg", "-f", "concat", "-i", "concatenate.txt", "-c", "copy", "output.mp4"]
output = subprocess.check_output(cmd).decode("utf-8").strip()
Example script will cut and merge scenes in between 00:00:00 - 00:00:10
and 00:06:00 - 00:07:00
.
If you want to cut the complete video (in case if you want to convert mkv
format into mp4
) just uncomment the following line:
# times = [["00:00:00", get_duration(name)]]
A concept can be better delivered with examples, always. I had trouble in comprehending these concept until I dig into Android framework source code, and do some experiments, even after reading all documents in Android developer sites & related stackoverflow threads. I'm gonna share two examples that helped me a lot to fully understand these concepts.
A DatePickerDialog will look different based on level that you put in AndroidManifest.xml file's targetSDKversion(<uses-sdk android:targetSdkVersion="INTEGER_VALUE"/>
). If you set the value 10 or lower, your DatePickerDialog will look like left. On the other hand, if you set the value 11 or higher, a DatePickerDialog will look like right, with the very same code.
The code that I used to create this sample is super-simple. MainActivity.java
looks :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View v) {
DatePickerDialog d = new DatePickerDialog(this, null, 2014, 5, 4);
d.show();
}
}
And activity_main.xml
looks :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Button" />
</RelativeLayout>
That's it. That's really every code that I need to test this.
And this change in look is crystal clear when you see the Android framework source code. It goes like :
public DatePickerDialog(Context context,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
this(context, context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB
? com.android.internal.R.style.Theme_Holo_Light_Dialog_Alert
: com.android.internal.R.style.Theme_Dialog_Alert,
callBack, year, monthOfYear, dayOfMonth, yearOptional);
}
As you can see, the framework gets current targetSDKversion and set different theme. This kind of code snippet(getApplicationInfo().targetSdkVersion >= SOME_VERSION
) can be found here and there in Android framework.
Another example is about WebView class. Webview class's public methods should be called on main thread, and if not, runtime system throws a RuntimeException
, when you set targetSDKversion 18 or higher. This behavior can be clearly delivered with its source code. It's just written like that.
sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
Build.VERSION_CODES.JELLY_BEAN_MR2;
if (sEnforceThreadChecking) {
throw new RuntimeException(throwable);
}
The Android doc says, "As Android evolves with each new version, some behaviors and even appearances might change." So, we've looked behavior and appearance change, and how that change is accomplished.
In summary, the Android doc says "This attribute(targetSdkVersion) informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version.". This is really clear with WebView case. It was OK until JELLY_BEAN_MR2 released to call WebView class's public method on not-main thread. It is nonsense if Android framework throws a RuntimeException on JELLY_BEAN_MR2 devices. It just should not enable newly introduced behaviors for its interest, which cause fatal result. So, what we have to do is to check whether everything is OK on certain targetSDKversions. We get benefit like appearance enhancement with setting higher targetSDKversion, but it comes with responsibility.
EDIT : disclaimer. The DatePickerDialog constructor that set different themes based on current targetSDKversion(that I showed above) actually has been changed in later commit. Nevertheless I used that example, because logic has not been changed, and those code snippet clearly shows targetSDKversion concept.
If you'd like to display the full name (instead of the username), add the -F
flag:
$ id -F
Andrew Havens
I got this when installing a library using anaconda. My version went from Python 3.* to 2.7 and a lot of my stuff stopped working. The best solution I found was to first see the most recent version available:
conda search python
Then update to the version you want:
conda install python=3.*.*
Source: http://chris35wills.github.io/conda_python_version/
Other helpful commands:
conda info
python --version
A real working solution with no other dependencies than angularjs (tested with v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
As far that I know you only can get time with Date.
Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.
var currentTime = +new Date();
This gives you the current time in milliseconds.
For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).
If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.
With Chrome you can see how much time the GC is spending in the Timeline panel.
EDIT: Since my answer, Date.now()
should be considered as the best option as it is supported everywhere and on IE >= 9.
Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
var id = rec.get('id');
// some DELETE/GET ajax callback here...
// pass in 'id' var or some key
// inside success
grid.getStore().removeAt(rowIndex);
}
Use the <button>
tag instead. <button>
labels are vertically centered by default.
I had really old project on older machine. Project was building correctly when I turned off machine. Today, I am getting build error but no error message. After trying some of suggestion from above, no luck.
In Visual Studio 2015, I turned on Detailed MSBuild under TOOLS > Options > Projects and Solutions > Build and Run
It gave me few details about build but no errors. After that I tried to check Extensions and updates (Tools > Extension and Updates) and found few of them needed update.
Nuget Package was culprit, after updating Nuget - build is successful.
you have to create an entry inside res/menu,
override onCreateOptionsMenu
and inflate it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourentry, menu);
return true;
}
an entry for the menu could be:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_cart"
android:icon="@drawable/cart"
android:orderInCategory="100"
android:showAsAction="always"/>
</menu>
the return statement exits from the current function and exit() exits from the program
they are the same when used in main() function
also return is a statement while exit() is a function which requires stdlb.h header file
Let's suppose that the given integer N
is not prime,
Then N can be factorized into two factors a
and b
, 2 <= a, b < N
such that N = a*b
.
Clearly, both of them can't be greater than sqrt(N)
simultaneously.
Let us assume without loss of generality that a
is smaller.
Now, if you could not find any divisor of N
belonging in the range [2, sqrt(N)]
, what does that mean?
This means that N
does not have any divisor in [2, a]
as a <= sqrt(N)
.
Therefore, a = 1
and b = n
and hence By definition, N
is prime.
...
Further reading if you are not satisfied:
Many different combinations of (a, b)
may be possible. Let's say they are:
(a1, b1), (a2, b2), (a3, b3), ..... , (ak, bk). Without loss of generality, assume ai < bi, 1<= i <=k
.
Now, to be able to show that N
is not prime it is sufficient to show that none of ai can be factorized further. And we also know that ai <= sqrt(N)
and thus you need to check till sqrt(N)
which will cover all ai. And hence you will be able to conclude whether or not N
is prime.
...
Control Panel --> Credential Manager --> Manage Windows Credentials --> Choose the entry of the git repository, and Edit the user and password. Delete '. git/config' and try again. Attention this will may reset some git settings too!
You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.
Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.
First, define timer
decorator:
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
return value
return wrapper
Then, use the decorator while defining the function:
@timer
def doubled_and_add(num):
res = sum([i*2 for i in range(num)])
print("Result : {}".format(res))
Let's try:
doubled_and_add(100000)
doubled_and_add(1000000)
Output:
Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs
Note: I'm not sure why to use time.perf_counter
instead of time.time
. Comments are welcome.
The bot detection I've seen seems more sophisticated or at least different than what I've read through in the answers below.
EXPERIMENT 1:
EXPERIMENT 2:
As before, I open a browser and the web page with Selenium from a Python console.
This time around, instead of clicking with the mouse, I use Selenium (in the Python console) to click the same element with a random offset.
The link doesn't open, but I am taken to a sign up page.
IMPLICATIONS:
Seems mysterious, but I guess they can just determine whether an action originates from Selenium or not, while they don't care whether the browser itself was opened via Selenium or not. Or can they determine if the window has focus? Would be interesting to hear if anyone has any insights.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
See this reference
>>> orange = range(1, 1001)
>>> otuples = list( zip(*[iter(orange)]*10))
>>> print(otuples)
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ... (991, 992, 993, 994, 995, 996, 997, 998, 999, 1000)]
>>> olist = [list(i) for i in otuples]
>>> print(olist)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ..., [991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]]
>>>
Python3
Get the path of running Apache
$ ps -ef | grep apache
apache 12846 14590 0 Oct20 ? 00:00:00 /usr/sbin/apache2
Append -V
argument to the path
$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location
Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:
For 32 bit OS:Here
For 64 bit OS:Here
The API docs give some good hints:
print() ? nil
print(obj, ...) ? nil
Writes the given object(s) to ios. Returns
nil
.The stream must be opened for writing. Each given object that isn't a string will be converted by calling its
to_s
method. When called without arguments, prints the contents of$_
.If the output field separator (
$,
) is notnil
, it is inserted between objects. If the output record separator ($\
) is notnil
, it is appended to the output....
puts(obj, ...) ? nil
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns
nil
.The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its
to_s
method. If called without arguments, outputs a single newline.
Experimenting a little with the points given above, the differences seem to be:
Called with multiple arguments, print
separates them by the 'output field separator' $,
(which defaults to nothing) while puts
separates them by newlines. puts
also puts a newline after the final argument, while print
does not.
2.1.3 :001 > print 'hello', 'world'
helloworld => nil
2.1.3 :002 > puts 'hello', 'world'
hello
world
=> nil
2.1.3 :003 > $, = 'fanodd'
=> "fanodd"
2.1.3 :004 > print 'hello', 'world'
hellofanoddworld => nil
2.1.3 :005 > puts 'hello', 'world'
hello
world
=> nil
puts
automatically unpacks arrays, while print
does not:
2.1.3 :001 > print [1, [2, 3]], [4] [1, [2, 3]][4] => nil 2.1.3 :002 > puts [1, [2, 3]], [4] 1 2 3 4 => nil
print
with no arguments prints $_
(the last thing read by gets
), while puts
prints a newline:
2.1.3 :001 > gets
hello world
=> "hello world\n"
2.1.3 :002 > puts
=> nil
2.1.3 :003 > print
hello world
=> nil
print
writes the output record separator $\
after whatever it prints, while puts
ignores this variable:
mark@lunchbox:~$ irb
2.1.3 :001 > $\ = 'MOOOOOOO!'
=> "MOOOOOOO!"
2.1.3 :002 > puts "Oink! Baa! Cluck! "
Oink! Baa! Cluck!
=> nil
2.1.3 :003 > print "Oink! Baa! Cluck! "
Oink! Baa! Cluck! MOOOOOOO! => nil
I had exact the same problem! I had been searching and searching for days because all the babble about "put the -vm c:\program files\java\jdkxxxxx\bin" in the ini ar as argument for a shortcut did not at all help!
(Do I sound frustrated? Believe me, that's an understatement! I am simply furious because I lost a week trying to make Maven reliable!)
I had very unpredictable behavior. Sometimes it compiled and sometimes not. If I did a maven clean
, it could not find the compiler and failed. If I then changed something in the build path, it suddenly worked again!!
Until I went to menu Window → Preferences → Java → Installed JRE's. I added a new JRE using the location of the JDK and then removed the JRE. Suddenly Maven ran stable!
Maybe this is worth putting in letters with font-size 30 or so in the Apache manual?
With all due respect, this is simply outrageous for the Java community! I can't imagine how many days were lost by all these people, trying to work out their problems of this kind! I cannot possibly imagine this is released as a final version. I personally would not even dare to release such a thing under the name beta software...
Kind regards either way.... After a week of tampering I can finally start developing. I hope my boss won't find out about this. It took me lots of effort to convince him not to go to .NET and I already feel sorry about it.
First something I think necessary to know:
It is symbol that is transferred on a physical channel. Not bit. Symbol is the physical signals that is transferred over the physical medium to convey the data bits. A symbol can be one of several voltage, frequency, or phase changes. Symbol is decided by the physical nature of the medium. While bit is a logical concept.
If you want to transfer data bits, you must do it by sending symbols over the medium. Baud rate describes how fast symbols change over a medium. I.e. it describes the rate of physical state changes over the medium.
If we use only 2 symbols to transfer binary data, which means one symbol for 0 and another symbol for 1, that will lead to baud rate = bit rate
. And this is how it works in the old days.
If we are lucky enough to find a way to encode more bits into a symbol, we can achieve higher bit rate with the same baud rate. And this is when the baud rate < bit rate
. This doesn't mean the transfer speed is slowed down. It actually means the transfer efficiency/speed is increased.
And the communicating parties have to agree on how bits are represented by each physical symbol. This is where the modulation protocols come in.
But the ability of sending multiple bits per symbol doesn't come free. The transmitter and receiver will be complex depending on the modulation methods. And more processing power is required.
Finally, I'd like to make an analogy:
Suppose I stand on the roof of my house and you stand on your roof. There's a rope between you and me. I want to send some apples to you through a basket down the rope.
The basket is the symbol. The apple is the data bits.
If the basket is small (a physical limitation of the symbol), I may only send one apple per basket. This is when baud/basket rate = bit/apple rate.
If the basket is big, I can send more apples per basket. This is when baud rate < bit rate. I can send all the apples with less baskets. But it takes me more effort (processing power) to put more apples into the basket than put just one apple. If the basket rate remains the same, the more apples I put in one basket, the less time it takes.
Here are some related threads:
How can I be sure that a multi-bit-per-symbol encoding schema exists?
What is difference between the terms bit rate,baud rate and data rate?
Yes, you can modify state of objects inside your stream, but most often you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:
For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose
Spliterator
reports theCONCURRENT
characteristic.
So this is OK
List<User> users = getUsers();
users.stream().forEach(u -> u.setProperty(value));
// ^ ^^^^^^^^^^^^^
but this in most cases is not
users.stream().forEach(u -> users.remove(u));
//^^^^^ ^^^^^^^^^^^^
and may throw ConcurrentModificationException
or even other unexpected exceptions like NPE:
List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.forEach(i -> list.remove(i)); //throws NullPointerException
Changing my header to the following solve the problem:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
A little slower, but readable I think:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
You can also try another library - https://github.com/wikimedia/jquery.i18n .
In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.
I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet
nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
Try my generic CSS regular expression
(([a-z]{5,6}.*?\))|([\d.+-]?)(?![a-z\s#.()%])(\d?\.?\d?)?[a-z\d%]+)|(url\([/"'][a-z:/.]*['")]\))|(rgb|hsl)a?\(\d+%?,?\s?\d+%?,?\s?\d+%?(,\s?\d+\.?\d?)?\)|(#(\w|[\d]){3,8})|([\w]{3,8}(?=.*-))
Here's a working example in which the execution of the service is started in the OnTimedEvent of the Timer which is implemented as delegate in the ServiceBase class and the Timer logic is encapsulated in a method called SetupProcessingTimer():
public partial class MyServiceProject: ServiceBase
{
private Timer _timer;
public MyServiceProject()
{
InitializeComponent();
}
private void SetupProcessingTimer()
{
_timer = new Timer();
_timer.AutoReset = true;
double interval = Settings.Default.Interval;
_timer.Interval = interval * 60000;
_timer.Enabled = true;
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// begin your service work
MakeSomething();
}
protected override void OnStart(string[] args)
{
SetupProcessingTimer();
}
...
}
The Interval is defined in app.config in minutes:
<userSettings>
<MyProject.Properties.Settings>
<setting name="Interval" serializeAs="String">
<value>1</value>
</setting>
</MyProject.Properties.Settings>
</userSettings>
I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:
class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
QSize sizeHint() const { return m_pixmap.size(); }
protected:
void paintEvent( QPaintEvent* e ) {
QPainter p( this );
p.drawPixmap( 0, 0, m_pixmap );
}
};
Simply use the following:
IF((SELECT count(*) FROM table)=0)
BEGIN
....
END
In MySql,the following query shall show the total number of open connections:
show status like 'Threads_connected';
Their are two methods you can use to pass an integer. One is as shown below.
A.class
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
B.class
Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);
The other method converts the integer to a string and uses the following code.
A.class
Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);
The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.
B.class
Bundle extras = getIntent().getExtras();
String stringVariableName = extras.getString("StringVariableName");
int intVariableName = Integer.parseInt(stringVariableName);
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
@CommonsWare's answer doesn't not actually work. I found that this is working properly :
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));
I had a similar issue. Back-revving RXJS from 6.x to the latest 5.x release fixed it for Angular 5.2.x.
Open package.json.
Change "rxjs": "^6.0.0",
to "rxjs": "^5.5.10",
run npm update
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use document.referrer
.
To access the user-agent, use navigator.userAgent
.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
When you are checking if an element has or does not have a class, make sure you didn't accidentally put a dot in the class name:
<div class="className"></div>
$('div').hasClass('className');
$('div').hasClass('.className'); #will not work!!!!
After a long time of staring at my code I realized I had done this. A little typo like this took me an hour to figure out what I had done wrong. Check your code!
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
Multiply by 1.
result = 1. * a / b
or, using the float function
result = float(a) / b
df_concat = df_1.union(df_2)
The dataframes may need to have identical columns, in which case you can use withColumn()
to create normal_1
and normal_2
I have heard good things about SlowCheetah, but was unable to get it to work. I did the following: add am tag to each for a specific configuration.
Ex:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'UAT|AnyCPU'">
<OutputPath>bin\UAT\</OutputPath>
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AppConfig>App.UAT.config</AppConfig>
</PropertyGroup>
Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.
Example: http://jsfiddle.net/SHLu4/2/
It'll be something like:
<div class="container drop-shadow">
<div class="container">
<div class="row">
<div class="col-md-8">Main Area</div>
<div class="col-md-4">Side Area</div>
</div>
</div>
</div>
And your CSS:
<style>
.drop-shadow {
-webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
}
.container.drop-shadow {
padding-left:0;
padding-right:0;
}
</style>
If you have your vim compiled with +menu
, you can follow menus with the :help
of console-menu
. From there, you can navigate to Edit.Color\ Scheme
to get the same list as with in gvim
.
Other method is to use a cool script ScrollColors that previews the colorschemes while you scroll the schemes with j/k
.
package com.test;
import java.util.Arrays;
public class Person implements Comparable {
private int age;
private Person(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
Person other = (Person)o;
if (this == other)
return 0;
if (this.age < other.age) return 1;
else if (this.age == other.age) return 0;
else return -1;
}
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(50);
arr[1] = new Person(20);
arr[2] = new Person(10);
arr[3] = new Person(90);
Arrays.sort(arr);
for (int i=0; i < arr.length; i++ ) {
System.out.println(arr[i].age);
}
}
}
Here is one way of doing it.
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Had the same problem. I apparently wrote the Main wrong:
public static void main(String[] args){
I missed the []
and that was the whole problem.
Check and recheck the Main function!
The Connection String Which We Are Assigning from server side will be same as that From Web config File. The Catalog: Means To Database it is followed by Username and Password And DataClient The New sql connection establishes The connection to sql server by using the credentials in the connection string.. Then it is followed by sql command which retrives the required data in the dataset and then we assing them to required variables or controls to get the required task done
myString += Environment.NewLine;
myString = myString + Environment.NewLine;
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
You can wrap your input field into a span, which you position:relative;
. Then you add with
:before
content:"€"
your currency symbol and make it position:absolute
. Working JSFiddle
HTML
<span class="input-symbol-euro">
<input type="text" />
</span>
CSS
.input-symbol-euro {
position: relative;
}
.input-symbol-euro input {
padding-left:18px;
}
.input-symbol-euro:before {
position: absolute;
top: 0;
content:"€";
left: 5px;
}
Update If you want to put the euro symbol either on the left or the right side of the text box. Working JSFiddle
HTML
<span class="input-euro left">
<input type="text" />
</span>
<span class="input-euro right">
<input type="text" />
</span>
CSS
.input-euro {
position: relative;
}
.input-euro.left input {
padding-left:18px;
}
.input-euro.right input {
padding-right:18px;
text-align:end;
}
.input-euro:before {
position: absolute;
top: 0;
content:"€";
}
.input-euro.left:before {
left: 5px;
}
.input-euro.right:before {
right: 5px;
}
Following is the code to get the list of activities/applications installed on Android :
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
You will get all the necessary data in the ResolveInfo
to start a application. You can check ResolveInfo
javadoc here.
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public
, private
or protected
).
A work around would be to define your constant as private
or protected
and then make them readable via a static function
. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.
Credits: http://dwellupper.io/post/48/defining-class-constants-in-php
from sklearn.linear_model import LinearRegression
X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )
I ran into this problem today. Based on the solutions above, this worked for me:
<div style="width:100%;">
<div style="float:left;">Content left div</div>
<div style="float:right;">Content right div</div>
</div>
Simply make the parent div span the full width and float the divs contained within.
Below code is for getting data from online server using GET method and okHTTP library for android kotlin...
Log.e("Main",response.body!!.string())
in above line !! is the thing using which you can get the json from response body
val client = OkHttpClient()
val request: Request = Request.Builder()
.get()
.url("http://172.16.10.126:8789/test/path/jsonpage")
.addHeader("", "")
.addHeader("", "")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle this
Log.e("Main","Try again latter!!!")
}
override fun onResponse(call: Call, response: Response) {
// Handle this
Log.e("Main",response.body!!.string())
}
})
You need to actually request the Location permission at runtime (notice the comments in your code stating this).
Here is tested and working code to request the Location permission.
Be sure to import android.Manifest
:
import android.Manifest;
Then put this code in the Activity:
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
Then call the checkLocationPermission()
method in onCreate()
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//.........
checkLocationPermission();
}
You can then use onResume()
and onPause()
exactly as it is in the question.
Here is a condensed version that is a bit more clean:
@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
}
@Override
protected void onPause() {
super.onPause();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(this);
}
}
so the .animate method works only if you have given a position attribute to an element, if not it didn't move?
for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;
A POST with httpClient in Angular 6 was also doing an OPTIONS request:
Headers General:
Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData Request Method:OPTIONS Status Code:200 OK Remote Address:127.0.0.1:443 Referrer Policy:no-referrer-when-downgrade
My Perl REST server implements the OPTIONS request with return code 200.
The next POST request Header:
Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Connection:keep-alive Host:hp-probook Origin:http://localhost:4200 Referer:http://localhost:4200/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Notice Access-Control-Request-Headers:content-type.
So, my backend perl script uses the following headers:
-"Access-Control-Allow-Origin" => '*', -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS', -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',
With this setup the GET and POST worked for me!
zIndex
is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index
.
you forgot .css("attr","value"). use ' or " in both, attr and val. so,
.css("z-index","3000");
It's not an NPP solution, but in a pinch, you can use this online JSON Formatter and then just paste the formatted text into NPP and then select Javascript as the language.
I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException
Slightly off topic, but have you considered Windows Scripting Host? You might find it nicer.
Simplest example:
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<ul>_x000D_
<li class="test">Coffee</li>_x000D_
<li class="test">Milk</li>_x000D_
<li class="test">Soda</li>_x000D_
</ul>_x000D_
_x000D_
</body> _x000D_
</html>
_x000D_
This mistake i was doing is i was passing the whole url in domain attribute, it should be only domain name.
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF
then the largest number you could represent would be 99999.99999
and the smallest non-zero number would be 00000.00001
. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.
A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50
and a smallest non-zero value of 0.0000001e-49
.
I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t
option for mv
, so I had to find another solution.
However the following command succeeded:
find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;
The secret was to quote the braces. No need for the braces to be at the end of the exec
command.
I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.
However, when using the +
sign, it seems indeed that it has to be at the end of the exec
command.
Advantages:
allows you to use multiple versions of Node and without sudo
is analogous to Ruby RVM and Python Virtualenv, widely considered best practice in Ruby and Python communities
downloads a pre-compiled binary where possible, and if not it downloads the source and compiles one for you
Tested in Ubuntu 17.10:
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | sh
source ~/.nvm/nvm.sh
nvm install 0.9.0
nvm install 0.9.9
nvm use 0.9.0
node --version
#v0.9.0
nvm use 0.9.9
node --version
#v0.9.9
For the particular case of the most recent long term support version (recommended if you can choose):
nvm install --lts
nvm use --lts
npm --version
npm install --global vaca
vaca
Since the sourcing has to be done for every new shell, the install script hacks adds some auto sourcing to the end of your .barshrc
. That works, but I prefer to remove the auto-added one and add my own:
f="$HOME/.nvm/nvm.sh"
if [ -r "$f" ]; then
. "$f" &>'/dev/null'
nvm use --lts &>'/dev/null'
fi
With this setup, you get for example:
which node
gives:
/home/ciro/.nvm/versions/node/v0.9.0/bin/node
and:
which vaca
gives:
/home/ciro/.nvm/versions/node/v0.9.0/bin/vaca
and if we want to use the globally installed module:
npm link vaca
node -e 'console.log(require.resolve("vaca"))'
gives:
/home/ciro/.nvm/versions/node/v0.9.0/lib/node_modules/vaca/index.js
so we see that everything is completely contained inside the specific node version.
To get all the columns in your result you need to place something as:
SELECT distinct a, Table.* FROM Table
it will place a as the first column and the rest will be ALL of the columns in the same order as your definition. This is, column a will be repeated.
When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:
if [[ $gg == ????grid* ]] ; then echo $gg; fi
When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*
" represents zero or more of any character, "a*
" represents zero or more "a", "[0-9]*
" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+
" represents one or more lowercase alpha character (in the C locale - and some others).
if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi
Just for the record: for me it turned out that it was the gem called 'mysql' ... obviously this is working with US-ASCII 8 bit by default. So changing it to the gem called mysql2 (the 2 is the important point here) solved all of my issues.
I looked @ the gem list posted above - Michael Koper has obviously mysql2 installed but I posted this in case someone has this issue as well .. (took me some time to figure out).
If you dislike this answer please comment and I will delete it.
P.S: German umlauts (ä,ö and ü) screwed it out with mysql
You have to distinct sub routines and functions in vba... Generally (as far as I know), sub routines do not return anything and the surrounding parantheses are optional. For functions, you need to write the parantheses.
As for your example, MsgBox is not a function but a sub routine and therefore the parantheses are optional in that case. One exception with functions is, when you do not assign the returned value, or when the function does not consume a parameter, you can leave away the parantheses too.
This answer goes into a bit more detail, but basically you should be on the save side, when you provide parantheses for functions and leave them away for sub routines.
I had this same problem a week ago.
First of all I noticed your URL has an ampersand preceding the parameter string, but it probably needs to have a question mark instead to begin the parameter string, followed by an ampersand between each additional parameter.
Now, you do need to escape your URL but also double-escape the URL parameters (title or other content you need to provide content in the Share) you are passing to the URL, as follows:
var myParams = 't=' + escape('Some title here.') + '&id=' + escape('some content ID or any other value I want to load');
var fooBar = 'http://www.facebook.com/share.php?u=' + escape('http://foobar.com/superDuperSharingPage.php?' + myParams);
Now, you need to create the above-linked superDuperSharingPage.php, which should provide the dynamic title, description, and image content you desire. Something like this should suffice:
<?php
// get our URL query parameters
$title = $_GET['t'];
$id = $_GET['id'];
// maybe we want to load some content with the id I'll pretend we loaded a
// description from some database in the sky which is magically arranged thusly:
$desciption = $databaseInTheSky[$id]['description'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $title;?></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="title" content="<?php echo $title;?>" />
<meta name="description" content="<?php echo $desciption;?>" />
<!-- the following line redirects to wherever we want the USER to land -->
<!-- Facebook won't follow it. you may or may not actually want || need this. -->
<meta http-equiv="refresh" content="1;URL=http://foobar.com" />
</head>
<body>
<p><?php echo $desciption;?></p>
<p><img src="image_a_<?php echo $id;?>.jpg" alt="Alt tags are always a good idea." /></p>
<p><img src="image_b_<?php echo $id;?>.jpg" alt="Make the web more accessible to the blind!" /></p>
</body>
</html>
Let me know if this works for you, it's essentially what did for me :)
With the Netbeans 10, commenting out the netbeans_jdkhome
setting in .../etc/netbeans.conf
doesn't do the job anymore. It is necessary to specify the right directory depending of 32/64 bitness.
E.g. for 64 bit application: netbeans_jdkhome="C:\Program Files\AdoptOpenJDK\jdk8u202-b08"
https://pypi.org/project/pdf2tiff/
You could also use pdf2ps, ps2image and then convert from the resulting image to tiff with other utilities (I remember 'paul' [paul - Yet another image viewer (displays PNG, TIFF, GIF, JPG, etc.])
format: 'YYYY-MM-DD HH:mm:ss',
The API changed since this commit, using version 1.4.1 it's now
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
JavaScript Sound Manager:
Besides all the other reasons, UDP can use multicast. Supporting 1000s of TCP users all transmitting the same data wastes bandwidth. However, there is another important reason for using TCP.
TCP can much more easily pass through firewalls and NATs. Depending on your NAT and operator, you may not even be able to receive a UDP stream due to problems with UDP hole punching.
You should also be able to use..
swfobject.getFlashPlayerVersion().major === 0
with the swfobject-Plugin.
In Swift:
For example, name of your custom class is InfoView
At first, you create files InfoView.xib
and InfoView.swift
like this:
import Foundation
import UIKit
class InfoView: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}
Then set File's Owner
to UIViewController
like this:
Rename your View
to InfoView
:
Right-click to File's Owner
and connect your view
field with your InfoView
:
Make sure that class name is InfoView
:
And after this you can add the action to button in your custom class without any problem:
And usage of this custom class in your MainViewController
:
func someMethod() {
var v = InfoView.instanceFromNib()
v.frame = self.view.bounds
self.view.addSubview(v)
}
I spent 8 hours to do that. It is simple...
You shoud have a code like that:
private const int GENERIC_WRITE = 0x40000000;
//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;
Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.
Right click on the database name, click on Property to get property window, Open the Options tab and change the "Restrict Access" property from Multi User to Single User. When you hit on OK button, it will prompt you to closes all open connection, select "Yes" and you are set to rename the database....
I had to use both:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:[NSDictionary
dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil]
forState:UIControlStateNormal];
[[self.navigationController.navigationBar.subviews lastObject] setTintColor:[UIColor whiteColor]];
And works for me, thank you for everyone!
As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.
int main(){
std::thread t(thread,1);
while(1){}
//t.detach();
return 0;}
It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.
Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.
void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}
int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);
t.detach();
t2.detach();
t3.detach();
return 0;}
An excellent and very fast file search utility, Agent Ransack, supports regular expression searching. It's primarily a GUI utility, but a command-line interface is also available.
There is no such thing. You'll have to either write a loop using printf
or puts
, or write a function that copies the string count times into a new string.
It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval()
it to turn it into executable code. I have found eval()
in this particular situation the exact opposite of evil.
Basically from
<div>
{{#each names}}
<span>{{this}}</span>
{{/each}}
</div>
To this
(function (state) {
var Runtime = Hyperbars.Runtime;
var context = state;
return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
return [h('span', {}, [options['@index'], context])]
})])
}.bind({}))
The performance of eval()
isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.
You can see how the code generation was achieved if you're curious here.
So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.
find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.
If it's a problem with the not selector, you can set all of them and override the last one
li:after
{
content: ' |';
}
li:last-child:after
{
content: '';
}
or if you can use before, no need for last-child
li+li:before
{
content: '| ';
}
You can Use <ng-container>
and <ng-template>
for Achieve This
<ng-container *ngIf="isValid; then template1 else template2"></ng-container>
<ng-template #template1>
<div>Template 1 contains</div>
</ng-template>
<ng-template #template2>
<div>Template 2 contains </div>
</ng-template>
You can find the Stackblitz Live demo below
Hope This will helps ... !!!
SELECT
AGE('2012-03-05', '2010-04-01'),
DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;
This will give you full years, month, days ... between two dates:
age | years | months | days
-----------------------+-------+--------+------
1 year 11 mons 4 days | 1 | 11 | 4
More detailed datediff information.
A general purpose image rotation, position, and scale.
// no need to use save and restore between calls as it sets the transform rather
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
ctx.rotate(rotation);
ctx.drawImage(image, -image.width / 2, -image.height / 2);
}
If you wish to control the rotation point use the next function
// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
ctx.rotate(rotation);
ctx.drawImage(image, -cx, -cy);
}
To reset the 2D context transform
ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore
Thus to rotate image to the left (anti clockwise) 90 deg
drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);
Thus to rotate image to the right (clockwise) 90 deg
drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);
var image = new Image;_x000D_
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";_x000D_
var canvas = document.createElement("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.top = "0px";_x000D_
canvas.style.left = "0px";_x000D_
document.body.appendChild(canvas);_x000D_
var w,h;_x000D_
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}_x000D_
resize();_x000D_
window.addEventListener("resize",resize);_x000D_
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }_x000D_
function DO(count,callback){ while (count--) { callback(count) } }_x000D_
const sprites = [];_x000D_
DO(500,()=>{_x000D_
sprites.push({_x000D_
x : rand(w), y : rand(h),_x000D_
xr : 0, yr : 0, // actual position of sprite_x000D_
r : rand(Math.PI * 2),_x000D_
scale : rand(0.1,0.25),_x000D_
dx : rand(-2,2), dy : rand(-2,2),_x000D_
dr : rand(-0.2,0.2),_x000D_
});_x000D_
});_x000D_
function drawImage(image, spr){_x000D_
ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin_x000D_
ctx.rotate(spr.r);_x000D_
ctx.drawImage(image, -image.width / 2, -image.height / 2);_x000D_
}_x000D_
function update(){_x000D_
var ihM,iwM;_x000D_
ctx.setTransform(1,0,0,1,0,0);_x000D_
ctx.clearRect(0,0,w,h);_x000D_
if(image.complete){_x000D_
var iw = image.width;_x000D_
var ih = image.height;_x000D_
for(var i = 0; i < sprites.length; i ++){_x000D_
var spr = sprites[i];_x000D_
spr.x += spr.dx;_x000D_
spr.y += spr.dy;_x000D_
spr.r += spr.dr;_x000D_
iwM = iw * spr.scale * 2 + w;_x000D_
ihM = ih * spr.scale * 2 + h;_x000D_
spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;_x000D_
spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;_x000D_
drawImage(image,spr);_x000D_
}_x000D_
} _x000D_
requestAnimationFrame(update);_x000D_
}_x000D_
requestAnimationFrame(update);
_x000D_
I had the same problem and i fixed it by checking what version pip (pip3 --version
) is, then realizing I'm typing python<uncorrect version> filename.py
instead of python<correct version> filename.py
The answer provided by Heiberg works really well, however the page control does not behave exactly like the one by apple.
If you want the page control to behave like the one from apple does (always increment the current page by one if you touch the second half, otherwise decrease by one), try this touchesBegan-method instead:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
CGRect currentBounds = self.bounds;
CGFloat x = touchPoint.x - CGRectGetMidX(currentBounds);
if(x<0 && self.currentPage>=0){
self.currentPage--;
[self.delegate pageControlPageDidChange:self];
}
else if(x>0 && self.currentPage<self.numberOfPages-1){
self.currentPage++;
[self.delegate pageControlPageDidChange:self];
}
}
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
you can use inner join :
DELETE
ps
FROM
posts ps INNER JOIN
(SELECT
distinct id
FROM
posts
GROUP BY id
HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id
URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".
RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).
In Java, the correct way to build a URL is with the URI
class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString()
method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI
object using the single-string constructor and then use the accessor methods (such as getPath()
) to retrieve the decoded components.
Don't use the URLEncoder
class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder
. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).
check if the app is in background or foreground. This method will return true if the app is in background.
First add the GET_TASKS permission to your AndroidManifest.xml
private boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime
and strftime
behavior to better understand how python processes dates and time field
run command prompt as administrator and use '--user' flag eg. pip install --user --upgrade pandas
I use:
npx jetifier
this fix the problem.
ref: Cannot build Ionic App on Android once installed BackgroundGeolocation Plugin with Capacitor
I managed to allow all my requisite sites with this header:
header("Content-Security-Policy: default-src *; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' stackexchange.com");
Imagine this scenario
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important
makes such situations easier to deal with.
Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...
I suppose you got the idea by now and can come up with some others as well.
!important
?I suggest you don't use !important
unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important
styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.
CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new
keywords has a simple answer: Yes. I'll illustrate...
You can either use the exports
variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require()
is a reference to the value of module.exports
.
A pseudo-code example of how a module is defined:
var theModule = {
exports: {}
};
(function(module, exports, require) {
// Your module code goes here
})(theModule, theModule.exports, theRequireFunction);
In the example above module.exports
and exports
are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.
Since you can attach a function directly to module.exports
you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)
So the following is perfectly good code and I personally encourage it:
// My module
function MyObject(bar) {
this.bar = bar;
}
MyObject.prototype.foo = function foo() {
console.log(this.bar);
};
module.exports = MyObject;
// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"
Same thing goes for non-constructor like functions:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
#each
#each
runs a function for each element in an array. The following two code excerpts are equivalent:
x = 10
["zero", "one", "two"].each{|element|
x++
puts element
}
x = 10
array = ["zero", "one", "two"]
for i in 0..2
x++
puts array[i]
end
#map
#map
applies a function to each element of an array, returning the resulting array. The following are equivalent:
array = ["zero", "one", "two"]
newArray = array.map{|element| element.capitalize()}
array = ["zero", "one", "two"]
newArray = []
array.each{|element|
newArray << element.capitalize()
}
#map!
#map!
is like #map
, but modifies the array in place. The following are equivalent:
array = ["zero", "one", "two"]
array.map!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array = array.map{|element| element.capitalize()}
Angular v2 doesn't support more than one structural directive on the same element.
As a workaround use the <ng-container>
element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.
<ng-container *ngIf="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-container>
<ng-template>
(<template>
before Angular v4) allows to do the same but with a different syntax which is confusing and no longer recommended
<ng-template [ngIf]="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-template>
Use the span
tag
<style>
.redText
{
color:red;
}
.blackText
{
color:black;
font-weight:bold;
}
</style>
<span class="redText">My Name is:</span> <span class="blackText">Tintincute</span>
It's also a good idea to avoid inline styling. Use a custom CSS class instead.
I've always had luck with the Chr(10) & Chr(13) - I have provided a sample below. This is an expression for an address text box I have in a report.
=Iif(Fields!GUAR_STREET_2.Value <> "",Fields!GUAR_STREET.Value & Chr(10) & Chr(13) & LTrim(Fields!GUAR_STREET_2.Value),Fields!GUAR_STREET.Value)
Also, if you are building a string you need to concatenate stuff together with an & not a + Here is what I think your example should look like
=IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though."
, "This is the second huge paragraph of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though." )
From the Javadoc:
Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a
public static void
no-arg method with@BeforeClass
causes it to be run once before any of the test methods in the class. The@BeforeClass
methods of superclasses will be run before those the current class.
I use Butterknife with switch-case to handle this kind of cases:
@OnClick({R.id.button_bireysel, R.id.button_kurumsal})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button_bireysel:
//Do something
break;
case R.id.button_kurumsal:
//Do something
break;
}
}
But the thing is there is no default case and switch statement falls through
You are declaring button1 in main method so you can not access it in actionPerform. You should make it global in class.
JButton button1;
public static void main(String[] args) {
JFrame calcFrame = new JFrame();
calcFrame.setSize(100, 100);
calcFrame.setVisible(true);
button1 = new JButton("1");
button1.addActionListener(this);
calcFrame.add(button1);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
}
NOTE: while using adb on Linux you'll need to type ./adb to execute adb commands unless you create a path in ~/.bashrc. In a terminal write:
sudo gedit ~/.bashrc
Add the following line at the end of the file. Once you're done, save and exit.
export PATH=~/Development/adt-bundle-linux/sdk/platform-tools:~/Development/adt-bundle-linux/sdk/tools:$PATH
Then in a Terminal run this command to reload your .bashrc: Code:
source ~/.bashrc
Now you can just run adb without put ./ before every command.
It usually is the directory from which the batch file is started, but if you start the batch file from a shortcut, a different starting directory could be given. Also, when you'r in cmd, and your current directory is c:\dir3
, you can still start the batch file using c:\dir1\dir2\batch.bat
in which case, the current directory will be c:\dir3
.
^[0-9]([.,][0-9]{1,3})?$
It allows:
0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234
BUT NOT:
.1
,1
12.1
12,1
1.
1,
1.2345
1,2345