Programs & Examples On #Asp.net mvc

The ASP.NET MVC Framework is an open source web application framework and tooling that implements a version of the model-view-controller (MVC) pattern tailored towards web applications and built upon an ASP.NET technology foundation.

How to Call Controller Actions using JQuery in ASP.NET MVC

You can start reading from here jQuery.ajax()

Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.

$.ajax({
    // edit to add steve's suggestion.
    //url: "/ControllerName/ActionName",
    url: '<%= Url.Action("ActionName", "ControllerName") %>',
    success: function(data) {
         // your data could be a View or Json or what ever you returned in your action method 
         // parse your data here
         alert(data);
    }
});

More examples can be found in here

Html.EditorFor Set Default Value

Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Redirect From Action Filter Attribute

It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute. If so, you should make sure that you inherit that, and not ActionFilterAttribute, in order to let ASP.NET MVC do more of the work for you.

Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Do whatever checking you need here

        // If you want the base check as well (against users/roles) call
        base.OnAuthorization(filterContext);
    }
}

There is a good question with an answer with more details here on SO.

Int or Number DataType for DataAnnotation validation attribute

public class IsNumericAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            decimal val;
            var isNumeric = decimal.TryParse(value.ToString(), out val);

            if (!isNumeric)
            {                   
                return new ValidationResult("Must be numeric");                    
            }
        }

        return ValidationResult.Success;
    }
}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

In my case it was not working because of the return.

Instead of using:

return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });

I used:

return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });

It´s a Model, so it is obvius that ModelState.AddModelError("keyName","Message"); must work with a model.

This answer show why. Adding validation with DataAnnotations

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

How to pass Multiple Parameters from ajax call to MVC Controller

function final_submit1() {
    var city = $("#city").val();
    var airport = $("#airport").val();

    var vehicle = $("#vehicle").val();

    if(city && airport){
    $.ajax({
        type:"POST",
        cache:false,
        data:{"city": city,"airport": airport},
        url:'http://airportLimo/ajax-car-list', 
        success: function (html) {
             console.log(html);
          //$('#add').val('data sent');
          //$('#msg').html(html);
           $('#pprice').html("Price: $"+html);
        }
      });

    }  
}

Calling @Html.Partial to display a partial view belonging to a different controller

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.

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.

So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.

How can I get the client's IP address in ASP.NET MVC?

How I account for my site being behind an Amazon AWS Elastic Load Balancer (ELB):

public class GetPublicIp {

    /// <summary>
    /// account for possbility of ELB sheilding the public IP address
    /// </summary>
    /// <returns></returns>
    public static string Execute() {
        try {
            Console.WriteLine(string.Join("|", new List<object> {
                    HttpContext.Current.Request.UserHostAddress,
                    HttpContext.Current.Request.Headers["X-Forwarded-For"],
                    HttpContext.Current.Request.Headers["REMOTE_ADDR"]
                })
            );

            var ip = HttpContext.Current.Request.UserHostAddress;
            if (HttpContext.Current.Request.Headers["X-Forwarded-For"] != null) {
                ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
                Console.WriteLine(ip + "|X-Forwarded-For");
            }
            else if (HttpContext.Current.Request.Headers["REMOTE_ADDR"] != null) {
                ip = HttpContext.Current.Request.Headers["REMOTE_ADDR"];
                Console.WriteLine(ip + "|REMOTE_ADDR");
            }
            return ip;
        }
        catch (Exception ex) {
            Console.Error.WriteLine(ex.Message);
        }
        return null;
    }
}

How to pass multiple parameters from ajax to mvc controller?

function toggleCheck(employeeId) {
    var data =  'referenceid= '+ employeeId +'&referencestatus=' 1;
    console.log(data);
    $.ajax({
        type : 'POST',
        url : 'edit',
        data : data,
        cache: false,
        async : false,
        success : function(employeeId) {
            alert("Success");
            window.redirect = "Users.jsp";
        }
    });

}

Change selected value of kendo ui dropdownlist

Seems there's an easier way, at least in Kendo UI v2015.2.624:

$('#myDropDownSelector').data('kendoDropDownList').search('Text value to find');

If there's not a match in the dropdown, Kendo appears to set the dropdown to an unselected value, which makes sense.


I couldn't get @Gang's answer to work, but if you swap his value with search, as above, we're golden.

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

Razor-based view doesn't see referenced assemblies

well, for me it was different. I was missing assembly of my console application project with MVC project. So, adding reference was not enough.

well this might help someone else. go to root web.config file system.web -> compilation -> add your project reference like this.

<assemblies> <add assembly="Your.Namespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> </assemblies>

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

The absolute easiest way to stream a file into browser using ASP.NET MVC is this:

public ActionResult DownloadFile() {
    return File(@"c:\path\to\somefile.pdf", "application/pdf", "Your Filename.pdf");
}

This is easier than the method suggested by @azarc3 since you don't even need to read the bytes.

Credit goes to: http://prideparrot.com/blog/archive/2012/8/uploading_and_returning_files#how_to_return_a_file_as_response

** Edit **

Apparently my 'answer' is the same as the OP's question. But I am not facing the problem he is having. Probably this was an issue with older version of ASP.NET MVC?

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

ASP.NET MVC Razor render without encoding

In case of ActionLink, it generally uses HttpUtility.Encode on the link text. In that case you can use HttpUtility.HtmlDecode(myString) it worked for me when using HtmlActionLink to decode the string that I wanted to pass. eg:

  @Html.ActionLink(HttpUtility.HtmlDecode("myString","ActionName",..)

Add CSS or JavaScript files to layout head from views or partial views

I tried to solve this issue.

My answer is here.

"DynamicHeader" - http://dynamicheader.codeplex.com/, https://nuget.org/packages/DynamicHeader

For example, _Layout.cshtml is:

<head>
@Html.DynamicHeader()
</head>
...

And, you can register .js and .css files to "DynamicHeader" anywhere you want.

For example, the code block in AnotherPartial.cshtml is:

@{
  DynamicHeader.AddSyleSheet("~/Content/themes/base/AnotherPartial.css");
  DynamicHeader.AddScript("~/some/myscript.js");
}

Result HTML output for this sample is:

<html>
  <link href="/myapp/Content/themes/base/AnotherPartial.css" .../>
  <script src="/myapp/some/myscript.js" ...></script>
</html>
...

How to use a ViewBag to create a dropdownlist?

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

ASP.NET MVC Conditional validation

I'm using MVC 5 but you could try something like this:

public DateTime JobStart { get; set; }

[AssertThat("StartDate >= JobStart", ErrorMessage = "Time Manager may not begin before job start date")]
[DisplayName("Start Date")]
[Required]
public DateTime? StartDate { get; set; }

In your case you would say something like "IsSenior == true". Then you just need to check the validation on your post action.

ASP.NET MVC ActionLink and post method

This is taken from the MVC sample project

@if (ViewBag.ShowRemoveButton)
      {
         using (Html.BeginForm("RemoveLogin", "Manage"))
           {
              @Html.AntiForgeryToken()
                  <div>
                     @Html.Hidden("company_name", account)
                     @Html.Hidden("returnUrl", Model.returnUrl)
                     <input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
                  </div>
            }
        }

The type or namespace name 'DbContext' could not be found

You need to reference the System.Data.Entity assembly in your project, or install the EntityFramework NuGet package, which will setup everything for you.

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

MVC - Set selected value of SelectList

Use LINQ and add the condition on the "selected" as a question mark condition.

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;

Redirect to external URI from ASP.NET MVC controller

Maybe the solution someone is looking for is this:

Response.Redirect("/Sucesso")

This work when used in the View as well.

How ViewBag in ASP.NET MVC works

ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData. ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.

e.g: 1. Creating ViewBag: ViewBag.FirstName="John";

  1. Accessing View: @ViewBag.FirstName.

Where will log4net create this log file?

FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
    logger.DebugFormat("log file located at : {0}", appender.File);
else
    logger.Error("Could not locate fileAppender");

Biggest advantage to using ASP.Net MVC vs web forms

Modern javascript controls as well as JSON requests can be handled much easily using MVC. There we can use a lot of other mechanisms to post data from one action to another action. That's why we prefer MVC over web forms. Also we can build light weight pages.

Application_Start not firing?

I have just the same problem. I have made a lot of renaming in my solution. After it I got two not working web-applications and several another web-applications were all right. I got error that I have wrong routes. When I have tried to setup break point in Application_Start method, and then restart IIS, VS didn't break execution. With workable web-applications break was working. Then I have recalled that "clean solution" and "rebuild" doesn't delete assemblies that left after renaming. And that was solution! I have manually cleaned bin directories of my buggy-web-applications and then saw new error in Global.asax Inherits="" attribute was referenced old dll. I have changed it on new and break began to work. Suppose that, during renaming Global.asax wasn't updated, and IIS took old assembly (with wrong routes) to start application.

displayname attribute vs display attribute

DisplayName sets the DisplayName in the model metadata. For example:

[DisplayName("foo")]
public string MyProperty { get; set; }

and if you use in your view the following:

@Html.LabelFor(x => x.MyProperty)

it would generate:

<label for="MyProperty">foo</label>

Display does the same, but also allows you to set other metadata properties such as Name, Description, ...

Brad Wilson has a nice blog post covering those attributes.

Writing/outputting HTML strings unescaped

Supposing your content is inside a string named mystring...

You can use:

@Html.Raw(mystring)

Alternatively you can convert your string to HtmlString or any other type that implements IHtmlString in model or directly inline and use regular @:

@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString

How to get 'System.Web.Http, Version=5.2.3.0?

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Then in the project Add Reference -> Browse. Push the browse button and go to the C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file

How can I pass parameters to a partial view in mvc 4

One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.

In your Partial calling side

@Html.Partial("ParitalAction", "String data to pass to partial")

And then binding the model with Partial View like this

@model string

and the using its value in Partial View like this

@Model

You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.

Hope it helps,

Why is my CSS bundling not working with a bin deployed MVC4 app?

This solved my issue. I have added these lines in _layout.cshtml

@*@Scripts.Render("~/bundles/plugins")*@
<script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Kendo JS -->
<script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="/Content/plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="/Content/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="/Content/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="/Content/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/Content/dist/js/demo.js"></script>
<!-- Common -->
<script src="/Scripts/common/common.js"></script>
<!-- Render Sections -->

Html attributes for EditorFor() in ASP.NET MVC

Now ASP.Net MVC 5.1 got a built in support for it.

From Release Notes

We now allow passing in HTML attributes in EditorFor as an anonymous object.

For example:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

Where can I find a list of escape characters required for my JSON ajax return type?

From the spec:

All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F

Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007.

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

How do I pass a datetime value as a URI parameter in asp.net mvc?

I have the same problem. I use DateTime.Parse Method. and in the URL use this format to pass my DateTime parameter 2018-08-18T07:22:16

for more information about using DateTime Parse method refer to this link : DateTime Parse Method

string StringDateToDateTime(string date)
    {
        DateTime dateFormat = DateTime.Parse(date);
        return dateFormat ;
    }

I hope this link helps you.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:

protected void Application_Error(object sender, EventArgs e) {
  Exception exception = Server.GetLastError();
  Response.Clear();

  HttpException httpException = exception as HttpException;

  if (httpException != null) {
    string action;

    switch (httpException.GetHttpCode()) {
      case 404:
        // page not found
        action = "HttpError404";
        break;
      case 500:
        // server error
        action = "HttpError500";
        break;
      default:
        action = "General";
        break;
      }

      // clear error on server
      Server.ClearError();

      Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
    }

Then your controller will receive whatever you want:

// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
   return View("SomeView", message);
}

There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

Turns out this was a problem, because the ASP.NET MVC 4 project was referencing a specific version of the Microsoft.Net.Compilers package. Visual Studio was using the compiler from this specific package, and not the compiler that was installed otherwise on the computer.

A warning or something would have been nice from VS2019 :-)

The solution then is to update the Microsoft.Net.Compilers package to a newer version.

Version 1.x is for C# 6 Version 2.x is for C# 7 Version 3.x is for C# 8 How I got to solve this was not immediately obvious. Visual Studio could have suggested or hinted that by me selecting a new version in the project settings that setting now conflicted with the package installed into the project.

(I ended up turning on Diagnostics level MSBuild logging to find out which CSC.EXE the IDE is really trying to use)

https://developercommunity.visualstudio.com/content/problem/519531/c-7x-versions-do-not-seem-to-work-in-vs2019.html

How do you create a dropdownlist from an enum in ASP.NET MVC?

I am very late on this one but I just found a really cool way to do this with one line of code, if you are happy to add the Unconstrained Melody NuGet package (a nice, small library from Jon Skeet).

This solution is better because:

  1. It ensures (with generic type constraints) that the value really is an enum value (due to Unconstrained Melody)
  2. It avoids unnecessary boxing (due to Unconstrained Melody)
  3. It caches all the descriptions to avoid using reflection on every call (due to Unconstrained Melody)
  4. It is less code than the other solutions!

So, here are the steps to get this working:

  1. In Package Manager Console, "Install-Package UnconstrainedMelody"
  2. Add a property on your model like so:

    //Replace "YourEnum" with the type of your enum
    public IEnumerable<SelectListItem> AllItems
    {
        get
        {
            return Enums.GetValues<YourEnum>().Select(enumValue => new SelectListItem { Value = enumValue.ToString(), Text = enumValue.GetDescription() });
        }
    }
    

Now that you have the List of SelectListItem exposed on your model, you can use the @Html.DropDownList or @Html.DropDownListFor using this property as the source.

System.web.mvc missing

Add the reference again from ./packages/Microsoft.AspNet.Mvc.[version]/lib/net45/System.Web.Mvc.dll

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

In ASP.NET MVC 5 you could use the [DataType(DataType.MultilineText)] attribute. It will render a TextArea tag.

public class MyModel
{
    [DataType(DataType.MultilineText)]
    public string MyField { get; set; }
}

Then in the view if you need to specify the rows you can do it like this:

@Html.EditorFor(model => model.MyField, new { htmlAttributes = new { rows = 10 } })

Or just use the TextAreaFor with the right overload:

@Html.TextAreaFor(model => model.MyField, 10, 20, null)

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

You could also use the RenderView Controller extension from here (source)

and use it like this:

public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}

it works for razor and web-forms viewengines

Updating user data - ASP.NET Identity

I also had problems using UpdateAsync when developing a version of SimpleSecurity that uses ASP.NET Identity. For example, I added a feature to do a password reset that needed to add a password reset token to the user information. At first I tried using UpdateAsync and it got the same results as you did. I ended up wrapping the user entity in a repository pattern and got it to work. You can look at the SimpleSecurity project for an example. After working with ASP.NET Identity more (documentation is still non-existent) I think that UpdateAsync just commits the update to the context, you still need to save the context for it to commit to the database.

POST string to ASP.NET Web Api application - returns null

([FromBody] IDictionary<string,object> data)

Pass Model To Controller using Jquery/Ajax

As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize() e.g.

$('#myform').on('submit', function(e){
    e.preventDefault();

    var formData = $(this).serialize();

    $.post('/student/update', formData, function(response){
         //Do something with response
    });
});

So your controller could have a view model as the param e.g.

 [HttpPost]
 public JsonResult Update(StudentViewModel studentViewModel)
 {}

Alternatively if you just want to post some specific values you can do:

$('#myform').on('submit', function(e){
    e.preventDefault();

    var studentId = $(this).find('#Student_StudentId');
    var isActive = $(this).find('#Student_IsActive');

    $.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
         //Do something with response
    });
});

With a controller like:

     [HttpPost]
     public JsonResult Update(int studentId, bool isActive)
     {}

How to calculate an age based on a birthday?

I do it like this:

(Shortened the code a bit)

public struct Age
{
    public readonly int Years;
    public readonly int Months;
    public readonly int Days;

}

public Age( int y, int m, int d ) : this()
{
    Years = y;
    Months = m;
    Days = d;
}

public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
    if( startDate.Date > endDate.Date )
        {
            throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
        }

        int years = endDate.Year - startDate.Year;
        int months = 0;
        int days = 0;

        // Check if the last year, was a full year.
        if( endDate < startDate.AddYears (years) && years != 0 )
        {
            years--;
        }

        // Calculate the number of months.
        startDate = startDate.AddYears (years);

        if( startDate.Year == endDate.Year )
        {
            months = endDate.Month - startDate.Month;
        }
        else
        {
            months = ( 12 - startDate.Month ) + endDate.Month;
        }

        // Check if last month was a complete month.
        if( endDate < startDate.AddMonths (months) && months != 0 )
        {
            months--;
        }

        // Calculate the number of days.
        startDate = startDate.AddMonths (months);

        days = ( endDate - startDate ).Days;

        return new Age (years, months, days);
}

// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...

}

How do I update a model value in JavaScript in a Razor view?

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>
    }
}

Why is JsonRequestBehavior needed?

By default Jsonresult "Deny get"

Suppose if we have method like below

  [HttpPost]
 public JsonResult amc(){}

By default it "Deny Get".

In the below method

public JsonResult amc(){}

When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.

public JsonResult amc()
{
 return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:

       $.ajax({
            traditional: true,
            url: "/Conroller/MethodTest",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify( 
               [
                { id: 1, color: 'yellow' },
                { id: 2, color: 'blue' },
                { id: 3, color: 'red' }
                ]),
            success: function (data) {
                $scope.DisplayError(data.requestStatus);
            }
        });

Controler

public class Thing
{
    public int id { get; set; }
    public string color { get; set; }
}

public JsonResult MethodTest(IEnumerable<Thing> datav)
    {
   //now  datav is having all your values
  }

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

The main concept of partial view is returning the HTML code rather than going to the partial view it self.

[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 action return the HTML code of the partial view ("HolidayPartialView").

To refresh partial view replace the existing item with the new filtered item using the jQuery below.

$.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });

How can I make my string property nullable?

Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; } and you'll be able to set it to null.

Jquery Ajax, return success/error from mvc.net controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");

Or

return StatusCode((int)HttpStatusCode.InternalServerError, "My error");

Or

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
        })

Additionally you can handle different HTTP errors from jQuery side like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            }
        })

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

Date only from TextBoxFor()

TL;DR;

@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })

Applying [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] didn't work out for me!


Explanation:

The date of an html input element of type date must be formatted in respect to ISO8601, which is: yyyy-MM-dd

The displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.

My experience is, that the language is not determined by the Accept-Language header, but by either the browser display language or OS system language.

In order to display a date property of your model using Html.TextBoxFor:

enter image description here

Date property of your model class:

public DateTime DOB { get; set; }

Nothing else is needed on the model side.


In Razor you do:

@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })

Read HttpContent in WebApi controller

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

The first read in your case is being done when Web API is binding your model, after that the Request.Content will not return anything.

You can remove the contact from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):

[HttpPut]
public HttpResponseMessage Put(int accountId)
{
    HttpContent requestContent = Request.Content;
    string jsonContent = requestContent.ReadAsStringAsync().Result;
    CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
    ...
}

That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

Mailto on submit button

This seems to work fine:

<button onclick="location.href='mailto:[email protected]';">send mail</button>

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

ASP.NET MVC - Getting QueryString values

Query string parameters can be accepted simply by using an argument on the action - i.e.

public ActionResult Foo(string someValue, int someOtherValue) {...}

which will accept a query like .../someroute?someValue=abc&someOtherValue=123

Other than that, you can look at the request directly for more control.

How can I properly handle 404 in ASP.NET MVC?

1) Make abstract Controller class.

public abstract class MyController:Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }

    protected override void HandleUnknownAction(string actionName)
    {
        this.ActionInvoker.InvokeAction(this.ControllerContext, "NotFound");
    }
    protected override void OnAuthorization(AuthorizationContext filterContext) { }
}  

2) Make inheritence from this abstract class in your all controllers

public class HomeController : MyController
{}  

3) And add a view named "NotFound" in you View-Shared folder.

Get controller and action name from within controller?

You can get controller name or action name from action like any variable. They are just special (controller and action) and already defined so you do not need to do anything special to get them except telling you need them.

public string Index(string controller,string action)
   {
     var names=string.Format("Controller : {0}, Action: {1}",controller,action);
     return names;
   }

Or you can include controller , action in your models to get two of them and your custom data.

public class DtoModel
    {
        public string Action { get; set; }
        public string Controller { get; set; }
        public string Name { get; set; }
    }

public string Index(DtoModel baseModel)
    {
        var names=string.Format("Controller : {0}, Action: {1}",baseModel.Controller,baseModel.Action);
        return names;
    }

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

How to add "active" class to Html.ActionLink in ASP.NET MVC

May be little late. But hope this helps.

public static class Utilities
{
    public static string IsActive(this HtmlHelper html, 
                                  string control,
                                  string action)
    {
        var routeData = html.ViewContext.RouteData;

        var routeAction = (string)routeData.Values["action"];
        var routeControl = (string)routeData.Values["controller"];

        // both must match
        var returnActive = control == routeControl &&
                           action == routeAction;

        return returnActive ? "active" : "";
    }
}

And usage as follow:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li class='@Html.IsActive("Home", "Index")'>
            @Html.ActionLink("Home", "Index", "Home")
        </li>
        <li class='@Html.IsActive("Home", "About")'>
            @Html.ActionLink("About", "About", "Home")
        </li>
        <li class='@Html.IsActive("Home", "Contact")'>
            @Html.ActionLink("Contact", "Contact", "Home")
        </li>
    </ul>
</div>

Got reference from http://www.codingeverything.com/2014/05/mvcbootstrapactivenavbar.html

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I faced this error becouse I sent the Query string with wrong format

http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &

so make sure your Query String or passed parameter in the right format

How to get DropDownList SelectedValue in Controller in MVC

1st Approach (via Request or FormCollection):

You can read it from Request using Request.Form , your dropdown name is ddlVendor so pass ddlVendor key in the formCollection to get its value that is posted by form:

string strDDLValue = Request.Form["ddlVendor"].ToString();

or Use FormCollection:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{           
  string strDDLValue = form["ddlVendor"].ToString();

  return View(MV);
}

2nd Approach (Via Model):

If you want with Model binding then add a property in Model:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectedVendor {get;set;}
}

and in View:

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")

and in Action:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{           
   string SelectedValue = MV.SelectedVendor;
   return View(MV);
}

UPDATE:

If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectVendor {get;set;}
    public string SelectedvendorText { get; set; }
}

use jquery to set hidden field:

<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
   $("#SelectedvendorText").val($(this).text());
 });
});
</script>

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I also faced the same issue, however in my case my solution has a console application and EF class library which mainly interacts with database. I removed Config settings related to EF from the Console Application Config. I maintained the following configuration settings in EF class library i.e only at one place.

This worked for me.


<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.2.61023.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

<add name="EntityModel" connectionString="Server=Localhost\SQLEXPRESS;Database=SampleEntities;Trusted_Connection=True;" providerName="System.Data.EntityClient" />


How do I improve ASP.NET MVC application performance?

The basic suggestion is to follow REST principles and the following points ties some of these principals to the ASP.NET MVC framework:

  1. Make your controllers stateless - this is more of a 'Web performance / scalability' suggestion (as opposed to micro/machine level performance) and a major design decision that would affect your applications future - especially in case it becomes popular or if you need some fault tolerance for example.
    • Do not use Sessions
    • Do not use tempdata - which uses sessions
    • Do not try to 'cache' everything 'prematurely'.
  2. Use Forms Authentication
    • Keep your frequently accessed sensitive data in the authentication ticket
  3. Use cookies for frequently accessed non sensitive information
  4. Make your resources cachable on the web
  5. Compile your JavaScript. There is Closure compiler library to do it as well (sure there are others, just search for 'JavaScript compiler' too)
  6. Use CDNs (Content Delivery Network) - especially for your large media files and so on.
  7. Consider different types of storage for your data, for example, files, key/value stores, etc. - not only SQL Server
  8. Last but not least, test your web site for performance

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

localhost refused to connect Error in visual studio

I was having this issue and solved it by closing all open instances of Visual Studio.

Returning binary file from controller in ASP.NET Web API

For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;

This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.

MVC 4 Edit modal form using Bootstrap

In $('.editor-container').click(function (){}), shouldn't var url = "/area/controller/MyEditAction"; be var url = "/area/controller/EditPartData";?

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Passing data to a jQuery UI Dialog

I have now tried your suggestions and found that it kinda works,

  1. The dialog div is alsways written out in plaintext
  2. With the $.post version it actually works in terms that the controller gets called and actually cancels the booking, but the dialog stays open and page doesn't refresh. With the get version window.location = h.ref works great.

Se my "new" script below:

$('a.cancel').click(function() {
        var a = this;               
        $("#dialog").dialog({
            autoOpen: false,
            buttons: {
                "Ja": function() {
                    $.post(a.href);                     
                },
                "Nej": function() { $(this).dialog("close"); }
            },
            modal: true,
            overlay: {
                opacity: 0.5,

            background: "black"
        }
    });
    $("#dialog").dialog('open');
    return false;
});

});

Any clues?

oh and my Action link now looks like this:

<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new  { @class = "cancel" })%>

ASP.NET MVC Razor pass model to layout

this is pretty basic stuff, all you need to do is to create a base view model and make sure ALL! and i mean ALL! of your views that will ever use that layout will receive views that use that base model!

public class SomeViewModel : ViewModelBase
{
    public bool ImNotEmpty = true;
}

public class EmptyViewModel : ViewModelBase
{
}

public abstract class ViewModelBase
{
}

in the _Layout.cshtml:

@model Models.ViewModelBase
<!DOCTYPE html>
  <html>
  and so on...

in the the Index (for example) method in the home controller:

    public ActionResult Index()
    {
        var model = new SomeViewModel()
        {
        };
        return View(model);
    }

the Index.cshtml:

@model Models.SomeViewModel

@{
  ViewBag.Title = "Title";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row">

i disagree that passing a model to the _layout is an error, some user info can be passed and the data can be populate in the controllers inheritance chain so only one implementation is needed.

obviously for more advanced purpose you should consider creating custom static contaxt using injection and include that model namespace in the _Layout.cshtml.

but for basic users this will do the trick

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

Here is a solution I made using the above ideas that can be used for TextBoxFor and PasswordFor:

public static class HtmlHelperEx
{
    public static MvcHtmlString TextBoxWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.TextBoxFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));

    }

    public static MvcHtmlString PasswordWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.PasswordFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));

    }
}

public static class HtmlAttributesHelper
{
    public static IDictionary<string, object> AddAttribute(this object htmlAttributes, string name, object value)
    {
        var dictionary = htmlAttributes == null ? new Dictionary<string, object>() : htmlAttributes.ToDictionary();
        if (!String.IsNullOrWhiteSpace(name) && value != null && !String.IsNullOrWhiteSpace(value.ToString()))
            dictionary.Add(name, value);
        return dictionary;
    }

    public static IDictionary<string, object> ToDictionary(this object obj)
    {
        return TypeDescriptor.GetProperties(obj)
            .Cast<PropertyDescriptor>()
            .ToDictionary(property => property.Name, property => property.GetValue(obj));
    }
}

All ASP.NET Web API controllers return 404

I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.

Adding a css class to select using @Html.DropDownList()

You can simply do this:

@Html.DropDownList("PriorityID", null, new { @class="form-control"})

How to pass a textbox value from view to a controller in MVC 4?

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

View Code:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

Model

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

ASP.NET MVC Ajax Error handling

Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

And handle it as standard HTTP error on client as you like.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I would probably build the link manually, like this:

<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>

Html.ActionLink as a button or an image, not a link

There seems to be lots of solutions on how to created a link that displays as an image, but none that make it appear to be a button.

There is only good way that I have found to do this. Its a little bit hacky, but it works.

What you have to do is create a button and a separate action link. Make the action link invisible using css. When you click on the button, it can fire the click event of the action link.

<input type="button" value="Search" onclick="Search()" />
 @Ajax.ActionLink("Search", "ActionName", null, new AjaxOptions {}, new { id = "SearchLink", style="display:none;" })

function Search(){
    $("#SearchLink").click();
 }

It may be a pain in the butt to do this every time you add a link that needs to look like a button, but it does accomplish the desired result.

Phone Number Validation MVC

Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

ASP.NET MVC - Extract parameter of an URL

You can get these parameter list in ControllerContext.RoutValues object as key-value pair.

You can store it in some variable and you make use of that variable in your logic.

How to add and get Header values in WebApi

For .net Core in GET method, you can do like this:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }

Set Culture in an ASP.Net MVC app

I know this is an old question, but if you really would like to have this working with your ModelBinder (in respect to DefaultModelBinder.ResourceClassKey = "MyResource"; as well as the resources indicated in the data annotations of the viewmodel classes), the controller or even an ActionFilter is too late to set the culture.

The culture could be set in Application_AcquireRequestState, for example:

protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        // For example a cookie, but better extract it from the url
        string culture = HttpContext.Current.Request.Cookies["culture"].Value;

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
    }

EDIT

Actually there is a better way using a custom routehandler which sets the culture according to the url, perfectly described by Alex Adamyan on his blog.

All there is to do is to override the GetHttpHandler method and set the culture there.

public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // get culture from route data
        var culture = requestContext.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
        return base.GetHttpHandler(requestContext);
    }
}

MVC 3: How to render a view without its layout page when loaded via ajax?

I prefer, and use, your #1 option. I don't like #2 because to me View() implies you are returning an entire page. It should be a fully fleshed out and valid HTML page once the view engine is done with it. PartialView() was created to return arbitrary chunks of HTML.

I don't think it's a big deal to have a view that just calls a partial. It's still DRY, and allows you to use the logic of the partial in two scenarios.

Many people dislike fragmenting their action's call paths with Request.IsAjaxRequest(), and I can appreciate that. But IMO, if all you are doing is deciding whether to call View() or PartialView() then the branch is not a big deal and is easy to maintain (and test). If you find yourself using IsAjaxRequest() to determine large portions of how your action plays out, then making a separate AJAX action is probably better.

ASP.NET MVC 404 Error Handling

The response from Marco is the BEST solution. I needed to control my error handling, and I mean really CONTROL it. Of course, I have extended the solution a little and created a full error management system that manages everything. I have also read about this solution in other blogs and it seems very acceptable by most of the advanced developers.

Here is the final code that I am using:

protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 404)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            Response.Clear();
            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values["controller"] = "ErrorManager";
            routeData.Values["action"] = "Fire404Error";
            routeData.Values["exception"] = exception;
            Response.StatusCode = 500;

            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                    case 404:
                        routeData.Values["action"] = "Fire404Error";
                        break;
                }
            }
            // Avoid IIS7 getting in the middle
            Response.TrySkipIisCustomErrors = true;
            IController errormanagerController = new ErrorManagerController();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            var rc = new RequestContext(wrapper, routeData);
            errormanagerController.Execute(rc);
        }
    }

and inside my ErrorManagerController :

        public void Fire404Error(HttpException exception)
    {
        //you can place any other error handling code here
        throw new PageNotFoundException("page or resource");
    }

Now, in my Action, I am throwing a Custom Exception that I have created. And my Controller is inheriting from a custom Controller Based class that I have created. The Custom Base Controller was created to override error handling. Here is my custom Base Controller class:

public class MyBasePageController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.GetType();
        filterContext.ExceptionHandled = true;
        this.View("ErrorManager", filterContext).ExecuteResult(this.ControllerContext);
        base.OnException(filterContext);
    }
}

The "ErrorManager" in the above code is just a view that is using a Model based on ExceptionContext

My solution works perfectly and I am able to handle ANY error on my website and display different messages based on ANY exception type.

Display only date and no time

If the column type is DateTime in SQL then it will store a time where you pass one or not.

It'd be better to save the date properly:

model.ReturnDate = DateTime.Now;

and then format it when you need to display it:

@Html.Label(Model.ReturnDate.ToShortDateString())

Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

or

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

To add a property to your model add this code:

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

EDIT:

I just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

Editor templates are a cool way of managing repetitive controls in MVC:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

Pass Additional ViewData to a Strongly-Typed Partial View

I think this should work no?

ViewData["currentIndex"] = index;

Reset par to the default values at startup

An alternative solution for preventing functions to change the user par. You can set the default parameters early on the function, so that the graphical parameters and layout will not be changed during the function execution. See ?on.exit for further details.

on.exit(layout(1))
opar<-par(no.readonly=TRUE)
on.exit(par(opar),add=TRUE,after=FALSE)

Convert the first element of an array to a string in PHP

You could use print_r and html interpret it to convert it into a string with newlines like this:

$arraystring = print_r($your_array, true); 

$arraystring = '<pre>'.print_r($your_array, true).'</pre>';

Or you could mix many arrays and vars if you do this

ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

How to import a jar in Eclipse

Adding external Jar is not smart in case you want to change the project location in filesystem.

The best way is to add the jar to build path so your project will compile if exported:

  1. Create a folder called lib in your project folder.

  2. copy to this folder all the jar files you need.

  3. Refresh your project in eclipse.

  4. Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

Conversion from Long to Double in Java

I think it is good for you.

BigDecimal.valueOf([LONG_VALUE]).doubleValue()

How about this code? :D

Query-string encoding of a Javascript Object

Just another way (no recursive object):

   getQueryString = function(obj)
   {
      result = "";

      for(param in obj)
         result += ( encodeURIComponent(param) + '=' + encodeURIComponent(obj[param]) + '&' );

      if(result) //it's not empty string when at least one key/value pair was added. In such case we need to remove the last '&' char
         result = result.substr(0, result.length - 1); //If length is zero or negative, substr returns an empty string [ref. http://msdn.microsoft.com/en-us/library/0esxc5wy(v=VS.85).aspx]

      return result;
   }

alert( getQueryString({foo: "hi there", bar: 123, quux: 2 }) );

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

Skip a submodule during a Maven build

Maven version 3.2.1 added this feature, you can use the -pl switch (shortcut for --projects list) with ! or - (source) to exclude certain submodules.

mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install

Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.

The syntax to exclude multiple module is the same as the inclusion

mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install

EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)

mvn -pl "!submodule1,!submodule2" install

How can I view live MySQL queries?

Even though an answer has already been accepted, I would like to present what might even be the simplest option:

$ mysqladmin -u bob -p -i 1 processlist

This will print the current queries on your screen every second.

  • -u The mysql user you want to execute the command as
  • -p Prompt for your password (so you don't have to save it in a file or have the command appear in your command history)
  • i The interval in seconds.
  • Use the --verbose flag to show the full process list, displaying the entire query for each process. (Thanks, nmat)

There is a possible downside: fast queries might not show up if they run between the interval that you set up. IE: My interval is set at one second and if there is a query that takes .02 seconds to run and is ran between intervals, you won't see it.

Use this option preferably when you quickly want to check on running queries without having to set up a listener or anything else.

JavaScript: Passing parameters to a callback function

If you are not sure how many parameters are you going to be passed into callback functions, use apply function.

function tryMe (param1, param2) {
  alert (param1 + " and " + param2);
}

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

Mongoose.js: Find user by username LIKE value

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});

How to process SIGTERM signal gracefully?

A class based clean to use solution:

import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

if __name__ == '__main__':
  killer = GracefulKiller()
  while not killer.kill_now:
    time.sleep(1)
    print("doing something in a loop ...")

  print("End of the program. I was killed gracefully :)")

Import mysql DB with XAMPP in command LINE

mysql -h localhost -u username databasename < dump.sql

It works, try it. If password is blank no need to add the -p args.

How to remove all numbers from string?

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

Remove Last Comma from a string

The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.

EDIT: Is it really that confusing?

'This, is a random string'

Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.

How to check which version of Keras is installed?

The simplest way is using pip command:

pip list | grep Keras

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Google Script to see if text contains a value

I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.

function foo() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = ss.getSheetByName('spreadsheet-name');
    var r = s.getRange('A:A');
    var v = r.getValues();
    var searchTerm = 'needle';
    for(var i=v.length-1;i>=0;i--) {
        if(v[0,i].toString().indexOf(searchTerm) > -1) {
            // do something
        }
    }
};

@font-face not working

Using font-face requires a little understanding of browser inconsistencies and may require some changes on the web server itself. First thing you have to do is check the console to see if/what messages are being generated. Is it a permissions issue or resource not found....?

Secondly because each browser is expecting a different font type I would use Font Squirrel to upload your font and then generate the additional files and CSS needed. http://www.fontsquirrel.com/fontface/generator

And finally, versions of FireFox and IE will not allow fonts to be loaded cross domain. You may need to modify your Apache config or .htaccess (Header set Access-Control-Allow-Origin "*")

What are all the uses of an underscore in Scala?

The ones I can think of are

Existential types

def foo(l: List[Option[_]]) = ...

Higher kinded type parameters

case class A[K[_],T](a: K[T])

Ignored variables

val _ = 5

Ignored parameters

List(1, 2, 3) foreach { _ => println("Hi") }

Ignored names of self types

trait MySeq { _: Seq[_] => }

Wildcard patterns

Some(5) match { case Some(_) => println("Yes") }

Wildcard patterns in interpolations

"abc" match { case s"a$_c" => }

Sequence wildcard in patterns

C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }

Wildcard imports

import java.util._

Hiding imports

import java.util.{ArrayList => _, _}

Joining letters to operators

def bang_!(x: Int) = 5

Assignment operators

def foo_=(x: Int) { ... }

Placeholder syntax

List(1, 2, 3) map (_ + 2)

Method values

List(1, 2, 3) foreach println _

Converting call-by-name parameters to functions

def toFunction(callByName: => Int): () => Int = callByName _

Default initializer

var x: String = _   // unloved syntax may be eliminated

There may be others I have forgotten!


Example showing why foo(_) and foo _ are different:

This example comes from 0__:

trait PlaceholderExample {
  def process[A](f: A => Unit)

  val set: Set[_ => Unit]

  set.foreach(process _) // Error 
  set.foreach(process(_)) // No Error
}

In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).

In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.

This may well be the trickiest gotcha in Scala I have ever encountered.

Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.

Can a html button perform a POST request?

You can:

  • Either, use an <input type="submit" ..>, instead of that button.
  • or, Use a bit of javascript, to get a hold of form object (using name or id), and call submit(..) on it. Eg: form.submit(). Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.

The type arguments for method cannot be inferred from the usage

For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:

public class Trololol : ISignatur<bool>, ISignatur<int>{
    Type ISignatur<bool>.Type => typeof(bool);
    Type ISignatur<int>.Type => typeof(int);
}

How is the compiler supposed to resolve var access = service.Get(new Trololol())? Both int and bool are valid.

The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.

How to refresh a page with jQuery by passing a parameter to URL

You should be able to accomplish this by using location.href

if(window.location.hostname == "www.myweb.com"){
   window.location.href = window.location.href + "?single";
}

How to write loop in a Makefile?

A simple, shell/platform-independent, pure macro solution is ...

# GNU make (`gmake`) compatible; ref: <https://www.gnu.org/software/make/manual>
define EOL

$()
endef
%sequence = $(if $(word ${1},${2}),$(wordlist 1,${1},${2}),$(call %sequence,${1},${2} $(words _ ${2})))

.PHONY: target
target:
    $(foreach i,$(call %sequence,10),./a.out ${i}${EOL})

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

Rotate an image in image source in html

You can do this:

<img src="your image" style="transform:rotate(90deg);">

it is much easier.

Escaping special characters in Java Regular Expressions

Use this Utility function escapeQuotes() in order to escape strings in between Groups and Sets of a RegualrExpression.

List of Regex Literals to escape <([{\^-=$!|]})?*+.>

public class RegexUtils {
    static String escapeChars = "\\.?![]{}()<>*+-=^$|";
    public static String escapeQuotes(String str) {
        if(str != null && str.length() > 0) {
            return str.replaceAll("[\\W]", "\\\\$0"); // \W designates non-word characters
        }
        return "";
    }
}

From the Pattern class the backslash character ('\') serves to introduce escaped constructs. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

Example: String to be matched (hello) and the regex with a group is (\(hello\)). Form here you only need to escape matched string as shown below. Test Regex online

public static void main(String[] args) {
    String matched = "(hello)", regexExpGrup = "(" + escapeQuotes(matched) + ")";
    System.out.println("Regex : "+ regexExpGrup); // (\(hello\))
}

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Android Webview - Completely Clear the Cache

The only solution that works for me

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();
} 

How to implement the ReLU function in Numpy

If we have 3 parameters (t0, a0, a1) for Relu, that is we want to implement

if x > t0:
    x = x * a1
else:
    x = x * a0

We can use the following code:

X = X * (X > t0) * a1 +  X * (X < t0) * a0

X there is a matrix.

jQuery trigger event when click outside the element

    var visibleNotification = false;

  function open_notification() {
        if (visibleNotification == false) {
            $('.notification-panel').css('visibility', 'visible');
            visibleNotification = true;
        } else {
            $('.notification-panel').css('visibility', 'hidden');
            visibleNotification = false;
        }
    }

    $(document).click(function (evt) {
        var target = evt.target.className;
        if(target!="fa fa-bell-o bell-notification")
        {
            var inside = $(".fa fa-bell-o bell-notification");
            if ($.trim(target) != '') {
                if ($("." + target) != inside) {
                    if (visibleNotification == true) {
                        $('.notification-panel').css('visibility', 'hidden');
                        visibleNotification = false;
                    }
                }
            }
        }
    });

Compiling with g++ using multiple cores

GNU parallel

I was making a synthetic compilation benchmark and couldn't be bothered to write a Makefile, so I used:

sudo apt-get install parallel
ls | grep -E '\.c$' | parallel -t --will-cite "gcc -c -o '{.}.o' '{}'"

Explanation:

  • {.} takes the input argument and removes its extension
  • -t prints out the commands being run to give us an idea of progress
  • --will-cite removes the request to cite the software if you publish results using it...

parallel is so convenient that I could even do a timestamp check myself:

ls | grep -E '\.c$' | parallel -t --will-cite "\
  if ! [ -f '{.}.o' ] || [ '{}' -nt '{.}.o' ]; then
    gcc -c -o '{.}.o' '{}'
  fi
"

xargs -P can also run jobs in parallel, but it is a bit less convenient to do the extension manipulation or run multiple commands with it: Calling multiple commands through xargs

Parallel linking was asked at: Can gcc use multiple cores when linking?

TODO: I think I read somewhere that compilation can be reduced to matrix multiplication, so maybe it is also possible to speed up single file compilation for large files. But I can't find a reference now.

Tested in Ubuntu 18.10.

Can't resolve module (not found) in React.js

For me, I had the input correct but npm start can be buggy (at least using it with Hyper terminal on Windows and Linux). If I move files to different folders, npm start doesn't pick up on these changes. I need to cancel npm start process, make the move, save and then run npm start and it will see the files now.

C++: Rounding up to the nearest multiple of a number

For negative numToRound:

It should be really easy to do this but the standard modulo % operator doesn't handle negative numbers like one might expect. For instance -14 % 12 = -2 and not 10. First thing to do is to get modulo operator that never returns negative numbers. Then roundUp is really simple.

public static int mod(int x, int n) 
{
    return ((x % n) + n) % n;
}

public static int roundUp(int numToRound, int multiple) 
{
    return numRound + mod(-numToRound, multiple);
}

No templates in Visual Studio 2017

You need to install it by launching the installer.

Link to installer

Click the "Workload" tab* in the upper-left, then check top right ".NET-Desktop Development" and hit install. Note it may modify your installation size (bottom-right), and you can install other Workloads, but you must install ".NET-Desktop Development" at least.

Open Visual Studio installer; either "Modify" existing installation or begin a new installation. On the "Workloads" tab, choose the ".NET desktop devvelopment" option

*as seen in comments below, users were not able to achieve the equivalent using the "Individual Components" tab.

iOS Swift - Get the Current Local Time and Date Timestamp

First I would recommend you to store your timestamp as a NSNumber in your Firebase Database, instead of storing it as a String.

Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date instead of NSDate, except if you're interacting with some Obj-C code in your app.

You can of course use both, but the Documentation states:

Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

Now to answer your question, I think the problem here is because of the timezone.

For example if you print(Date()), as for now, you would get:

2017-09-23 06:59:34 +0000

This is the Greenwich Mean Time (GMT).

So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd HH:mm"

    let dateString = formatter.string(from: now)

Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date / NSNumber, or store it directly as a String in the database..)

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

Laravel: getting a a single value from a MySQL query

On laravel 5.6 it has a very simple solution:

User::where('username', $username)->first()->groupName;

It will return groupName as a string.

Simple URL GET/POST function in Python

Even easier: via the requests module.

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)

How to determine whether a substring is in a different string

You can also try find() method. It determines if string str occurs in string, or in a substring of string.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

opening html from google drive

I don't think it is necessary to "host" the content using the way from the accepted answer. It is too complicated for a normal user with limited developing skills.

Google actually has provided hosting feature without using Drive SDK/API, what you need is just few clicks. Check this out:

http://support.google.com/drive/bin/answer.py?hl=en&answer=2881970

It is the same to the answer of user1557669. However, in step 4, the URL is not correct, it is like:

https://drive.google.com/#folders/...

To get the correct host URL. Right click on the html file (you have to finish 1-3 steps first and put the html in the public shared folder), and select "Details" from the context menu. You will find the hosting URL right close to the bottom of the details panel. It should look like:

https://googledrive.com/host/.../abc.html

Then you can share the link to anyone. Happy sharing.

How to keep a Python script output window open?

To keep your window open in case of exception (yet, while printing the exception)

Python 2

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
        print "Press Enter to continue ..." 
        raw_input() 

To keep the window open in any case:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
    finally:
        print "Press Enter to continue ..." 
        raw_input()

Python 3

For Python3 you'll have to use input() in place of raw_input(), and of course adapt the print statements.

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
        print("Press Enter to continue ...")
        input() 

To keep the window open in any case:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Press Enter to continue ...")
    input()

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

inline conditionals in angular.js

Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}}

URL to load resources from the classpath in Java

You can also set the property programmatically during startup:

final String key = "java.protocol.handler.pkgs";
String newValue = "org.my.protocols";
if (System.getProperty(key) != null) {
    final String previousValue = System.getProperty(key);
    newValue += "|" + previousValue;
}
System.setProperty(key, newValue);

Using this class:

package org.my.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(final URL u) throws IOException {
        final URL resourceUrl = ClassLoader.getSystemClassLoader().getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Thus you get the least intrusive way to do this. :) java.net.URL will always use the current value from the system properties.

Disable Enable Trigger SQL server for a table

After the ENABLE TRIGGER OR DISABLE TRIGGER in a new line write GO, Example:

DISABLE TRIGGER dbo.tr_name ON dbo.table_name

GO
-- some update statement

ENABLE TRIGGER dbo.tr_name  ON dbo.table_name

GO

Is it possible that one domain name has multiple corresponding IP addresses?

You can do it. That is what big guys do as well.

First query:

» host google.com 
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229

Next query:

» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238

As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.

Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.

Read MS Exchange email in C#

It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.

What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)

If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)

If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I had a similar problem, where I had a master page as follows:

@section Scripts {
<script>
    $(document).ready(function () {
        ...
    });
</script>
}

...

@Html.Partial("_Charts", Model)

but the partial view depended on some JavaScript in the Scripts section. I solved it by encoding the partial view as JSON, loading it into a JavaScript variable and then using this to populate a div, so:

@{
    var partial = Html.Raw(Json.Encode(new { html = Html.Partial("_Charts", Model).ToString() }));
}

@section Scripts {
<script>
    $(document).ready(function () {
        ...
        var partial = @partial;
        $('#partial').html(partial.html);
    });
</script>
}

<div id="partial"></div>

How to format font style and color in echo

 echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";

reCAPTCHA ERROR: Invalid domain for site key

No need to create a new key just clear site data on browser

If you change your site domain then add that domain to existing key (it's not necessary to a create new one) and save it.

https://www.google.com/recaptcha/admin#list

but google recapture has some data on browser. Clear them then it will work with your new domain enter image description here

How to set image in circle in swift

For Swift 4:

import UIKit

extension UIImageView {

func makeRounded() {
    let radius = self.frame.width/2.0
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
   }
}

Razor View Engine : An expression tree may not contain a dynamic operation

This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.

How do I pass JavaScript variables to PHP?

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

jquery get height of iframe content when loaded

I found the following to work on Chrome, Firefox and IE11:

$('iframe').load(function () {
    $('iframe').height($('iframe').contents().height());
});

When the Iframes content is done loading the event will fire and it will set the IFrames height to that of its content. This will only work for pages within the same domain as that of the IFrame.

XAMPP permissions on Mac OS X?

If you are running your page on the new XAMPP-VM version of MacOS you will have to set daemon as user and as group. Here you can find a great step-by-step illustration with screenshots from aXfon on how to do this.

As the htdocs folder under XAMPP-VM will be mounted as external volume, you'll have to do this as root of the mounted volume (root@debian). This can be achieved through the XAMPP-VM GUI: See screenshot.

Once you are running as root of the mounted volume you can as described above change the file permission using:

chown -R daemon:daemon /opt/lampp/htdocs/FOLDER_OF_YOUR_PAGE

Source (w/ step-by-step illustration): aXfon

How to properly add include directories with CMake

Two things must be done.

First add the directory to be included:

target_include_directories(test PRIVATE ${YOUR_DIRECTORY})

In case you are stuck with a very old CMake version (2.8.10 or older) without support for target_include_directories, you can also use the legacy include_directories instead:

include_directories(${YOUR_DIRECTORY})

Then you also must add the header files to the list of your source files for the current target, for instance:

set(SOURCES file.cpp file2.cpp ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_executable(test ${SOURCES})

This way, the header files will appear as dependencies in the Makefile, and also for example in the generated Visual Studio project, if you generate one.

How to use those header files for several targets:

set(HEADER_FILES ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)

add_library(mylib libsrc.cpp ${HEADER_FILES})
target_include_directories(mylib PRIVATE ${YOUR_DIRECTORY})
add_executable(myexec execfile.cpp ${HEADER_FILES})
target_include_directories(myexec PRIVATE ${YOUR_DIRECTORY})

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

ASP.NET MVC - Extract parameter of an URL

public ActionResult Index(int id,string value)

This function get values form URL After that you can use below function

Request.RawUrl - Return complete URL of Current page

RouteData.Values - Return Collection of Values of URL

Request.Params - Return Name Value Collections

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Make sure that you aren't clicking on "Run unnamed" from 'run' tab. You must click on "run ". Or just click the green shortcut button.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

I'd utilize the built in Date object to do the validation for me. Even after you switch from - to / you still need to check whether the month is between 0 and 12, the date is between 0 and 31 and the year between 1900 and 2013 for example.

function validateDOB(){

    var dob = document.forms["ProcessInfo"]["txtDOB"].value;
    var data = dob.split("/");
    // using ISO 8601 Date String
    if (isNaN(Date.parse(data[2] + "-" + data[1] + "-" + data[0]))) {
        return false;
    }

    return true;
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Example:_Using_parse for more information.

How to pass Multiple Parameters from ajax call to MVC Controller

In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({
                    'input': $('#myInput').val(),
                    'name': $('#myName').val(),
                });

Now use it in ajax call

$.ajax({
          url: "/Home/SaveChart",
          type: 'POST',
          async: false,
          dataType: 'json',
          contentType: 'application/json',
          data: dataObject,
          success: function (data) { },
          error: function (xhr) { }            )};

AngularJs $http.post() does not send data

Unlike JQuery and for the sake of pedantry, Angular uses JSON format for POST data transfer from a client to the server (JQuery applies x-www-form-urlencoded presumably, although JQuery and Angular uses JSON for data imput). Therefore there are two parts of problem: in js client part and in your server part. So you need:

  1. put js Angular client part like this:

    $http({
    method: 'POST',
    url: 'request-url',
    data: {'message': 'Hello world'}
    });
    

AND

  1. write in your server part to receive data from a client (if it is php).

            $data               = file_get_contents("php://input");
            $dataJsonDecode     = json_decode($data);
            $message            = $dataJsonDecode->message;
            echo $message;     //'Hello world'
    

Note: $_POST will not work!

The solution works for me fine, hopefully, and for you.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

UPDATE

the super finishAffinity() method will help to reduce the code but achieve the same. It will finish the current activity as well as all activities in the stack, use getActivity().finishAffinity() if you are in a fragment.

finishAffinity(); 
startActivity(new Intent(mActivity, LoginActivity.class));

ORIGINAL ANSWER

Assume that LoginActivity --> HomeActivity --> ... --> SettingsActivity call signOut():

void signOut() {
    Intent intent = new Intent(this, HomeActivity.class);
    intent.putExtra("finish", true);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
    startActivity(intent);
    finish();
}

HomeActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    boolean finish = getIntent().getBooleanExtra("finish", false);
    if (finish) {
        startActivity(new Intent(mContext, LoginActivity.class));
        finish();
        return;
    }
    initializeView();
}

This works for me, hope that it is helpful for you too. :)

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

Concatenate multiple files but include filename as section headers

This is how I normally handle formatting like that:

for i in *; do echo "$i"; echo ; cat "$i"; echo ; done ;

I generally pipe the cat into a grep for specific information.

Best way to display data via JSON using jQuery

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

offsetTop vs. jQuery.offset().top

Try this: parseInt(jQuery.offset().top, 10)

Sending mass email using PHP

First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers

I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

Install Application programmatically on Android

The solutions provided to this question are all applicable to targetSdkVersion s of 23 and below. For Android N, i.e. API level 24, and above, however, they do not work and crash with the following Exception:

android.os.FileUriExposedException: file:///storage/emulated/0/... exposed beyond app through Intent.getData()

This is due to the fact that starting from Android 24, the Uri for addressing the downloaded file has changed. For instance, an installation file named appName.apk stored on the primary external filesystem of the app with package name com.example.test would be as

file:///storage/emulated/0/Android/data/com.example.test/files/appName.apk

for API 23 and below, whereas something like

content://com.example.test.authorityStr/pathName/Android/data/com.example.test/files/appName.apk

for API 24 and above.

More details on this can be found here and I am not going to go through it.

To answer the question for targetSdkVersion of 24 and above, one has to follow these steps: Add the following to the AndroidManifest.xml:

<application
        android:allowBackup="true"
        android:label="@string/app_name">
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.authorityStr"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"/>
        </provider>
</application>

2. Add the following paths.xml file to the xml folder on res in src, main:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="pathName"
        path="pathValue"/>
</paths>

The pathName is that shown in the exemplary content uri example above and pathValue is the actual path on the system. It would be a good idea to put a "." (without quotes) for pathValue in the above if you do not want to add any extra subdirectory.

  1. Write the following code to install the apk with the name appName.apk on the primary external filesystem:

    File directory = context.getExternalFilesDir(null);
    File file = new File(directory, fileName);
    Uri fileUri = Uri.fromFile(file);
    if (Build.VERSION.SDK_INT >= 24) {
        fileUri = FileProvider.getUriForFile(context, context.getPackageName(),
                file);
    }
    Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
    activity.finish();
    

No permission is also necessary when writing to your own app's private directory on the external filesystem.

I have written an AutoUpdate library here in which I have used the above.

regular expression for Indian mobile numbers

You may use this

/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/

Valid Entries:

6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723

Invalid Entries:

WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184

Validate it at https://regex101.com/

How do you change the document font in LaTeX?

I found the solution thanks to the link in Vincent's answer.

 \renewcommand{\familydefault}{\sfdefault}

This changes the default font family to sans-serif.

How to center icon and text in a android button with width set to "fill parent"

Had similar issue but wanted to have center drawable with no text and no wrapped layouts. Solution was to create custom button and add one more drawable in addition to LEFT, RIGHT, TOP, BOTTOM. One can easily modify drawable placement and have it in desired position relative to text.

CenterDrawableButton.java

public class CenterDrawableButton extends Button {
    private Drawable mDrawableCenter;

    public CenterDrawableButton(Context context) {
        super(context);
        init(context, null);
    }

    public CenterDrawableButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs){
        //if (isInEditMode()) return;
        if(attrs!=null){
            TypedArray a = context.getTheme().obtainStyledAttributes(
                    attrs, R.styleable.CenterDrawableButton, 0, 0);

            try {
                setCenterDrawable(a.getDrawable(R.styleable.CenterDrawableButton_drawableCenter));

            } finally {
                a.recycle();
            }

        }
    }

    public void setCenterDrawable(int center) {
        if(center==0){
            setCenterDrawable(null);
        }else
        setCenterDrawable(getContext().getResources().getDrawable(center));
    }
    public void setCenterDrawable(@Nullable Drawable center) {
        int[] state;
        state = getDrawableState();
        if (center != null) {
            center.setState(state);
            center.setBounds(0, 0, center.getIntrinsicWidth(), center.getIntrinsicHeight());
            center.setCallback(this);
        }
        mDrawableCenter = center;
        invalidate();
        requestLayout();
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(mDrawableCenter!=null) {
            setMeasuredDimension(Math.max(getMeasuredWidth(), mDrawableCenter.getIntrinsicWidth()),
                    Math.max(getMeasuredHeight(), mDrawableCenter.getIntrinsicHeight()));
        }
    }
    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (mDrawableCenter != null) {
            int[] state = getDrawableState();
            mDrawableCenter.setState(state);
            mDrawableCenter.setBounds(0, 0, mDrawableCenter.getIntrinsicWidth(),
                    mDrawableCenter.getIntrinsicHeight());
        }
        invalidate();
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        if (mDrawableCenter != null) {
            Rect rect = mDrawableCenter.getBounds();
            canvas.save();
            canvas.translate(getWidth() / 2 - rect.right / 2, getHeight() / 2 - rect.bottom / 2);
            mDrawableCenter.draw(canvas);
            canvas.restore();
        }
    }
}

attrs.xml

<resources>
    <attr name="drawableCenter" format="reference"/>
    <declare-styleable name="CenterDrawableButton">
        <attr name="drawableCenter"/>
    </declare-styleable>
</resources>

usage

<com.virtoos.android.view.custom.CenterDrawableButton
            android:id="@id/centerDrawableButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:drawableCenter="@android:drawable/ic_menu_info_details"/>

Android WebView not loading an HTTPS URL

override onReceivedSslError and remove

super.onReceivedSslError(view, handler, error)

And to solve Google security:

setDomStorageEnabled(true);

Full code is:

webView.enableJavaScript();
webView.getSettings().setDomStorageEnabled(true); // Add this
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // DO NOT CALL SUPER METHOD
            super.onReceivedSslError(view, handler, error);
        }
    });

store return json value in input hidden field

If you use the JSON Serializer, you can simply store your object in string format as such

myHiddenText.value = JSON.stringify( myObject );

You can then get the value back with

myObject = JSON.parse( myHiddenText.value );

However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

How to run python script in webpage

If you are using your own computer, install a software called XAMPP (or WAMPP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to xampp folder and double click the htdocs folder. Now what you need to do is create an html file (I'm gonna call it runpython.html). (Remember to move the python file to htdocs as well)

Add in this to your html body (and inputs as necessary)

<form action = "file_name.py" method = "POST">
   <input type = "submit" value = "Run the Program!!!">
</form>

Now, in the python file, we are basically going to be printing out HTML code.

#We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.

    import cgitb
    import cgi

    cgitb.enable() #This will show any errors on your webpage

    inputs = cgi.FieldStorage() #REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']

    print "Content-type: text/html" #We are using HTML, so we need to tell the server

    print #Just do it because it is in the tutorial :P

    print "<title> MyPythonWebpage </title>"

    print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

How to create a temporary directory and get the path / file name in Python

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

Making Python loggers output all messages to stdout in addition to log file

All logging output is handled by the handlers; just add a logging.StreamHandler() to the root logger.

Here's an example configuring a stream handler (using stdout instead of the default stderr) and adding it to the root logger:

import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

E: Unable to locate package mongodb-org

sudo apt-get install -y mongodb 

it works for 32-bit ubuntu, try it.best of luck.

Maximum length for MD5 input/output

There is no limit to the input of md5 that I know of. Some implementations require the entire input to be loaded into memory before passing it into the md5 function (i.e., the implementation acts on a block of memory, not on a stream), but this is not a limitation of the algorithm itself. The output is always 128 bits. Note that md5 is not an encryption algorithm, but a cryptographic hash. This means that you can use it to verify the integrity of a chunk of data, but you cannot reverse the hashing. Also note that md5 is considered broken, so you shouldn't use it for anything security-related (it's still fine to verify the integrity of downloaded files and such).

Handling back button in Android Navigation Component

This is 2 lines of code can listen for back press, from fragments, [TESTED and WORKING]

  requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {

            //setEnabled(false); // call this to disable listener
            //remove(); // call to remove listener
            //Toast.makeText(getContext(), "Listing for back press from this fragment", Toast.LENGTH_SHORT).show();
     }

Trim to remove white space

jQuery.trim() capital Q?

or $.trim()

How to check if a URL exists or returns 404 with Java?

You may want to add

HttpURLConnection.setFollowRedirects(false);
// note : or
//        huc.setInstanceFollowRedirects(false)

if you don't want to follow redirection (3XX)

Instead of doing a "GET", a "HEAD" is all you need.

huc.setRequestMethod("HEAD");
return (huc.getResponseCode() == HttpURLConnection.HTTP_OK);

Convert string to a variable name

The function you are looking for is get():

assign ("abc",5)
get("abc")

Confirming that the memory address is identical:

getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE

Reference: R FAQ 7.21 How can I turn a string into a variable?

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

For me following worked:

in directive declare it like this:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            myFunction: '=',
        },
        templateUrl: 'myDirective.html'
    };
})  

In directive template use it in following way:

<select ng-change="myFunction(selectedAmount)">

And then when you use the directive, pass the function like this:

<data-my-directive
    data-my-function="setSelectedAmount">
</data-my-directive>

You pass the function by its declaration and it is called from directive and parameters are populated.

how I can show the sum of in a datagridview column?

 decimal Total = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value);
  }

labelName.Text = Total.ToString();

struct in class

I'd like to add another use case for an internal struct/class and its usability. An inner struct is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct instead of loose data members lying around.

The inner struct/class is but a data only compartment, ie it has no functions (except maybe constructors).

#include <iostream>

class E
{
    // E functions..
public:
    struct X
    {
        int v;
        // X variables..
    } x;
    // E variables..
};

int main()
{
    E e;
    e.x.v = 9;
    std::cout << e.x.v << '\n';
    
    E e2{5};
    std::cout << e2.x.v << '\n';

    // You can instantiate an X outside E like so:
    //E::X xOut{24};
    //std::cout << xOut.v << '\n';
    // But you shouldn't want to in this scenario.
    // X is only a data member (containing other data members)
    // for use only inside the internal operations of E
    // just like the other E's data members
}

This practice is widely used in graphics, where the inner struct will be sent as a Constant Buffer to HLSL. But I find it neat and useful in many cases.

Private pages for a private Github repo

I had raised a support ticket against Github and got a response confirming the fact that ALL pages are public. I've now requested them to add a note to help.github.com/pages.

Logging in Scala

Writer, Monoid and a Monad implementation.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Since cP/WHM took away the ability to modify User privileges as root in PHPMyAdmin, you have to use the command line to:

mysql>  GRANT FILE ON *.* TO 'user'@'localhost';

Step 2 is to allow that user to dump a file in a specific folder. There are a few ways to do this but I ended up putting a folder in :

/home/user/tmp/db

and

chown mysql:mysql /home/user/tmp/db

That allows the mysql user to write the file. As previous posters have said, you can use the MySQL temp folder too, I don't suppose it really matters but you definitely don't want to make it 0777 permission (world-writeable) unless you want the world to see your data. There is a potential problem if you want to rinse-repeat the process as INTO OUTFILE won't work if the file exists. If your files are owned by a different user then just trying to unlink($file) won't work. If you're like me (paranoid about 0777) then you can set your target directory using:

chmod($dir,0777)

just prior to doing the SQL command, then

chmod($dir,0755)

immediately after, followed by unlink(file) to delete the file. This keeps it all running under your web user and no need to invoke the mysql user.

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return currentPopulation + currentPopulation * growthRate  / 100;
}

Redirect stdout to a file in Python?

Programs written in other languages (e.g. C) have to do special magic (called double-forking) expressly to detach from the terminal (and to prevent zombie processes). So, I think the best solution is to emulate them.

A plus of re-executing your program is, you can choose redirections on the command-line, e.g. /usr/bin/python mycoolscript.py 2>&1 1>/dev/null

See this post for more info: What is the reason for performing a double fork when creating a daemon?

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

How to insert a newline in front of a pattern?

In my case the below method works.

sed -i 's/playstation/PS4/' input.txt

Can be written as:

sed -i 's/playstation/PS4\nplaystation/' input.txt

PS4
playstation

Consider using \\n while using it in a string literal.

  • sed : is stream editor

  • -i : Allows to edit the source file

  • +: Is delimiter.

I hope the above information works for you .

Remove border from buttons

$(".myButtonClass").css(["border:none; background-color:white; padding:0"]);

What is PECS (Producer Extends Consumer Super)?

Using real life example (with some simplifications):

  1. Imagine a freight train with freight cars as analogy to a list.
  2. You can put a cargo in a freight car if the cargo has the same or smaller size than the freight car = <? super FreightCarSize>
  3. You can unload a cargo from a freight car if you have enough place (more than the size of the cargo) in your depot = <? extends DepotSize>

Postgres ERROR: could not open file for reading: Permission denied

I had the same error message but was using psycopg2 to communicate with PostgreSQL. I fixed the permission issues by using the functions copy_from and copy_expert that will open the file on the client side as the user running the python script and feed the data to the database over STDIN.

Refer to this link for further information.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

cy = function()
    local T = os.time()
        coroutine.yield(coroutine.resume(coroutine.create(function()
    end)))
    return os.time()-T
end
sleep = function(time)
    if not time or time == 0 then 
        time = cy()
    end
    local t = 0
    repeat
        local T = os.time()
        coroutine.yield(coroutine.resume(coroutine.create(function() end)))
        t = t + (os.time()-T)
    until t >= time
end

How to check a radio button with jQuery?

Try this.

To check Radio button using Value use this.

$('input[name=type][value=2]').attr('checked', true); 

Or

$('input[name=type][value=2]').attr('checked', 'checked');

Or

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this.

$('#radio_1').attr('checked','checked');

Or

$('#radio_1').prop('checked','checked');

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I solved, replacing 'http..' git url with 'ssh..' simple open .git/config file and copy it there

Numpy: Checking if a value is NaT

Very simple and surprisingly fast: (without numpy or pandas)

    str( myDate ) == 'NaT'            # True if myDate is NaT

Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.

It's also useful when comparing two dates either of which might be NaT as follows:

   str( date1 ) == str( date1 )       # True
   str( date1 ) == str( NaT )         # False
   str( NaT )   == str( date1 )       # False

wait for it...

   str( NaT )   == str( Nat )         # True    (hooray!)

SQL - Update multiple records in one query

You can accomplish it with INSERT as below:

INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);

This insert new values into table, but if primary key is duplicated (already inserted into table) that values you specify would be updated and same record would not be inserted second time.

How to read/write files in .Net Core?

For writing any Text to a file.

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
    {
        //Check Whether directory exist or not if not then create it
        if(!Directory.Exists(DirectoryPath))
        {
            Directory.CreateDirectory(DirectoryPath);
        }

        string FilePath = DirectoryPath + "\\" + FileName;
        //Check Whether file exist or not if not then create it new else append on same file
        if (!File.Exists(FilePath))
        {
            File.WriteAllText(FilePath, Text);
        }
        else
        {
            Text = $"{Environment.NewLine}{Text}";
            File.AppendAllText(FilePath, Text);
        }
    }

For reading a Text from file

public static string ReadFromFile(string DirectoryPath,string FileName)
    {
        if (Directory.Exists(DirectoryPath))
        {
            string FilePath = DirectoryPath + "\\" + FileName;
            if (File.Exists(FilePath))
            {
                return File.ReadAllText(FilePath);
            }
        }
        return "";
    }

For Reference here this is the official microsoft document link.

Avoiding NullPointerException in Java

I find Guava Preconditions to be very useful in this case. I don't like leaving nulls to null pointer exception since the only way to understand an NPE is by locating the line number. Line numbers in production version and development version can be different.

Using Guava Preconditions, I can check null parameters and define a meaningful exception message in one line.

For example,

Preconditions.checkNotNull(paramVal, "Method foo received null paramVal");

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

Correct way to detach from a container without stopping it

You can simply kill docker cli process by sending SEGKILL. If you started the container with

docker run -it some/container

You can get it's pid

ps -aux | grep docker

user   1234  0.3  0.6 1357948 54684 pts/2   Sl+  15:09   0:00 docker run -it some/container

let's say it's 1234, you can "detach" it with

kill -9 1234

It's somewhat of a hack but it works!

Angular File Upload

Very easy and fastest method is using ng2-file-upload.

Install ng2-file-upload via npm. npm i ng2-file-upload --save

At first import module in your module.

import { FileUploadModule } from 'ng2-file-upload';

Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]

Markup:

<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>

In your commponent ts:

import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });

It`is simplest usage of this. To know all power of this see demo

How do I get video durations with YouTube API version 3?

You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because the duration is there.

For example, the following call:

https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Perhaps a 63.2% / 36.8% is a reasonable choice. The reason would be that if you had a total sample size n and wanted to randomly sample with replacement (a.k.a. re-sample, as in the statistical bootstrap) n cases out of the initial n, the probability of an individual case being selected in the re-sample would be approximately 0.632, provided that n is not too small, as explained here: https://stats.stackexchange.com/a/88993/16263

For a sample of n=250, the probability of an individual case being selected for a re-sample to 4 digits is 0.6329. For a sample of n=20000, the probability is 0.6321.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

Here the problem was my Avast AV. As soon I disabled it, the problem was gone.

But, I really would like to understand the cause of this behavior.

Counting unique values in a column in pandas dataframe like in Qlik?

To count unique values in column, say hID of dataframe df, use:

len(df.hID.unique())

Why doesn't JUnit provide assertNotEquals methods?

I am working on JUnit in java 8 environment, using jUnit4.12

for me: compiler was not able to find the method assertNotEquals, even when I used
import org.junit.Assert;

So I changed
assertNotEquals("addb", string);
to
Assert.assertNotEquals("addb", string);

So if you are facing problem regarding assertNotEqual not recognized, then change it to Assert.assertNotEquals(,); it should solve your problem

Opening Android Settings programmatically

You can try to call:

startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));

for other screen in setting screen, you can go to

https://developer.android.com/reference/android/provider/Settings.html

Hope help you in this case.

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

Which WebControl are you using? Did you try?

DateTime.Now.ToString("yyyy-MM-dd");

How to implement drop down list in flutter?

If you don't want the Drop list to show up like a popup. You can customize it this way just like me (it will show up as if on the same flat, see image below):

enter image description here

After expand:

enter image description here

Please follow the steps below: First, create a dart file named drop_list_model.dart:

import 'package:flutter/material.dart';

class DropListModel {
  DropListModel(this.listOptionItems);

  final List<OptionItem> listOptionItems;
}

class OptionItem {
  final String id;
  final String title;

  OptionItem({@required this.id, @required this.title});
}

Next, create file file select_drop_list.dart:

import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';

class SelectDropList extends StatefulWidget {
  final OptionItem itemSelected;
  final DropListModel dropListModel;
  final Function(OptionItem optionItem) onOptionSelected;

  SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);

  @override
  _SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}

class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {

  OptionItem optionItemSelected;
  final DropListModel dropListModel;

  AnimationController expandController;
  Animation<double> animation;

  bool isShow = false;

  _SelectDropListState(this.optionItemSelected, this.dropListModel);

  @override
  void initState() {
    super.initState();
    expandController = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: 350)
    );
    animation = CurvedAnimation(
      parent: expandController,
      curve: Curves.fastOutSlowIn,
    );
    _runExpandCheck();
  }

  void _runExpandCheck() {
    if(isShow) {
      expandController.forward();
    } else {
      expandController.reverse();
    }
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.symmetric(
                horizontal: 15, vertical: 17),
            decoration: new BoxDecoration(
              borderRadius: BorderRadius.circular(20.0),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                    blurRadius: 10,
                    color: Colors.black26,
                    offset: Offset(0, 2))
              ],
            ),
            child: new Row(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Icon(Icons.card_travel, color: Color(0xFF307DF1),),
                SizedBox(width: 10,),
                Expanded(
                    child: GestureDetector(
                      onTap: () {
                        this.isShow = !this.isShow;
                        _runExpandCheck();
                        setState(() {

                        });
                      },
                      child: Text(optionItemSelected.title, style: TextStyle(
                          color: Color(0xFF307DF1),
                          fontSize: 16),),
                    )
                ),
                Align(
                  alignment: Alignment(1, 0),
                  child: Icon(
                    isShow ? Icons.arrow_drop_down : Icons.arrow_right,
                    color: Color(0xFF307DF1),
                    size: 15,
                  ),
                ),
              ],
            ),
          ),
          SizeTransition(
              axisAlignment: 1.0,
              sizeFactor: animation,
              child: Container(
                margin: const EdgeInsets.only(bottom: 10),
                  padding: const EdgeInsets.only(bottom: 10),
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          blurRadius: 4,
                          color: Colors.black26,
                          offset: Offset(0, 4))
                    ],
                  ),
                  child: _buildDropListOptions(dropListModel.listOptionItems, context)
              )
          ),
//          Divider(color: Colors.grey.shade300, height: 1,)
        ],
      ),
    );
  }

  Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
    return Column(
      children: items.map((item) => _buildSubMenu(item, context)).toList(),
    );
  }

  Widget _buildSubMenu(OptionItem item, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
      child: GestureDetector(
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                padding: const EdgeInsets.only(top: 20),
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
                ),
                child: Text(item.title,
                    style: TextStyle(
                        color: Color(0xFF307DF1),
                        fontWeight: FontWeight.w400,
                        fontSize: 14),
                    maxLines: 3,
                    textAlign: TextAlign.start,
                    overflow: TextOverflow.ellipsis),
              ),
            ),
          ],
        ),
        onTap: () {
          this.optionItemSelected = item;
          isShow = false;
          expandController.reverse();
          widget.onOptionSelected(item);
        },
      ),
    );
  }

}

Initialize value:

DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Ch?n quy?n truy c?p");

Finally use it:

SelectDropList(
           this.optionItemSelected, 
           this.dropListModel, 
           (optionItem){
                 optionItemSelected = optionItem;
                    setState(() {
  
                    });
               },
            )

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

Annotations from javax.validation.constraints not working

You need to add @Valid to each member variable, which was also an object that contained validation constraints.

Laravel Query Builder where max id

For objects you can nest the queries:

DB::table('orders')->find(DB::table('orders')->max('id'));

So the inside query looks up the max id in the table and then passes that to the find, which gets you back the object.

How to remove the default link color of the html hyperlink 'a' tag?

If you don't want to see the underline and default color which is provided by the browser, you can keep the following code in the top of your main.css file. If you need different color and decoration styling you can easily override the defaults using the below code snippet.

 a, a:hover, a:focus, a:active {
      text-decoration: none;
      color: inherit;
 }

converting CSV/XLS to JSON?

This worked perfectly for me and does NOT require a file upload:

https://github.com/cparker15/csv-to-json?files=1

Why and when to use angular.copy? (Deep Copy)

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.

_x000D_
_x000D_
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.printToConsole = function() {_x000D_
      $scope.main = {_x000D_
        first: 'first',_x000D_
        second: 'second'_x000D_
      };_x000D_
_x000D_
      $scope.child = angular.copy($scope.main);_x000D_
      console.log('Main object :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object with angular.copy :');_x000D_
      console.log($scope.child);_x000D_
_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('New Child object :')_x000D_
      console.log($scope.child);_x000D_
      console.log('Main object after child change and using angular.copy :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Assing main object without copy and updating child');_x000D_
_x000D_
      $scope.child = $scope.main;_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('Main object after update:');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object after update:');_x000D_
      console.log($scope.child);_x000D_
    }_x000D_
  }_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
  first: 'first',_x000D_
  second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
  three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
  <button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I read all classes from a Java package in the classpath?

Scannotation and Reflections use class path scanning approach:

Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:

Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

enabling cross-origin resource sharing on IIS7

With ASP.net Web API 2 install Microsoft ASP.NET Cross Origin support via nuget.

http://enable-cors.org/server_aspnet.html

public static void Register(HttpConfiguration config)
{
 var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com",
                                                   "Origin, Content-Type, Accept",
                                                   "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
}

How to listen for 'props' changes

@JoeSchr has an answer. Here is another way to do if you don't want deep: true

 mounted() {
    this.yourMethod();
    // re-render any time a prop changes
    Object.keys(this.$options.props).forEach(key => {
      this.$watch(key, this.yourMethod);
    });
  },

send Content-Type: application/json post with node.js

Using request with headers and post.

var options = {
            headers: {
                  'Authorization': 'AccessKey ' + token,
                  'Content-Type' : 'application/json'
            },
            uri: 'https://myurl.com/param' + value',
            method: 'POST',
            json: {'key':'value'}
 };
      
 request(options, function (err, httpResponse, body) {
    if (err){
         console.log("Hubo un error", JSON.stringify(err));
    }
    //res.status(200).send("Correcto" + JSON.stringify(body));
 })

Accessing elements of Python dictionary by index

You can use mydict['Apple'].keys()[0] in order to get the first key in the Apple dictionary, but there's no guarantee that it will be American. The order of keys in a dictionary can change depending on the contents of the dictionary and the order the keys were added.

How do I expand the output display to see more columns of a pandas DataFrame?

None of these answers were working for me. A couple of them would indeed print all the columns, but it would look sloppy. As in all the information was there, but it wasn't formatted correctly. I'm using a terminal inside of Neovim so I suspect that to be the reason.

This mini function does exactly what I need, just change df_data in the two places it is for your dataframe name (col_range is set to what pandas naturally shows, for me it is 5 but it could be bigger or smaller for you).

import math
col_range = 5
for _ in range(int(math.ceil(len(df_data.columns)/col_range))):
    idx1 = _*col_range
    idx2 = idx1+col_range
    print(df_data.iloc[:, idx1:idx2].describe())

Pycharm/Python OpenCV and CV2 install error

Try this. I am using Jupyter notebook (OS: Ubuntu 16.04 LTS on Google Cloud Platform + on Windows). Executed following command in the Jupyter notebook to install opencv:

!pip install opencv-contrib-python    #working on both Windows and Ubuntu

After successful installation you will get following message:

Successfully installed opencv-contrib-python-4.1.0.25

Now restart the kernel and try to import opencv as:

import cv2

The same command can be used to installed opencv on Windows as well.

SOLUTION 2: try following commands to install opencv: For Ubuntu: Run following command from terminal:

sudo apt-get install libsm6 libxrender1 libfontconfig1

Restart Jupyter notebook kernel and execute following command:

!pip install opencv-contrib-python

NOTE: You can run all the above commands from the terminal as well without using '!'.

How to get distinct values from an array of objects in JavaScript?

var unique = array
    .map(p => p.age)
    .filter((age, index, arr) => arr.indexOf(age) == index)
    .sort(); // sorting is optional

// or in ES6

var unique = [...new Set(array.map(p => p.age))];

// or with lodash

var unique = _.uniq(_.map(array, 'age'));

ES6 example

const data = [
  { name: "Joe", age: 17}, 
  { name: "Bob", age: 17}, 
  { name: "Carl", age: 35}
];

const arr = data.map(p => p.age); // [17, 17, 35]
const s = new Set(arr); // {17, 35} a set removes duplications, but it's still a set
const unique = [...s]; // [17, 35] Use the spread operator to transform a set into an Array
// or use Array.from to transform a set into an array
const unique2 = Array.from(s); // [17, 35]

How do I rename all folders and files to lowercase on Linux?

This works if you already have or set up the rename command (e.g. through brew install in Mac):

rename --lower-case --force somedir/*

Is it possible to start a shell session in a running container (without ssh)

No. This is not possible. Use something like supervisord to get an ssh server if that's needed. Although, I definitely question the need.

How do I correctly clone a JavaScript object?

(The following was mainly an integration of @Maciej Bukowski, @A. Levy, @Jan Turon, @Redu's answers, and @LeviRoberts, @RobG's comments, many thanks to them!!!)

Deep copy? — YES! (mostly);
Shallow copy? — NO! (except Proxy).

I sincerely welcome everyone to test clone().
In addition, defineProp() is designed to easily and quickly (re)define or copy any type of descriptor.

Function

"use strict"
function clone(object) {
  /*
    Deep copy objects by value rather than by reference,
    exception: `Proxy`
  */

  const seen = new WeakMap()

  return clone(object)


  function clone(object) {
    if (object !== Object(object)) return object /*
    —— Check if the object belongs to a primitive data type */

    if (object instanceof Node) return object.cloneNode(true) /*
    —— Clone DOM trees */

    let _object // The clone of object

    switch (object.constructor) {
      case Array:
      case Object:
        _object = cloneObject(object)
        break

      case Date:
        _object = new Date(+object)
        break

      case Function:
        const fnStr = String(object)

        _object = new Function("return " +
          (/^(?!function |[^{]+?=>)[^(]+?\(/.test(fnStr)
            ? "function " : ""
          ) + fnStr
        )()

        copyPropDescs(_object, object)
        break

      case RegExp:
        _object = new RegExp(object)
        break

      default:
        switch (Object.prototype.toString.call(object.constructor)) {
          //                              // Stem from:
          case "[object Function]":       // `class`
          case "[object Undefined]":      // `Object.create(null)`
            _object = cloneObject(object)
            break

          default:                        // `Proxy`
            _object = object
        }
    }

    return _object
  }


  function cloneObject(object) {
    if (seen.has(object)) return seen.get(object) /*
    —— Handle recursive references (circular structures) */

    const _object = Array.isArray(object)
      ? []
      : Object.create(Object.getPrototypeOf(object)) /*
        —— Assign [[Prototype]] for inheritance */

    seen.set(object, _object) /*
    —— Make `_object` the associative mirror of `object` */

    Reflect.ownKeys(object).forEach(key =>
      defineProp(_object, key, { value: clone(object[key]) }, object)
    )

    return _object
  }


  function copyPropDescs(target, source) {
    Object.defineProperties(target,
      Object.getOwnPropertyDescriptors(source)
    )
  }
}


function defineProp(object, key, descriptor = {}, copyFrom = {}) {
  const { configurable: _configurable, writable: _writable }
    = Object.getOwnPropertyDescriptor(object, key)
    || { configurable: true, writable: true }

  const test = _configurable // Can redefine property
    && (_writable === undefined || _writable) // Can assign to property

  if (!test || arguments.length <= 2) return test

  const basisDesc = Object.getOwnPropertyDescriptor(copyFrom, key)
    || { configurable: true, writable: true } // Custom…
    || {}; // …or left to native default settings

  ["get", "set", "value", "writable", "enumerable", "configurable"]
    .forEach(attr =>
      descriptor[attr] === undefined &&
      (descriptor[attr] = basisDesc[attr])
    )

  const { get, set, value, writable, enumerable, configurable }
    = descriptor

  return Object.defineProperty(object, key, {
    enumerable, configurable, ...get || set
      ? { get, set } // Accessor descriptor
      : { value, writable } // Data descriptor
  })
}

// Tests

"use strict"
const obj0 = {
  u: undefined,
  nul: null,
  t: true,
  num: 9,
  str: "",
  sym: Symbol("symbol"),
  [Symbol("e")]: Math.E,
  arr: [[0], [1, 2]],
  d: new Date(),
  re: /f/g,
  get g() { return 0 },
  o: {
    n: 0,
    o: { f: function (...args) { } }
  },
  f: {
    getAccessorStr(object) {
      return []
        .concat(...
          Object.values(Object.getOwnPropertyDescriptors(object))
            .filter(desc => desc.writable === undefined)
            .map(desc => Object.values(desc))
        )
        .filter(prop => typeof prop === "function")
        .map(String)
    },
    f0: function f0() { },
    f1: function () { },
    f2: a => a / (a + 1),
    f3: () => 0,
    f4(params) { return param => param + params },
    f5: (a, b) => ({ c = 0 } = {}) => a + b + c
  }
}

defineProp(obj0, "s", { set(v) { this._s = v } })
defineProp(obj0.arr, "tint", { value: { is: "non-enumerable" } })
obj0.arr[0].name = "nested array"


let obj1 = clone(obj0)
obj1.o.n = 1
obj1.o.o.g = function g(a = 0, b = 0) { return a + b }
obj1.arr[1][1] = 3
obj1.d.setTime(+obj0.d + 60 * 1000)
obj1.arr.tint.is = "enumerable? no"
obj1.arr[0].name = "a nested arr"
defineProp(obj1, "s", { set(v) { this._s = v + 1 } })
defineProp(obj1.re, "multiline", { value: true })

console.log("\n\n" + "-".repeat(2 ** 6))




console.log(">:>: Test - Routinely")

console.log("obj0:\n ", JSON.stringify(obj0))
console.log("obj1:\n ", JSON.stringify(obj1))
console.log()

console.log("obj0:\n ", obj0)
console.log("obj1:\n ", obj1)
console.log()

console.log("obj0\n ",
  ".arr.tint:", obj0.arr.tint, "\n ",
  ".arr[0].name:", obj0.arr[0].name
)
console.log("obj1\n ",
  ".arr.tint:", obj1.arr.tint, "\n ",
  ".arr[0].name:", obj1.arr[0].name
)
console.log()

console.log("Accessor-type descriptor\n ",
  "of obj0:", obj0.f.getAccessorStr(obj0), "\n ",
  "of obj1:", obj1.f.getAccessorStr(obj1), "\n ",
  "set (obj0 & obj1) .s :", obj0.s = obj1.s = 0, "\n ",
  "  ? (obj0 , obj1) ._s:", obj0._s, ",", obj1._s
)

console.log("—— obj0 has not been interfered.")

console.log("\n\n" + "-".repeat(2 ** 6))




console.log(">:>: Test - Circular structures")

obj0.o.r = {}
obj0.o.r.recursion = obj0.o
obj0.arr[1] = obj0.arr

obj1 = clone(obj0)
console.log("obj0:\n ", obj0)
console.log("obj1:\n ", obj1)

console.log("Clear obj0's recursion:",
  obj0.o.r.recursion = null, obj0.arr[1] = 1
)
console.log(
  "obj0\n ",
  ".o.r:", obj0.o.r, "\n ",
  ".arr:", obj0.arr
)
console.log(
  "obj1\n ",
  ".o.r:", obj1.o.r, "\n ",
  ".arr:", obj1.arr
)
console.log("—— obj1 has not been interfered.")


console.log("\n\n" + "-".repeat(2 ** 6))




console.log(">:>: Test - Classes")

class Person {
  constructor(name) {
    this.name = name
  }
}

class Boy extends Person { }
Boy.prototype.sex = "M"

const boy0 = new Boy
boy0.hobby = { sport: "spaceflight" }

const boy1 = clone(boy0)
boy1.hobby.sport = "superluminal flight"

boy0.name = "one"
boy1.name = "neo"

console.log("boy0:\n ", boy0)
console.log("boy1:\n ", boy1)
console.log("boy1's prototype === boy0's:",
  Object.getPrototypeOf(boy1) === Object.getPrototypeOf(boy0)
)

References

  1. Object.create() | MDN
  2. Object.defineProperties() | MDN
  3. Enumerability and ownership of properties | MDN
  4. TypeError: cyclic object value | MDN

Language tricks used

  1. Conditionally add prop to object

String is immutable. What exactly is the meaning?

An immutable object is an object whose state cannot be modified after it is created.

So a = "ABC" <-- immutable object. "a" holds reference to the object. And, a = "DEF" <-- another immutable object, "a" holds reference to it now.

Once you assign a string object, that object can not be changed in memory.

In summary, what you did is to change the reference of "a" to a new string object.

What is sharding and why is it important?

In my opinion the application tier should have no business determining where data should be stored

This is a good rule but like most things not always correct.

When you do your architecture you start with responsibilities and collaborations. Once you determine your functional architecture, you have to balance the non-functional forces.

If one of these non-functional forces is massive scalability, you have to adapt your architecture to cater for this force even if it means that your data storage abstraction now leaks into your application tier.

How to find the Vagrant IP?

run:

vagrant ssh-config > .ssh.config

and then in config/deploy.rb

role :web, "default"     
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo

# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'

Count number of rows within each group

You can use by functions as by(df1$Year, df1$Month, count) that will produce a list of needed aggregation.

The output will look like,

df1$Month: Feb
     x freq
1 2012    1
2 2013    1
3 2014    5
--------------------------------------------------------------- 
df1$Month: Jan
     x freq
1 2012    5
2 2013    2
--------------------------------------------------------------- 
df1$Month: Mar
     x freq
1 2012    1
2 2013    3
3 2014    2
> 

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

What's the difference between %s and %d in Python string formatting?

%s is used as a placeholder for string values you want to inject into a formatted string.

%d is used as a placeholder for numeric or decimal values.

For example (for python 3)

print ('%s is %d years old' % ('Joe', 42))

Would output

Joe is 42 years old

How do I put variable values into a text string in MATLAB?

I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.

    >> a=['matlab','is','fun']

a =

matlabisfun

>> size(a)

ans =

     1    11

In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.

To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.

>> a={'matlab','is','fun'}

a = 

    'matlab'    'is'    'fun'

>> size(a)

ans =

     1     3

How to convert Json array to list of objects in c#

Your data structure and your JSON do not match.

Your JSON is this:

{
    "JsonValues":{
        "id": "MyID",
        ...
    }
}

But the data structure you try to serialize it to is this:

class ValueSet
{
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    ...
}

You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.

Also inside your class your JSON is this:

"values": { ... }

Your data structure is this:

[JsonProperty("values")]
public List<Value> values
{
    get;
    set;
}

Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.

Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.

If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:

{
    "id": "MyID",

     "values": [
         {
            "id": "100",
            "diaplayName": "MyValue1"
         }, {
            "id": "200",
            "diaplayName": "MyValue2"
         }
     ]
}

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.

FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment

MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4 package.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

        @Override
        public int getCount() {
            return 5;
        }       
    }
}

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

first_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_dark" >

    <TextView
        android:id="@+id/tvFragFirst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />
</RelativeLayout>

SecondFragment.java

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

second_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_dark" >

    <TextView
        android:id="@+id/tvFragSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

ThirdFragment.java

public class ThirdFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragThird);      
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

third_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light" >

    <TextView
        android:id="@+id/tvFragThird"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

On OS X I realised, that while cv2.imread can deal with "filename.jpg" it can not process "file.name.jpg". Being a novice to python, I can't yet propose a solution, but as François Leblanc wrote, it is more of a silent imread error.

So it has a problem with an additional dot in the filename and propabely other signs as well, as with " " (Space) or "%" and so on.

How to redirect cin and cout to files?

If your input file is in.txt, you can use freopen to set stdin file as in.txt

freopen("in.txt","r",stdin);

if you want to do the same with your output:

freopen("out.txt","w",stdout);

this will work for std::cin (if using c++), printf, etc...

This will also help you in debugging your code in clion, vscode

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

How to get element's width/height within directives and component?

For a bit more flexibility than with micronyks answer, you can do it like that:

1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

<p #myIdentifier>
  my-component works!
</p>

2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}

Security

About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

Disable Laravel's Eloquent timestamps

Eloquent Model:

class User extends Model    
{      
    protected $table = 'users';

    public $timestamps = false;
}

Or Simply try this

$users = new Users();
$users->timestamps = false;
$users->name = 'John Doe';
$users->email = '[email protected]';
$users->save();

Loading an image to a <img> from <input file>

Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.

* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)

Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)

Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

More about the question:

"When Html.RenderPartial() is called with just the name of the partial view, ASP.NET MVC will pass to the partial view the same Model and ViewData dictionary objects used by the calling view template."

“NerdDinner” from Professional ASP.NET MVC 1.0

Alter table add multiple columns ms sql

this should work in T-SQL

ALTER TABLE Countries  ADD
HasPhotoInReadyStorage  bit,  
HasPhotoInWorkStorage  bit,  
HasPhotoInMaterialStorage bit,  
HasText  bit GO

http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx

What is the best way to give a C# auto-property an initial value?

Use the constructor because "When the constructor is finished, Construction should be finished". properties are like states your classes hold, if you had to initialize a default state, you would do that in your constructor.

How to use function srand() with time.h?

#include"stdio.h"//rmv coding for randam number access

#include"conio.h"

#include"time.h"

void main()
{
    time_t t;
    int rmvivek;

    srand(time(&t));
    rmvivek=1;

    while(rmvivek<=5)
    {
        printf("%c\t",rand()%10);
        rmvivek++;
    }
    getch();
}

How to iterate a loop with index and element in Swift

I found this answer while looking for a way to do that with a Dictionary, and it turns out it's quite easy to adapt it, just pass a tuple for the element.

// Swift 2

var list = ["a": 1, "b": 2]

for (index, (letter, value)) in list.enumerate() {
    print("Item \(index): \(letter) \(value)")
}

Is there a way to 'pretty' print MongoDB shell output to a file?

Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js and your database is foo, it would look like this:

./mongo foo find.js >> out.json

How do I reload a page without a POSTDATA warning in Javascript?

I've written a function that will reload the page without post submission and it will work with hashes, too.

I do this by adding / modifying a GET parameter in the URL called reload by updating its value with the current timestamp in ms.

var reload = function () {
    var regex = new RegExp("([?;&])reload[^&;]*[;&]?");
    var query = window.location.href.split('#')[0].replace(regex, "$1").replace(/&$/, '');
    window.location.href =
        (window.location.href.indexOf('?') < 0 ? "?" : query + (query.slice(-1) != "?" ? "&" : ""))
        + "reload=" + new Date().getTime() + window.location.hash;
};

Keep in mind, if you want to trigger this function in a href attribute, implement it this way: href="javascript:reload();void 0;" to make it work, successfully.

The downside of my solution is it will change the URL, so this "reload" is not a real reload, instead it's a load with a different query. Still, it could fit your needs like it does for me.

Minimum and maximum value of z-index?

My tests show that z-index: 2147483647 is the maximum value, tested on FF 3.0.1 for OS X. I discovered a integer overflow bug: if you type z-index: 2147483648 (which is 2147483647 + 1) the element just goes behind all other elements. At least the browser doesn't crash.

And the lesson to learn is that you should beware of entering too large values for the z-index property because they wrap around.

How to prune local tracking branches that do not exist on remote anymore

There doesn't seem to be a safe one-liner, too many edge cases (like a branch having "master" as part of its name, etc). Safest is these steps:

  1. git branch -vv | grep 'gone]' > stale_branches.txt
  2. view the file and remove lines for branches you want to keep (such as master branch!); you don't need to edit the contents of any line
  3. awk '{print $1}' stale_branches.txt | xargs git branch -d

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

Regular Expressions: Is there an AND operator?

Is it not possible in your case to do the AND on several matching results? in pseudocode

regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...

Bootstrap 3 Horizontal and Vertical Divider

The <hr> should be placed inside a <div> for proper functioning.

Place it like this to get desired width `

<div class='row'>
        <div class='col-lg-8 col-lg-offset-2'>
        <hr>
       </div>
       </div>

`

Hope this helps a future reader!

How can you get the Manifest Version number from the App's (Layout) XML variables?

Easiest solution is to use BuildConfig.

I use BuildConfig.VERSION_NAME in my application.

You can also use BuildConfig.VERSION_CODE to get version code.

Programmatically scroll to a specific position in an Android ListView

For a SmoothScroll with Scroll duration:

getListView().smoothScrollToPositionFromTop(position,offset,duration);

Parameters
position -> Position to scroll to
offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished
duration-> Number of milliseconds to use for the scroll

Note: From API 11.

HandlerExploit's answer was what I was looking for, but My listview is quite lengthy and also with alphabet scroller. Then I found that the same function can take other parameters as well :)


Edit:(From AFDs suggestion)

To position the current selection:

int h1 = mListView.getHeight();
int h2 = listViewRow.getHeight();

mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);  

Edit and replay XHR chrome/firefox etc?

Chrome now has Copy as fetch in version 67:

Copy as fetch

Right-click a network request then select Copy > Copy As Fetch to copy the fetch()-equivalent code for that request to your clipboard.

https://developers.google.com/web/updates/2018/04/devtools#fetch

Sample output:

fetch("https://stackoverflow.com/posts/validate-body", {
  credentials: "include",
  headers: {},
  referrer: "https://stackoverflow.com/",
  referrerPolicy: "origin",
  body:
    "body=Chrome+now+has+_Copy+as+fetch_+in+version+67%3A%0A%0A%3E+Copy+as+fetch%0ARight-click+a+network+request+then+select+**Copy+%3E+Copy+As+Fetch**+to+copy+the+%60fetch()%60-equivalent+code+for+that+request+to+your+clipboard.%0A%0A&oldBody=&isQuestion=false",
  method: "POST",
  mode: "cors"
});

The difference is that Copy as cURL will also include all the request headers (such as Cookie and Accept) and is suitable for replaying the request outside of Chrome. The fetch() code is suitable for replaying inside of the same browser.

Get the first N elements of an array?

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);

jquery 3.0 url.indexOf error

Update all your code that calls load function like,

$(window).load(function() { ... });

To

$(window).on('load', function() { ... });

jquery.js:9612 Uncaught TypeError: url.indexOf is not a function

This error message comes from jQuery.fn.load function.

I've come across the same issue on my application. After some digging, I found this statement in jQuery blog,

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

I simply just change how my jQuery objects call the load function like above. And everything works as expected.

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

How to check if a file exists in a folder?

Since nobody said how to check if the file exists AND get the current folder the executable is in (Working Directory):

if (File.Exists(Directory.GetCurrentDirectory() + @"\YourFile.txt")) {
                //do stuff
}

The @"\YourFile.txt" is not case sensitive, that means stuff like @"\YoUrFiLe.txt" and @"\YourFile.TXT" or @"\yOuRfILE.tXt" is interpreted the same.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

Importing json file in TypeScript

Another way to go

const data: {[key: string]: any} = require('./data.json');

This was you still can define json type is you want and don't have to use wildcard.

For example, custom type json.

interface User {
  firstName: string;
  lastName: string;
  birthday: Date;
}
const user: User = require('./user.json');

PDOException “could not find driver”

Had the same issue, because I forgot to go into my virtual machine. If I go to my local directory like this:

cd /www/homestead/my_project
php artisan migrate

that error will appear. But it works on my virtual machine

cd ~/homestead
vagrant ssh   
cd /www/homestead/my_project
php artisan migrate

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

It seems like a bug in Safari's cache handling policies.

Workaround in apache:

Header unset ETag
Header unset Last-Modified

Axios Delete request with body and headers?

Actually, axios.delete supports a request body.
It accepts two parameters: a URL and an optional config. That is...

axios.delete(url: string, config?: AxiosRequestConfig | undefined)

You can do the following to set the response body for the delete request:

let config = { 
    headers: {
        Authorization: authToken
    },
    data: { //! Take note of the `data` keyword. This is the request body.
        key: value,
        ... //! more `key: value` pairs as desired.
    } 
}

axios.delete(url, config)

I hope this helps someone!

How do I get whole and fractional parts from double in JSP/Java?

double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

How do I programmatically set the value of a select box element using JavaScript?

Suppose your form is named form1:

function selectValue(val)
{
  var lc = document.form1.leaveCode;
  for (i=0; i&lt;lc.length; i++)
  {
    if (lc.options[i].value == val)
    {
        lc.selectedIndex = i;
        return;
    }
  }
}

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.

Just type COMMIT and execute it F5

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

Do conditional INSERT with SQL?

I dont know about SmallSQL, but this works for MSSQL:

IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
    INSERT INTO Table1 VALUES (...)

Based on the where-condition, this updates the row if it exists, else it will insert a new one.

I hope that's what you were looking for.

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

Html code as IFRAME source rather than a URL

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

How to get cumulative sum

Try this

select 
    t.id,
    t.SomeNumt, 
    sum(t.SomeNumt) Over (Order by t.id asc Rows Between Unbounded Preceding and Current Row) as cum
from 
    @t t 
group by
    t.id,
    t.SomeNumt
order by
    t.id asc;