Programs & Examples On #Html.beginform

Writes an opening
tag to the response. When the user submits the form, the request will be processed by an action method.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Posting form to different MVC post action depending on the clicked submit button

BEST ANSWER 1:

ActionNameSelectorAttribute mentioned in

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

Second Approach

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

Third Approach: Client Script

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

MVC 4 - Return error message from Controller - Show in View

Thanks for all the replies.

I was able to solve this by doing the following:

CONTROLLER:

[HttpPost]       
public ActionResult form_edit(FormModels model)
{
  model.error_msg = model.update_content(model);
  return RedirectToAction("Form_edit", "Form", model);
}

public ActionResult form_edit(FormModels model, string searchString,string id)
{
  string test = model.selectedvalue;
  var bal = new FormModels();
  bal.Countries = bal.get_contentdetails(searchString);
  bal.selectedvalue = id;
  bal.dd_text = "content_name";
  bal.dd_value = "content_id";

  test = model.error_msg;
  ViewBag.head = "Heading";

  if (model.error_msg != null)
  {
    ModelState.AddModelError("error_msg", test);
  }

  model.error_msg = "";
  return View(bal);
}   

VIEW:

@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
  <table>
    <tr>
      <td>
        @ViewBag.error
        @Html.ValidationMessage("error_msg")
      </td>
    </tr>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
      </th>
    </tr>
  </table>
}

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Pass values of checkBox to controller action in asp.net mvc4

None of the previous solutions worked for me. Finally I found that the action should be coded as:

public ActionResult Index(string MyCheck = null)

and then, when checked the passed value was "on", not "true". Else, it is always null.

Hope it helps somebody!

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

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";?

MVC 4 Razor File Upload

I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.

File properties you can find here:

MVC3 How to check if HttpPostedFileBase is an image

For example ImageApi:

[HttpPost]
[Route("api/image")]  
public ActionResult Index(HttpPostedFileBase file)  
{  
    if (file != null && file.ContentLength > 0)  
        try 
        {  
            string path = Path.Combine(Server.MapPath("~/Images"),  
               Path.GetFileName(file.FileName));

            file.SaveAs(path);  
            ViewBag.Message = "Your message for success";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = "ERROR:" + ex.Message.ToString();  
        }  
    else 
    {  
        ViewBag.Message = "Please select file";  
    }  
    return View();  
}

Hope it help.

MVC 4 client side validation not working

There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:

@using (Html.BeginForm())
{
    ...
    @Html.TextBoxFor(x => x.AgreementNumber)
}

Also I don't know what the jquery.validate.inline.js script is but if it somehow depends on the jquery.validate.js plugin make sure that it is referenced after it.

In all cases look at your javascript console in the browser for potential errors or missing scripts.

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

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

your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript

You could also just wrap that in a form and have hidden fields for id, productid, and unitrate

Here's a sample for ya.

HTML

<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate"  href="/someurl?quantity=1">click me</a>

JS

function changeUrl(){
   var url = document.getElementById("imgUpdate").getAttribute('href');
   var inputValue = document.getElementById('ss').value;
   var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
    url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}

    function GiveMeTheQueryStringParameterValue(parameterName, input) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
    var results = regex.exec(input);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

this could be cleaned up and expanded as you need it but the example works

C# ASP.NET MVC Return to Previous Page

Here is just another option you couold apply for ASP NET MVC.

Normally you shoud use BaseController class for each Controller class.

So inside of it's constructor method do following.

public class BaseController : Controller
{
        public BaseController()
        {
            // get the previous url and store it with view model
            ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
        }
}

And now in ANY view you can do like

<button class="btn btn-success mr-auto" onclick="  window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>

Enjoy!

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

An item with the same key has already been added

I have had the same error. When i check the code then i found that declare "GET" request in my angular (font-end) side and declare "POST" request in the ASP.net (back-end) side. Set POST/GET any one in both side. Then solved the error.

Two models in one view in ASP MVC 3

If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...

public class EditViewModel
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

Many people use AutoMapper to map from their domain objects to their flat views.

The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.

MVC 3 file upload and model binding

1st download jquery.form.js file from below url

http://plugins.jquery.com/form/

Write below code in cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
    <div id="uploadTemplate">

        <input type="text" value="Asif" id="txtname" name="txtName" />


        <div id="dvAddTemplate">
            Add Template
            <br />
            <input type="file" name="file" id="file" tabindex="2" />
            <br />
            <input type="submit" value="Submit" />
            <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
        </div>

        <div id="TemplateTree" style="overflow-x: auto;"></div>
    </div>

    <div id="progressBarDiv" style="display: none;">
        <img id="loading-image" src="~/Images/progress-loader.gif" />
    </div>

}


<script type="text/javascript">

    $(document).ready(function () {
        debugger;
        alert('sample');
        var status = $('#status');
        $('#frmTemplateUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {
                    //$("#uploadTemplate").hide();
                    $("#btnAction").hide();
                    $("#progressBarDiv").show();
                    //progress_run_id = setInterval(progress, 300);
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {
                        //clearInterval(progress_run_id);
                        $("#uploadTemplate").show();
                        $("#btnAction").show();
                        $("#progressBarDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });

    });


</script>

Action method :-

 public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

 public void Upload(HttpPostedFileBase file, string txtname )
        {

            try
            {
                string attachmentFilePath = file.FileName;
                string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);

           }
            catch (Exception ex)
            {

            }
        }

Multiple models in a view

Do I need to make another view which holds these 2 views?

Answer:No

Isn't there another way such as (without the BigViewModel):

Yes, you can use Tuple (brings magic in view having multiple model).

Code:

 @model Tuple<LoginViewModel, RegisterViewModel>


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
     @Html.TextBoxFor(tuple=> tuple.Item.Name)
     @Html.TextBoxFor(tuple=> tuple.Item.Email)
     @Html.PasswordFor(tuple=> tuple.Item.Password)
    }


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
     {
      @Html.TextBoxFor(tuple=> tuple.Item1.Email)
      @Html.PasswordFor(tuple=> tuple.Item1.Password)
     }

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

You can also fix this problem by adding to model (Entity Framework version >= 5)

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreationDate { get; set; }

How to add ID property to Html.BeginForm() in asp.net mvc?

May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.

@using (Html.BeginForm("Login", "Account", new {  ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))

Hope this can help somebody :)

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

I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:

ModelState.AddModelError(string.Empty, ex.Message);

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

Apply jQuery datepicker to multiple instances

I just had the same problem.

The correct way to use date pick is $('.my_class').datepicker(); but you need to make sure you don't assign the same ID to multiple datepickers.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Based on mkozicki answer I come up with a bit different solution. I still use ActionNameSelectorAttribute But I needed to handle two buttons 'Save' and 'Sync'. They do almost the same so I didn't want to have two actions.

attribute:

public class MultipleButtonActionAttribute : ActionNameSelectorAttribute
{        
    private readonly List<string> AcceptedButtonNames;

    public MultipleButtonActionAttribute(params string[] acceptedButtonNames)
    {
        AcceptedButtonNames = acceptedButtonNames.ToList();
    }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {            
        foreach (var acceptedButtonName in AcceptedButtonNames)
        {
            var button = controllerContext.Controller.ValueProvider.GetValue(acceptedButtonName);
            if (button == null)
            {
                continue;
            }                
            controllerContext.Controller.ControllerContext.RouteData.Values.Add("ButtonName", acceptedButtonName);
            return true;
        }
        return false;
    }
}

view

<input type="submit" value="Save" name="Save" />
<input type="submit" value="Save and Sync" name="Sync" />

controller

 [MultipleButtonAction("Save", "Sync")]
 public ActionResult Sync(OrgSynchronizationEditModel model)
 {
     var btn = this.RouteData.Values["ButtonName"];

I also want to point out that if actions do different things I would probably follow mkozicki post.

Html helper for <input type="file" />

Improved version of Paulius Zaliaduonis' answer:

In order to make the validation work properly I had to change the Model to:

public class ViewModel
{
      public HttpPostedFileBase File { get; set; }

        [Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
        public string FileName
        {
            get
            {
                if (File != null)
                    return File.FileName;
                else
                    return String.Empty;
            }
        }
}

and the view to:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.FileName)
}

This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.

How to handle checkboxes in ASP.NET MVC forms?

this is what i did to loose the double values when using the Html.CheckBox(...

Replace("true,false","true").Split(',')

with 4 boxes checked, unchecked, unchecked, checked it turns true,false,false,false,true,false into true,false,false,true. just what i needed

Html.BeginForm and adding properties

As part of htmlAttributes,e.g.

Html.BeginForm(
    action, controller, FormMethod.Post, new { enctype="multipart/form-data"})

Or you can pass null for action and controller to get the same default target as for BeginForm() without any parameters:

Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})

How can I reduce the waiting (ttfb) time

TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.

You need to look into what queries are being run and how the website connects to the server.

This article might help understand TTFB, but otherwise you need to dig deeper into your application.

Android draw a Horizontal line between views

----> Simple one

 <TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#c0c0c0"
    android:id="@+id/your_id"
    android:layout_marginTop="160dp" />

open the file upload dialogue box onclick the image

HTML Code:

 <form method="post" action="#" id="#">
<div class="form-group files color">
    <input type="file" class="form-control" multiple="">
</div>

CSS:

.files input {
outline: 2px dashed #92b0b3;
outline-offset: -10px;
-webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
transition: outline-offset .15s ease-in-out, background-color .15s linear;
padding: 120px 0px 85px 35%;
text-align: center !important;
margin: 0;
width: 100% !important;
height: 400px;

}

.files input:focus{    
    outline: 2px dashed #92b0b3; 
    outline-offset: -10px;
   -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear;
    transition: outline-offset .15s ease-in-out, background-color .15s linear;
  border:1px solid #92b0b3;

}

.files{ position:relative}
   .files:after {  pointer-events: none;
     position: absolute;
     top: 60px;
     left: 0;
    width: 50px;
   right: 0;
   height: 400px;
  content: "";
  background-image: url('../../images/');
  display: block;
  margin: 0 auto;
  background-size: 100%;
  background-repeat: no-repeat;

}

.color input{ background-color:#f1f1f1;}
.files:before {
  position: absolute;
  bottom: 10px;
   left: 0;  pointer-events: none;
  width: 100%;
  right: 0;
  height: 400px;
  display: block;
  margin: 0 auto;
  color: #2ea591;
  font-weight: 600;
  text-transform: capitalize;
  text-align: center;

}

Removing duplicates from a list of lists

This should work.

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

k_cleaned = []
for ele in k:
    if set(ele) not in [set(x) for x in k_cleaned]:
        k_cleaned.append(ele)
print(k_cleaned)

# output: [[1, 2], [4], [5, 6, 2], [3]]

Does JavaScript pass by reference?

Without purisms, I think that the best way to emulate scalar argument by reference in JavaScript is using object, like previous an answer tells.

However, I do a little bit different:

I've made the object assignment inside function call, so one can see the reference parameters near the function call. It increases the source readability.

In function declaration, I put the properties like a comment, for the very same reason: readability.

var r;

funcWithRefScalars(r = {amount:200, message:null} );
console.log(r.amount + " - " + r.message);


function funcWithRefScalars(o) {  // o(amount, message)
  o.amount  *= 1.2;
  o.message = "20% increase";
}

In the above example, null indicates clearly an output reference parameter.

The exit:

240 - 20% Increase

On the client-side, console.log should be replaced by alert.

? ? ?

Another method that can be even more readable:

var amount, message;

funcWithRefScalars(amount = [200], message = [null] );
console.log(amount[0] + " - " + message[0]);

function funcWithRefScalars(amount, message) {  // o(amount, message)
   amount[0]  *= 1.2;
   message[0] = "20% increase";
}

Here you don't even need to create new dummy names, like r above.

Excel concatenation quotes

easier answer - put the stuff in quotes in different cells and then concatenate them!

B1: rcrCheck.asp
C1: =D1&B1&E1
D1: "code in quotes" and "more code in quotes"  
E1: "

it comes out perfect (can't show you because I get a stupid dialog box about code)

easy peasy!!

How do I edit SSIS package files?

Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx

SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.

Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.

This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016

Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014

How to add a "open git-bash here..." context menu to the windows explorer?

What worked for me was almost this, but with the following REGEDIT path:
HKEY_LOCAL_MACHINE/SOFTWARE/Classes/Directory/background/shell and here I created the key Bash, with the value of what I want the display name to be, and then created another key under this named command with the value as the path to git-bash.exe

I'm on Windows 10 and have a fresh git install that didn't add this automatically for some reason (git version 2.12.0 64bit)

SQL Server - stop or break execution of a SQL script

I use RETURN here all the time, works in script or Stored Procedure

Make sure you ROLLBACK the transaction if you are in one, otherwise RETURN immediately will result in an open uncommitted transaction

How do I start a program with arguments when debugging?

My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.

Passing data to a jQuery UI Dialog

Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:

        buttons: {
            "Ja": function() {
                $.post(a.href);
                $(a). // code to remove the table row
                $("#dialog").dialog("close");
            },
            "Nej": function() { $(this).dialog("close"); }
        },

The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

S3 - Access-Control-Allow-Origin Header

fwuensche "answer" is corret to set up a CDN; doing this, i removed MaxAgeSeconds.

<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>

Combine two arrays

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in: http://php.net/manual/en/function.array-merge.php

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

Docker: Container keeps on restarting again on again

This could also be the case if you have created a systemd service that has:

[Service]
Restart=always
ExecStart=/usr/bin/docker container start -a my_container
ExecStop=/usr/bin/docker container stop -t 2 my_container

How to find the privileges and roles granted to a user in Oracle?

always make SQL re-usuable: -:)

-- ===================================================
-- &role_name will be "enter value for 'role_name'".
-- Date:  2015 NOV 11.

-- sample code:   define role_name=&role_name
-- sample code:   where role like '%&&role_name%'
-- ===================================================


define role_name=&role_name

select * from ROLE_ROLE_PRIVS where ROLE = '&&role_name';
select * from ROLE_SYS_PRIVS  where ROLE = '&&role_name';


select role, privilege,count(*)
 from ROLE_TAB_PRIVS
where ROLE = '&&role_name'
group by role, privilege
order by role, privilege asc
;

How to get the height of a body element

$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

Best Regular Expression for Email Validation in C#

First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email)
{
    try {
        var mail = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

NSDate get year/month/day

As of iOS 8.0 (and OS X 10) you can use the component method to simplify getting a single date component like so:

int year = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];

Should make things simpler and hopefully this is implemented efficiently.

Using Python String Formatting with Lists

This was a fun question! Another way to handle this for variable length lists is to build a function that takes full advantage of the .format method and list unpacking. In the following example I don't use any fancy formatting, but that can easily be changed to suit your needs.

list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]

# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
    # Create a format spec for each item in the input `alist`.
    # E.g., each item will be right-adjusted, field width=3.
    format_list = ['{:>3}' for item in alist] 

    # Now join the format specs into a single string:
    # E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
    s = ','.join(format_list)

    # Now unpack the input list `alist` into the format string. Done!
    return s.format(*alist)

# Example output:
>>>ListToFormattedString(list_1)
'  1,  2,  3,  4,  5,  6'
>>>ListToFormattedString(list_2)
'  1,  2,  3,  4,  5,  6,  7,  8'

Android Image View Pinch Zooming

Custom zoom view in Kotlin

 import android.content.Context
 import android.graphics.Matrix
 import android.graphics.PointF
 import android.util.AttributeSet
 import android.util.Log
 import android.view.MotionEvent
 import android.view.ScaleGestureDetector
 import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
 import androidx.appcompat.widget.AppCompatImageView

 class ZoomImageview : AppCompatImageView {
var matri: Matrix? = null
var mode = NONE

// Remember some things for zooming
var last = PointF()
var start = PointF()
var minScale = 1f
var maxScale = 3f
lateinit var m: FloatArray
var viewWidth = 0
var viewHeight = 0
var saveScale = 1f
protected var origWidth = 0f
protected var origHeight = 0f
var oldMeasuredWidth = 0
var oldMeasuredHeight = 0
var mScaleDetector: ScaleGestureDetector? = null
var contex: Context? = null

constructor(context: Context) : super(context) {
    sharedConstructing(context)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    sharedConstructing(context)
}

private fun sharedConstructing(context: Context) {
    super.setClickable(true)
    this.contex= context
    mScaleDetector = ScaleGestureDetector(context, ScaleListener())
    matri = Matrix()
    m = FloatArray(9)
    imageMatrix = matri
    scaleType = ScaleType.MATRIX
    setOnTouchListener { v, event ->
        mScaleDetector!!.onTouchEvent(event)
        val curr = PointF(event.x, event.y)
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                last.set(curr)
                start.set(last)
                mode = DRAG
            }
            MotionEvent.ACTION_MOVE -> if (mode == DRAG) {
                val deltaX = curr.x - last.x
                val deltaY = curr.y - last.y
                val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale)
                val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale)
                matri!!.postTranslate(fixTransX, fixTransY)
                fixTrans()
                last[curr.x] = curr.y
            }
            MotionEvent.ACTION_UP -> {
                mode = NONE
                val xDiff = Math.abs(curr.x - start.x).toInt()
                val yDiff = Math.abs(curr.y - start.y).toInt()
                if (xDiff < CLICK && yDiff < CLICK) performClick()
            }
            MotionEvent.ACTION_POINTER_UP -> mode = NONE
        }
        imageMatrix = matri
        invalidate()
        true // indicate event was handled
    }
}

fun setMaxZoom(x: Float) {
    maxScale = x
}

private inner class ScaleListener : SimpleOnScaleGestureListener() {
    override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
        mode = ZOOM
        return true
    }

    override fun onScale(detector: ScaleGestureDetector): Boolean {
        var mScaleFactor = detector.scaleFactor
        val origScale = saveScale
        saveScale *= mScaleFactor
        if (saveScale > maxScale) {
            saveScale = maxScale
            mScaleFactor = maxScale / origScale
        } else if (saveScale < minScale) {
            saveScale = minScale
            mScaleFactor = minScale / origScale
        }
        if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matri!!.postScale(mScaleFactor, mScaleFactor, viewWidth / 2.toFloat(), viewHeight / 2.toFloat()) else matri!!.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY)
        fixTrans()
        return true
    }
}

fun fixTrans() {
    matri!!.getValues(m)
    val transX = m[Matrix.MTRANS_X]
    val transY = m[Matrix.MTRANS_Y]
    val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale)
    val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale)
    if (fixTransX != 0f || fixTransY != 0f) matri!!.postTranslate(fixTransX, fixTransY)
}

fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float {
    val minTrans: Float
    val maxTrans: Float
    if (contentSize <= viewSize) {
        minTrans = 0f
        maxTrans = viewSize - contentSize
    } else {
        minTrans = viewSize - contentSize
        maxTrans = 0f
    }
    if (trans < minTrans) return -trans + minTrans
    if (trans > maxTrans) return -trans + maxTrans
    return 0f
}

fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
    if (contentSize <= viewSize) {
        return 0f
    } else {
        return delta
    }
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    viewWidth = MeasureSpec.getSize(widthMeasureSpec)
    viewHeight = MeasureSpec.getSize(heightMeasureSpec)
    //
    // Rescales image on rotation
    //
    if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return
    oldMeasuredHeight = viewHeight
    oldMeasuredWidth = viewWidth
    if (saveScale == 1f) {
        //Fit to screen.
        val scale: Float
        val drawable = drawable
        if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return
        val bmWidth = drawable.intrinsicWidth
        val bmHeight = drawable.intrinsicHeight
        Log.d("bmSize", "bmWidth: $bmWidth bmHeight : $bmHeight")
        val scaleX = viewWidth.toFloat() / bmWidth.toFloat()
        val scaleY = viewHeight.toFloat() / bmHeight.toFloat()
        scale = Math.min(scaleX, scaleY)
        matri!!.setScale(scale, scale)
        // Center the image
        var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat()
        var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat()
        redundantYSpace /= 2.toFloat()
        redundantXSpace /= 2.toFloat()
        matri!!.postTranslate(redundantXSpace, redundantYSpace)
        origWidth = viewWidth - 2 * redundantXSpace
        origHeight = viewHeight - 2 * redundantYSpace
        imageMatrix = matri
    }
    fixTrans()
}

companion object {
    // We can be in one of these 3 states
    const val NONE = 0
    const val DRAG = 1
    const val ZOOM = 2
    const val CLICK = 3
}
 }

Work on a remote project with Eclipse via SSH

I tried ssh -X but it was unbearably slow.

I also tried RSE, but it didn't even support building the project with a Makefile (I'm being told that this has changed since I posted my answer, but I haven't tried that out)

I read that NX is faster than X11 forwarding, but I couldn't get it to work.

Finally, I found out that my server supports X2Go (the link has install instructions if yours does not). Now I only had to:

  • download and unpack Eclipse on the server,
  • install X2Go on my local machine (sudo apt-get install x2goclient on Ubuntu),
  • configure the connection (host, auto-login with ssh key, choose to run Eclipse).

Everything is just as if I was working on a local machine, including building, debugging, and code indexing. And there are no noticeable lags.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

in activity used ContextCompat

ContextCompat.getColor(context, R.color.color_name)

in Adaper

private Context context;


context.getResources().getColor()

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;

or

char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);

will print

X
3626

Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How to copy part of an array to another array in C#?

int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

Laravel: How do I parse this json data in view blade?

The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.

First replace every \ with a double slash \\ and then every quote" with a \".

$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
  ->with('payload', $payload)

Then in the blade template

@if(isset($payload))
<script>
  window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif

This basically allows you to take an object on the php side, and then have an object on the javascript side.

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

What does IFormatProvider do?

IFormatProvider provides culture info to the method in question. DateTimeFormatInfo implements IFormatProvider, and allows you to specify the format you want your date/time to be displayed in. Examples can be found on the relevant MSDN pages.

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

I had this warning when had this in angular.json config:

"prefix": "app_ng"

When changed to "app" all worked perfectly fine.

How to Alter Constraint

You can not alter constraints ever but you can drop them and then recreate.

Have look on this

ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;

and then recreate it with ON DELETE CASCADE like this

ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
    ON DELETE CASCADE;

hope this help

How can I convert a stack trace to a string?

Print the stack trace to a PrintStream, then convert it to a String:

// ...

catch (Exception e)
{
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    e.printStackTrace(new PrintStream(out));
    String str = new String(out.toByteArray());

    System.out.println(str);
}

SQL Server IN vs. EXISTS Performance

Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.

  1. In the first, the correlated subquery will likely cause the subquery to be run for each row.
  2. In the second example, the subquery should only run once, since not correlated.
  3. In the second example, the IN will short-circuit as soon as it finds a match.

Radio Buttons "Checked" Attribute Not Working

You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)

Try this:

<form>
  <label>Do you want to accept American Express?</label>
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

Colors in JavaScript console

// log in color 
// consolelog({"color":"red","background-color":"blue"},1,2,3)

// consolelog({"color":"red"},1,2,3)
// consolelog(1,2,3)
function consolelog()
{
    var style=Array.prototype.slice.call(arguments,0,1)||["black"];
    var vars=(Array.prototype.slice.call(arguments,1)||[""])
    var message=vars.join(" ")
    var colors = 
        {
            warn:
                {
                    "background-color"  :"yellow",
                    "color"             :"red"
                },
            error:
                {
                    "background-color"  :"red",
                    "color"             :"yellow"
                },
            highlight:
                {
                    "background-color"  :"yellow",
                    "color"             :"black"
                },
            success : "green", 
            info    : "dodgerblue"  

        }
    var givenstyle=style[0];
    var colortouse= colors[givenstyle] || givenstyle;
    if(typeof colortouse=="object")
    {
        colortouse= printobject(colortouse)
    }
    if(colortouse)
    {
        colortouse=(colortouse.match(/\W/)?"":"color:")+colortouse;
    }
    function printobject(o){
        var str='';

        for(var p in o){
            if(typeof o[p] == 'string'){
                str+= p + ': ' + o[p]+'; \n';
            }else{
            str+= p + ': { \n' + print(o[p]) + '}';
            }
        }

        return str;
    }
    if(colortouse)
    {
        console.log("%c" + message, colortouse);
    }
    else
    {
        console.log.apply(null,vars);
    }
}
console.logc=consolelog;

How to lock orientation of one view controller to portrait mode only in Swift

For a new version of Swift try this

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

powershell mouse move does not prevent idle mode

There is an analog solution to this also. There's an android app called "Timeout Blocker" that vibrates at a set interval and you put your mouse on it. https://play.google.com/store/apps/details?id=com.isomerprogramming.application.timeoutblocker&hl=en

Volatile boolean vs AtomicBoolean

volatile keyword guarantees happens-before relationship among threads sharing that variable. It doesn't guarantee you that 2 or more threads won't interrupt each other while accessing that boolean variable.

How to style a JSON block in Github Wiki?

You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI

Sorting object property by values

Couln't find answer above that would both work and be SMALL, and would support nested objects (not arrays), so I wrote my own one :) Works both with strings and ints.

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

Usage:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }

Initialize class fields in constructor or at declaration?

I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to "initialize at declaration" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is "base" and another is the newly declared ones, and it cost me quite some time to debug.

The lesson: to initialize inherited fields, you'd do it inside of the constructor.

Make body have 100% of the browser height

Try

<html style="width:100%; height:100%; margin: 0; padding: 0;">
<body style="overflow:hidden; width:100%; height:100%; margin:0; padding:0;">

Change URL parameters

Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.

As requested -

Goto his test page here

In firebug enter the following into the console

jQuery.param.querystring(window.location.href, 'a=3&newValue=100');

It will return you the following amended url string

http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3

Notice the a querystring value for a has changed from X to 3 and it has added the new value.

You can then use the new url string however you wish e.g using document.location = newUrl or change an anchor link etc

Set a form's action attribute when submitting?

HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:

<button onclick="this.form.action='/PropertiesList';" 
    Account Details </button>

How do you properly use namespaces in C++?

In Java:

package somepackage;
class SomeClass {}

In C++:

namespace somenamespace {
    class SomeClass {}
}

And using them, Java:

import somepackage;

And C++:

using namespace somenamespace;

Also, full names are "somepackge.SomeClass" for Java and "somenamespace::SomeClass" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren't there though, so you can name your folders and classes independently off packages and namespaces.

How to disable javax.swing.JButton in java?

This works.

public class TestButton {

public TestButton() {
    JFrame f = new JFrame();
    f.setSize(new Dimension(200,200));
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout());

    final JButton stop = new JButton("Stop");
    final JButton start = new JButton("Start");
    p.add(start);
    p.add(stop);
    f.getContentPane().add(p);
    stop.setEnabled(false);
    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(true);
            stop.setEnabled(false);

        }
    });

    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            stop.setEnabled(true);

        }
    });
    f.setVisible(true);
}

/**
 * @param args
 */
public static void main(String[] args) {
    new TestButton();

}

}

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

Inner join vs Where

As kiewik said, the execution plan is the same.

The JOIN statement is only more easy to read, making it easier not to forget the ON condition and getting a cartesian product. These errors can be quite hard to detect in long queries using multiple joins of type : SELECT * FROM t1, t2 WHERE t1.id=t2.some_field.

If you forget only one join condition, you get a very long to execute query returning too many records... really too many. Some poeple use a DISTINCT to patch the query, but it's still very long to execute.

That's accurately why, using JOIN statement is surely the best practice : a better maintainability, and a better readability.

Further more, if I well remember, JOIN is optimized concerning memory usage.

Enabling/installing GD extension? --without-gd

For PHP7.0 use (php7.1-gd, php7.2-gd, php7.3-gd and php7.4-gd are also available):

sudo apt-get install php7.0-gd

and than restart your webserver.

enabling cross-origin resource sharing on IIS7

It took Microsoft years to identify the gaps and ship an out-of-band CORS module to solve this problem.

  1. Install the module from Microsoft
  2. Configure it with snippets

as below

<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">            
            <add origin="http://*" allowed="true" />
        </cors>
    </system.webServer>
</configuration>

In general, it is much easier than your custom headers and also offers better handling of preflight requests.

In case you need the same for IIS Express, use some PowerShell scripts I wrote.

How to disable Excel's automatic cell reference change after copy/paste?

Haven't check in Excel, but this works in Libreoffice4:

The whole thing of address rewriting comes during consecutive
(a1) cut
(a2) paste

You need to interrupt the consecutiveness by putting something in-between:
(b1) cut
(b2) select some empty cells (more than 1) and drag(move) them
(b3) paste

Step (b2) is where the cell that is about to update itself stops the tracking. Quick and simple.

What is the best IDE to develop Android apps in?

I Feel Eclipse IDE is more suitable for android applications rather than other IDEs. Because its providing us more than five perspectives which will make our project flexible and ease.You may try Eclipse ides starts with 3.6 and above will provide you better performance.

Eclipse_jee_indigo
Eclipse_java_indigo
Eclipse_classic

The above eclipses are belongs to the version3.7.2 which are all latest and supports all kind of access.

What’s the best way to check if a file exists in C++? (cross platform)

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

Combining node.js and Python

I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.

The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Excel VBA Automation Error: The object invoked has disconnected from its clients

I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

time.sleep -- sleeps thread or process?

It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:

import time
from threading import Thread

class worker(Thread):
    def run(self):
        for x in xrange(0,11):
            print x
            time.sleep(1)

class waiter(Thread):
    def run(self):
        for x in xrange(100,103):
            print x
            time.sleep(5)

def run():
    worker().start()
    waiter().start()

Which will print:

>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102

What's the difference between text/xml vs application/xml for webservice response

According to this article application/xml is preferred.


EDIT

I did a little follow-up on the article.

The author claims that the encoding declared in XML processing instructions, like:

<?xml version="1.0" encoding="UTF-8"?>

can be ignored when text/xml media type is used.

They support the thesis with the definition of text/* MIME type family specification in RFC 2046, specifically the following fragment:

4.1.2.  Charset Parameter

   A critical parameter that may be specified in the Content-Type field
   for "text/plain" data is the character set.  This is specified with a
   "charset" parameter, as in:

     Content-type: text/plain; charset=iso-8859-1

   Unlike some other parameter values, the values of the charset
   parameter are NOT case sensitive.  The default character set, which
   must be assumed in the absence of a charset parameter, is US-ASCII.

   The specification for any future subtypes of "text" must specify
   whether or not they will also utilize a "charset" parameter, and may
   possibly restrict its values as well.  For other subtypes of "text"
   than "text/plain", the semantics of the "charset" parameter should be
   defined to be identical to those specified here for "text/plain",
   i.e., the body consists entirely of characters in the given charset.
   In particular, definers of future "text" subtypes should pay close
   attention to the implications of multioctet character sets for their
   subtype definitions.

According to them, such difficulties can be avoided when using application/xml MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.

Remove gutter space for a specific div only

Since no one has mentioned this, to add to the no-gutter answer above which works, if you want custom spaced gutters, all you have to do is specify the value in px for the margin left and right properties, and padding left and right properties like so;

.row.no-gutter {
margin-left: 4px;
margin-right: 4px;
}

.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
padding-right: 4px;
padding-left: 4px;
}

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

How do I make an HTML text box show a hint when empty?

Simple Html 'required' tag is useful.

<form>
<input type="text" name="test" id="test" required>
<input type="submit" value="enter">
</form>

It specifies that an input field must be filled out before submitting the form or press the button submit. Here is example

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.

I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had same problem, and have the latest ver Microsoft Visual Studio Community 2017 Version 15.7.3

I just downloaded the latest SDK 2.1 and no more targeting issue. https://www.microsoft.com/net/download/thank-you/dotnet-sdk-2.1.301-windows-x64-installer

Info: Microsoft Visual Studio Community 2017 Version 15.7.3 VisualStudio.15.Release/15.7.3+27703.2026 Microsoft .NET Framework Version 4.7.03056

Installed Version: Community

C# Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

NuGet Package Manager 4.6.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info

ResourcePackage Extension 1.0 ResourcePackage Visual Studio Extension Detailed Info

Visual Basic Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Tools for Unity 3.7.0.1 Visual Studio Tools for Unity

Truncate Decimal number not Round Off

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

target="_blank" vs. target="_new"

The use of _New is useful when working on pages that are Iframed. Since target="_blank" doesn't do the trick and opens the page on the same iframe... target new is the best solution for Iframe Pages. Just my five cents.

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

React - Display loading screen while DOM is rendering?

I'm using react-progress-2 npm package, which is zero-dependency and works great in ReactJS.

https://github.com/milworm/react-progress-2

Installation:

npm install react-progress-2

Include react-progress-2/main.css to your project.

import "node_modules/react-progress-2/main.css";

Include react-progress-2 and put it somewhere in the top-component, for example:

import React from "react";
import Progress from "react-progress-2";

var Layout = React.createClass({
render: function() {
    return (
        <div className="layout">
            <Progress.Component/>
                {/* other components go here*/}
            </div>
        );
    }
});

Now, whenever you need to show an indicator, just call Progress.show(), for example:

loadFeed: function() {
    Progress.show();
    // do your ajax thing.
},

onLoadFeedCallback: function() {
    Progress.hide();
    // render feed.
}

Please note, that show and hide calls are stacked, so after n-consecutive show calls, you need to do n hide calls to hide an indicator or you can use Progress.hideAll().

can't load package: package .: no buildable Go source files

To resolve this for my situation:

I had to specify a more specific sub-package to install.

Wrong:

go get github.com/garyburd/redigo

Correct:

go get github.com/garyburd/redigo/redis

#pragma mark in Swift?

Add a to-do item: Insert a comment with the prefix TODO:. For example: // TODO: [your to-do item].

Add a bug fix reminder: Insert a comment with the prefix FIXME:. For example: // FIXME: [your bug fix reminder].

Add a heading: Insert a comment with the prefix MARK:. For example: // MARK: [your section heading].

Add a separator line: To add a separator above an annotation, add a hyphen (-) before the comment portion of the annotation. For example: // MARK: - [your content]. To add a separator below an annotation, add a hyphen (-) after the comment portion of the annotation. For example: // MARK: [your content] -.

Is Ruby pass by reference or by value?

The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):


Q1: What happens when you assign a new variable str to a value of 'foo'?

str = 'foo'
str.object_id # => 2000

enter image description here

A: A label called str is created that points at the object 'foo', which for the state of this Ruby interpreter happens to be at memory location 2000.


Q2: What happens when you assign the existing variable str to a new object using =?

str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002

enter image description here

A: The label str now points to a different object.


Q3: What happens when you assign a new variable = to str?

str2 = str
str2.object_id # => 2002

enter image description here

A: A new label called str2 is created that points at the same object as str.


Q4: What happens if the object referenced by str and str2 gets changed?

str2.replace 'baz'
str2 # => 'baz'
str  # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002

enter image description here

A: Both labels still point at the same object, but that object itself has mutated (its contents have changed to be something else).


How does this relate to the original question?

It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2) that gets passed in to it (str). It can't change which object the label str points to, but it can change the contents of the object that they both reference to contain else:

str = 'foo'

def mutate(str2)
  puts "str2: #{str2.object_id}"
  str2.replace 'bar'
  str2 = 'baz'
  puts "str2: #{str2.object_id}"
end

str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Updates were rejected because the tip of your current branch is behind its remote counterpart

This is how I solved my problem

Let's assume the upstream branch is the one that you forked from and origin is your repo and you want to send an MR/PR to the upstream branch.

You already have let's say about 4 commits and you are getting Updates were rejected because the tip of your current branch is behind.

Here is what I did

First, squash all your 4 commits

git rebase -i HEAD~4

You'll get a list of commits with pick written on them. (opened in an editor)

example

pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
pick c011a77 commit 4

to

pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
squash c011a77 commit 4

After that, you can save your combined commit

Next

You'll need to stash your commit

Here's how

git reset --soft HEAD~1
git stash

now rebase with your upstream branch

git fetch upstream beta && git rebase upstream/beta

Now pop your stashed commit

git stash pop

commit these changes and push them

git add -A
git commit -m "[foo] - foobar commit"
git push origin fix/#123 -f

OS specific instructions in CMAKE: How to?

Use

if (WIN32)
    #do something
endif (WIN32)

or

if (UNIX)
    #do something
endif (UNIX)

or

if (MSVC)
    #do something
endif (MSVC)

or similar

see CMake Useful Variables and CMake Checking Platform

How to call one shell script from another shell script?

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

Python: How do I make a subclass from a superclass?

# Initialize using Parent
#
class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

Or, even better, the use of Python's built-in function, super() (see the Python 2/Python 3 documentation for it) may be a slightly better method of calling the parent for initialization:

# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
    def __init__(self):
        super(MySubClassBetter, self).__init__()

Or, same exact thing as just above, except using the zero argument form of super(), which only works inside a class definition:

class MySubClassBetter(MySuperClass):
    def __init__(self):
        super().__init__()

Absolute vs relative URLs

In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

How to specify 64 bit integers in c

Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

REST API error code 500 handling

Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.

Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.

To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.

It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.

I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.

It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!

Print very long string completely in pandas dataframe

The way I often deal with the situation you describe is to use the .to_csv() method and write to stdout:

import sys

df.to_csv(sys.stdout)

Update: it should now be possible to just use None instead of sys.stdout with similar effect!

This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.

I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas

Heatmap in matplotlib with pcolor?

Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes object directly.

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)

# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)


ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

Hope that helps.

How can I read pdf in python?

You can USE PyPDF2 package

#install pyDF2
pip install PyPDF2

# importing all the required modules
import PyPDF2

# creating an object 
file = open('example.pdf', 'rb')

# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)

# print the number of pages in pdf file
print(fileReader.numPages)

Follow this Documentation http://pythonhosted.org/PyPDF2/

Loop through each row of a range in Excel

Something like this:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

How to make PDF file downloadable in HTML link?

Instead of linking to the .PDF file, instead do something like

<a href="pdf_server.php?file=pdffilename">Download my eBook</a>

which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value

Check if value exists in column in VBA

The find method of a range is faster than using a for loop to loop through all the cells manually.

here is an example of using the find method in vba

Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets("Sheet1").Range("A:A") 'searches all of column A
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Application.Goto Rng, True 'value found
        Else
            MsgBox "Nothing found" 'value not found
        End If
    End With
End If
End Sub

How to extract base URL from a string in JavaScript?

This, works for me:

_x000D_
_x000D_
var getBaseUrl = function (url) {_x000D_
  if (url) {_x000D_
    var parts = url.split('://');_x000D_
    _x000D_
    if (parts.length > 1) {_x000D_
      return parts[0] + '://' + parts[1].split('/')[0] + '/';_x000D_
    } else {_x000D_
      return parts[0].split('/')[0] + '/';_x000D_
    }_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

Using both Python 2.x and Python 3.x in IPython Notebook

I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.

Check if decimal value is null

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

Change type of varchar field to integer: "cannot be cast automatically to type integer"

this worked for me.

change varchar column to int

change_column :table_name, :column_name, :integer

got:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

chnged to

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

GridView sorting: SortDirection always Ascending

I don't know why everyone forgets about using hidden fields! They are so much "cheaper" than ViewState (which I have turned off since 2005). If you don't want to use Session or ViewState, then here is my solution:

Put these two hidden fields on your aspx page, and put the default sort you want for your data (I'm using LastName for example):

<asp:HiddenField ID="hfSortExpression" runat="server" Value="LastName" />
<asp:HiddenField ID="hfSortDirection" runat="server" Value="Ascending" />

Then put this helper code in your Base page (you have a base page don't you? If not, put in your .cs code behind).

/// <summary>
/// Since native ASP.Net GridViews do not provide accurate SortDirections, 
/// we must save a hidden field with previous sort Direction and Expression.
/// Put these two hidden fields on page and call this method in grid sorting event
/// </summary>
/// <param name="hfSortExpression">The hidden field on page that has the PREVIOUS column that is sorted on</param>
/// <param name="hfSortDirection">The hidden field on page that has the PREVIOUS sort direction</param>
protected SortDirection GetSortDirection(GridViewSortEventArgs e, HiddenField hfSortExpression, HiddenField hfSortDirection)
{
    //assume Ascending always by default!!
    SortDirection sortDirection = SortDirection.Ascending;

    //see what previous column (if any) was sorted on
    string previousSortExpression = hfSortExpression.Value;
    //see what previous sort direction was used
    SortDirection previousSortDirection = !string.IsNullOrEmpty(hfSortDirection.Value) ? ((SortDirection)Enum.Parse(typeof(SortDirection), hfSortDirection.Value)) : SortDirection.Ascending;

    //check if we are now sorting on same column
    if (e.SortExpression == previousSortExpression)
    {
        //check if previous direction was ascending
        if (previousSortDirection == SortDirection.Ascending)
        {
            //since column name matches but direction doesn't, 
            sortDirection = SortDirection.Descending;
        }
    }

    // save them back so you know for next time
    hfSortExpression.Value = e.SortExpression;
    hfSortDirection.Value = sortDirection.ToString();

    return sortDirection;
}

Next, you need to handle the sorting in your grid sorting event handler. Call the method above from the sorting event handler, before calling your main method that gets your data

protected void gridContacts_Sorting(object sender, GridViewSortEventArgs e)
{
    //get the sort direction (since GridView sortDirection is not implemented!)
    SortDirection sortDirection = GetSortDirection(e, hfSortExpression, hfSortDirection);

    //get data, sort and rebind (obviously, this is my own method... you must replace with your own)
    GetCases(_accountId, e.SortExpression, sortDirection);
}

Since so many examples out there use DataTables or DataViews or other non LINQ friendly collections, I thought I'd include an example a call to a middle tier method that returns a generic list, and use LINQ to do the sorting in order to round out the example and make it more "real world":

private void GetCases(AccountID accountId, string sortExpression, SortDirection sortDirection)
{
    //get some data from a middle tier method (database etc._)(
    List<PendingCase> pendingCases = MyMiddleTier.GetCasesPending(accountId.Value);
    //show a count to the users on page (this is just nice to have)
    lblCountPendingCases.Text = pendingCases.Count.ToString();
    //do the actual sorting of your generic list of custom objects
    pendingCases = Sort(sortExpression, sortDirection, pendingCases);
    //bind your grid
    grid.DataSource = pendingCases;
    grid.DataBind();
}

Lastly, here is the down and dirty sorting using LINQ on a generic list of custom objects. I'm sure there is something fancier out there that will do the trick, but this illustrates the concept:

private static List Sort(string sortExpression, SortDirection sortDirection, List pendingCases) {

    switch (sortExpression)
    {
        case "FirstName":
            pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c => c.FirstName).ToList() : pendingCases.OrderByDescending(c => c.FirstName).ToList();
            break;
        case "LastName":
            pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c => c.LastName).ToList() : pendingCases.OrderByDescending(c => c.LastName).ToList();
            break;
        case "Title":
            pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c => c.Title).ToList() : pendingCases.OrderByDescending(c => c.Title).ToList();
            break;
        case "AccountName":
            pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c => c.AccountName).ToList() : pendingCases.OrderByDescending(c => c.AccountName).ToList();
            break;
        case "CreatedByEmail":
            pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c => c.CreatedByEmail).ToList() : pendingCases.OrderByDescending(c => c.CreatedByEmail).ToList();
            break;
        default:
            break;
    }
    return pendingCases;
}

Last but not least (did I say that already?) you may want to put something like this in your Page_Load handler, so that the grid binds by default upon page load... Note that _accountId is a querystring parameter, converted to a custom type of AccountID of my own in this case...

    if (!Page.IsPostBack)
    {
        //sort by LastName ascending by default
        GetCases(_accountId,hfSortExpression.Value,SortDirection.Ascending);
    }

How do you format a Date/Time in TypeScript?

This worked for me

    /**
     * Convert Date type to "YYYY/MM/DD" string 
     * - AKA ISO format?
     * - It's logical and sortable :)
     * - 20200227
     * @param Date eg. new Date()
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd 
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
     */
    static DateToYYYYMMDD(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
        return DS
    }

You can certainly add HH:MM something like this...

    static DateToYYYYMMDD_HHMM(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
            + ' ' + ('0' + Date.getHours()).slice(-2)
            + ':' + ('0' + Date.getMinutes()).slice(-2)
        return DS
    }

How to print a list in Python "nicely"

from pprint import pprint
pprint(the_list)

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

Custom Adapter for List View

Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf

Of Countries and their Cities

You can use database from here -

http://myip.ms/info/cities_sql_database/

CREATE TABLE `cities` (
  `cityID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `cityName` varchar(50) NOT NULL,
  `stateID` smallint(5) unsigned NOT NULL DEFAULT '0',
  `countryID` varchar(3) NOT NULL DEFAULT '',
  `language` varchar(10) NOT NULL DEFAULT '',
  `latitude` double NOT NULL DEFAULT '0',
  `longitude` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`cityID`),
  UNIQUE KEY `unq` (`countryID`,`stateID`,`cityID`),
  KEY `cityName` (`cityName`),
  KEY `stateID` (`stateID`),
  KEY `countryID` (`countryID`),
  KEY `latitude` (`latitude`),
  KEY `longitude` (`longitude`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

In a URL, should spaces be encoded using %20 or +?

Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded: this specifies + for spaces.

URLs are encoded as RFC 1738 which specifies %20.

In theory I think you should have %20 before the ? and + after:

example.com/foo%20bar?foo+bar

Can I change the color of Font Awesome's icon color?

If you want to change the color of a specific icon, you can use something like this:

.fa-stop {
    color:red;
}

Eloquent ORM laravel 5 Get Array of ids

You can use all() method instead of toArray() method (see more: laravel documentation):

test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array

If you need a string, you can use without toArray() attachment:

test::where('id' ,'>' ,0)->pluck('id'); //returns string

How do I allow HTTPS for Apache on localhost?

This should be work Ubuntu, Mint similar with Apache2

It is a nice guide, so following this

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

and leaving your ssl.conf like this or similar similar

<VirtualHost _default_:443>
        ServerAdmin [email protected]
        ServerName localhost
        ServerAlias www.localhost.com

        DocumentRoot /var/www


    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

you can get it.

Hope this help for linuxer

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

Is there any kind of hash code function in JavaScript?

Just use hidden secret property with the defineProperty enumerable: false

It work very fast:

  • The first read uniqueId: 1,257,500 ops/s
  • All others: 309,226,485 ops/s
var nextObjectId = 1
function getNextObjectId() {
    return nextObjectId++
}

var UNIQUE_ID_PROPERTY_NAME = '458d576952bc489ab45e98ac7f296fd9'
function getObjectUniqueId(object) {
    if (object == null) {
        return null
    }

    var id = object[UNIQUE_ID_PROPERTY_NAME]

    if (id != null) {
        return id
    }

    if (Object.isFrozen(object)) {
        return null
    }

    var uniqueId = getNextObjectId()
    Object.defineProperty(object, UNIQUE_ID_PROPERTY_NAME, {
        enumerable: false,
        configurable: false,
        writable: false,
        value: uniqueId,
    })

    return uniqueId
}

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

for me changing the Mysql character encoding the same as my code helped to sort out the solution. `photo=open('pic3.png',encoding=latin1), strong text enter image description here

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

How to detect a docker daemon port

Try add -H tcp://0.0.0.0:2375(at end of Execstart line) instead of -H 0.0.0.0:2375.

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

How to fit a smooth curve to my data in R?

The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess and approx, which may give better fits or faster performance.

The advantages are more easily demonstrated with an alternate dataset:

sigmoid <- function(x)
{
  y<-1/(1+exp(-.15*(x-100)))
  return(y)
}

dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))

Here is the data overlaid with the sigmoid curve that generated it:

Data

This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).

A large number of points are used to better demonstrate the performance differences of these functions.

Smooth, spline, and smooth.spline all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.

The loess, lowess, and approx functions all produce usable results, although just barely for approx. This is the code for each using lightly optimized parameters:

loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]

approxFit <- approx(dat,n = 15)

lowessFit <-data.frame(lowess(dat,f = .6,iter=1))

And the results:

plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
       legend=c("Sigmoid","Loess","Lowess",'Approx'),
       lty=c(1,1),
       lwd=c(2.5,2.5),col=c("blue","green","red","purple"))

Fits

As you can see, lowess produces a near perfect fit to the original generating curve. Loess is close, but experiences a strange deviation at both tails.

Although your dataset will be very different, I have found that other datasets perform similarly, with both loess and lowess capable of producing good results. The differences become more significant when you look at benchmarks:

> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
                           expr        min         lq       mean     median        uq        max neval cld
  loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746    20   c
            approx(dat, n = 20)   1.297685   1.346773   1.689133   1.441823   1.86018   4.281735    20 a  
 lowess(dat, f = 0.6, iter = 1)   9.637583  10.085613  11.270911  11.350722  12.33046  12.495343    20  b 

Loess is extremely slow, taking 100x as long as approx. Lowess produces better results than approx, while still running fairly quickly (15x faster than loess).

Loess also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.

EDIT: Additional research shows that loess gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

How to change the text of a button in jQuery?

For buttons created with .Button() in jQuery........

Whilst the other answers will change the text they will mess up the styling of the button, it turns out that when a jQuery button is rendered the text of the button is nested within a span e.g.

<button id="thebutton">
  <span class="ui-button-text">My Text</span>
</button>

If you remove the span and replace it with text (as in the other examples) - you'll loose the span and associated formatting.

So you actually need to change the text within the SPAN tag and NOT the BUTTON!

$("#thebutton span").text("My NEW Text");

or (if like me it's being done on a click event)

$("span", this).text("My NEW Text");

react-router go back a page how do you configure history?

This is a working BackButton component (React 0.14):

var React = require('react');
var Router = require('react-router');

var History = Router.History;

var BackButton = React.createClass({
  mixins: [ History ],
  render: function() {
    return (
      <button className="back" onClick={this.history.goBack}>{this.props.children}</button>
    );
  }
});

module.exports = BackButton;

You can off course do something like this if there is no history:

<button className="back" onClick={goBack}>{this.props.children}</button>

function goBack(e) {
  if (/* no history */) {
    e.preventDefault();
  } else {
    this.history.goBack();
  }
}

JQuery Ajax POST in Codeigniter

$(document).ready(function(){   

    $("#send").click(function()
    {       
     $.ajax({
         type: "POST",
         url: base_url + "chat/post_action", 
         data: {textbox: $("#textbox").val()},
         dataType: "text",  
         cache:false,
         success: 
              function(data){
                alert(data);  //as a debugging message.
              }
          });// you have missed this bracket
     return false;
 });
 });

Obtain smallest value from array in Javascript?

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

jQuery Find and List all LI elements within a UL within a specific DIV

html

<ul class="answerList" id="oneAnswer">
    <li class="answer" value="false">info1</li>
    <li class="answer" value="false">info2</li>
    <li class="answer" value="false">info3</li>
</ul>   

Get index,text,value js

    $('#oneAnswer li').each(function (i) {

        var index = $(this).index();
        var text = $(this).text();
        var value = $(this).attr('value');
        alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
    });

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

How to create jar file with package structure?

This is what I do inside .sh file, let's consider install.sh

#!/bin/sh
echo Installing
cd .../Your_Project_Directory/com/cdy/ws/
jar cfe X.jar Main *.class
cd .../Your_Project_Directory/
ln -s .../Your_Project_Directory/com/cdy/ws/X.jar X
echo Testing...
java -jar X
echo You are Good to Go...Use hapily
#etc.

Creating Executable Jar file at the Class directory and creating a SymLink at anywhere you want.

Run it using,

$ sh install.sh[ENTER]
$ java -jar X[ENTER]

Is there a way to collapse all code blocks in Eclipse?

In addition to the hotkey, if you right click in the gutter where you see the +/-, there is a context menu item 'Folding.' Opening the submenu associated with this, you can see a 'Collapse All' item. this will also do what you wish.

The maximum value for an int type in Go

I would use math package for getting the maximal value and minimal value :

func printMinMaxValue() {
    // integer max
    fmt.Printf("max int64 = %+v\n", math.MaxInt64)
    fmt.Printf("max int32 = %+v\n", math.MaxInt32)
    fmt.Printf("max int16 = %+v\n", math.MaxInt16)

    // integer min
    fmt.Printf("min int64 = %+v\n", math.MinInt64)
    fmt.Printf("min int32 = %+v\n", math.MinInt32)

    fmt.Printf("max flloat64= %+v\n", math.MaxFloat64)
    fmt.Printf("max float32= %+v\n", math.MaxFloat32)

    // etc you can see more int the `math`package
}

Ouput :

max int64 = 9223372036854775807
max int32 = 2147483647
max int16 = 32767
min int64 = -9223372036854775808
min int32 = -2147483648
max flloat64= 1.7976931348623157e+308
max float32= 3.4028234663852886e+38

Find Nth occurrence of a character in a string

Here's another LINQ solution:

string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char
var result = input.Select((c, i) => new { Char = c, Index = i })
                  .Where(item => item.Char == searchChar)
                  .Skip(occurrencePosition - 1)
                  .FirstOrDefault();

if (result != null)
{
    Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
                        occurrencePosition, searchChar, result.Index);
}
else
{
    Console.WriteLine("Position {0} of '{1}' not found!",
                        occurrencePosition, searchChar);
}

Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.

string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char

Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
                   .Cast<Match>()
                   .Skip(occurrencePosition - 1)
                   .FirstOrDefault();

if (match != null)
    Console.WriteLine("Index: " + match.Index);
else
    Console.WriteLine("Match not found!");

How to store values from foreach loop into an array?

You can try to do my answer,

you wrote this:

<?php
foreach($group_membership as $i => $username) {
    $items = array($username);
}

print_r($items);
?>

And in your case I would do this:

<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
    $items[] = $username;
} ?>

As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)

<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
    $items[] = $username; 
} 
?>

while is faster, but the last example is only a result of an observation. :)

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Had the same problem, thanks mikej.

In WLS 10.3 this configuration can be found in Services > JTA menu, or if you click on the domain name (first item in the menu) - on the Configuration > JTA tabs.

alt text

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

There's a great article on Mozilla's MDN docs that describes exactly this issue:

The "Unicode Problem" Since DOMStrings are 16-bit-encoded strings, in most browsers calling window.btoa on a Unicode string will cause a Character Out Of Range exception if a character exceeds the range of a 8-bit byte (0x00~0xFF). There are two possible methods to solve this problem:

  • the first one is to escape the whole string (with UTF-8, see encodeURIComponent) and then encode it;
  • the second one is to convert the UTF-16 DOMString to an UTF-8 array of characters and then encode it.

A note on previous solutions: the MDN article originally suggested using unescape and escape to solve the Character Out Of Range exception problem, but they have since been deprecated. Some other answers here have suggested working around this with decodeURIComponent and encodeURIComponent, this has proven to be unreliable and unpredictable. The most recent update to this answer uses modern JavaScript functions to improve speed and modernize code.

If you're trying to save yourself some time, you could also consider using a library:

Encoding UTF8 ? base64

function b64EncodeUnicode(str) {
    // first we use encodeURIComponent to get percent-encoded UTF-8,
    // then we convert the percent encodings into raw bytes which
    // can be fed into btoa.
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
            return String.fromCharCode('0x' + p1);
    }));
}

b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="

Decoding base64 ? UTF8

function b64DecodeUnicode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
b64DecodeUnicode('Cg=='); // "\n"

The pre-2018 solution (functional, and though likely better support for older browsers, not up to date)

Here is the the current recommendation, direct from MDN, with some additional TypeScript compatibility via @MA-Maddin:

// Encoding UTF8 ? base64

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    }))
}

b64EncodeUnicode('? à la mode') // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n') // "Cg=="

// Decoding base64 ? UTF8

function b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
}

b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU=') // "? à la mode"
b64DecodeUnicode('Cg==') // "\n"

The original solution (deprecated)

This used escape and unescape (which are now deprecated, though this still works in all modern browsers):

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent( str )));
}

function b64_to_utf8( str ) {
    return decodeURIComponent(escape(window.atob( str )));
}

// Usage:
utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"

And one last thing: I first encountered this problem when calling the GitHub API. To get this to work on (Mobile) Safari properly, I actually had to strip all white space from the base64 source before I could even decode the source. Whether or not this is still relevant in 2017, I don't know:

function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(escape(window.atob( str )));
}

css width: calc(100% -100px); alternative using jquery

If you have a browser that doesn't support the calc expression, it's not hard to mimic with jQuery:

$('#yourEl').css('width', '100%').css('width', '-=100px');

It's much easier to let jQuery handle the relative calculation than doing it yourself.

Looping through all the properties of object php

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

How to break nested loops in JavaScript?

You need to name your outer loop and break that loop, rather than your inner loop - like this.

outer_loop: 
for(i=0;i<5;i++) {
    for(j=i+1;j<5;j++) {
        break outer_loop;
    }
    alert(1);
}

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Add table row in jQuery

Here, You can Just Click on button then you will get Output. When You Click on Add row button then one more row Added.

I hope It is very helpful.

<html> 

<head> 
    <script src= 
            "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 

    <style> 
        table { 
            margin: 25px 0; 
            width: 200px; 
        } 

        table th, table td { 
            padding: 10px; 
            text-align: center; 
        } 

        table, th, td { 
            border: 1px solid; 
        } 
    </style> 
</head> 

<body> 

    <b>Add table row in jQuery</b> 

    <p> 
        Click on the button below to 
        add a row to the table 
    </p> 

    <button class="add-row"> 
        Add row 
    </button> 

    <table> 
        <thead> 
            <tr> 
                <th>Rows</th> 
            </tr> 
        </thead> 
        <tbody> 
            <tr> 
                <td>This is row 0</td> 
            </tr> 
        </tbody> 
    </table> 

    <!-- Script to add table row -->
    <script> 
        let rowno = 1; 
        $(document).ready(function () { 
            $(".add-row").click(function () { 
                rows = "<tr><td>This is row " 
                    + rowno + "</td></tr>"; 
                tableBody = $("table tbody"); 
                tableBody.append(rows); 
                rowno++; 
            }); 
        }); 
    </script> 
</body> 
</html>                  

How do I pause my shell script for a second before continuing?

use trap to pause and check command line (in color using tput) before running it

trap 'tput setaf 1;tput bold;echo $BASH_COMMAND;read;tput init' DEBUG

press any key to continue

use with set -x to debug command line

Apply style to cells of first row

Below works for first tr of the table under thead

table thead tr:first-child {
   background: #f2f2f2;
}

And this works for the first tr of thead and tbody both:

table thead tbody tr:first-child {
   background: #f2f2f2;
}

How can I get the height and width of an uiimage?

There are a lot of helpful solutions out there, but there is no simplified way with extension. Here is the code to solve the issue with an extension:

extension UIImage {

    var getWidth: CGFloat {
        get {
            let width = self.size.width
            return width
        }
    }

    var getHeight: CGFloat {
        get {
            let height = self.size.height
            return height
        }
    }
}

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

You can motivate the solution by thinking about it in terms of symmetries (groups, in math language). No matter the order of the set of numbers, the answer should be the same. If you're going to use k functions to help determine the missing elements, you should be thinking about what functions have that property: symmetric. The function s_1(x) = x_1 + x_2 + ... + x_n is an example of a symmetric function, but there are others of higher degree. In particular, consider the elementary symmetric functions. The elementary symmetric function of degree 2 is s_2(x) = x_1 x_2 + x_1 x_3 + ... + x_1 x_n + x_2 x_3 + ... + x_(n-1) x_n, the sum of all products of two elements. Similarly for the elementary symmetric functions of degree 3 and higher. They are obviously symmetric. Furthermore, it turns out they are the building blocks for all symmetric functions.

You can build the elementary symmetric functions as you go by noting that s_2(x,x_(n+1)) = s_2(x) + s_1(x)(x_(n+1)). Further thought should convince you that s_3(x,x_(n+1)) = s_3(x) + s_2(x)(x_(n+1)) and so on, so they can be computed in one pass.

How do we tell which items were missing from the array? Think about the polynomial (z-x_1)(z-x_2)...(z-x_n). It evaluates to 0 if you put in any of the numbers x_i. Expanding the polynomial, you get z^n-s_1(x)z^(n-1)+ ... + (-1)^n s_n. The elementary symmetric functions appear here too, which is really no surprise, since the polynomial should stay the same if we apply any permutation to the roots.

So we can build the polynomial and try to factor it to figure out which numbers are not in the set, as others have mentioned.

Finally, if we are concerned about overflowing memory with large numbers (the nth symmetric polynomial will be of the order 100!), we can do these calculations mod p where p is a prime bigger than 100. In that case we evaluate the polynomial mod p and find that it again evaluates to 0 when the input is a number in the set, and it evaluates to a non-zero value when the input is a number not in the set. However, as others have pointed out, to get the values out of the polynomial in time that depends on k, not N, we have to factor the polynomial mod p.

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

How can I recover the return value of a function passed to multiprocessing.Process?

This example shows how to use a list of multiprocessing.Pipe instances to return strings from an arbitrary number of processes:

import multiprocessing

def worker(procnum, send_end):
    '''worker function'''
    result = str(procnum) + ' represent!'
    print result
    send_end.send(result)

def main():
    jobs = []
    pipe_list = []
    for i in range(5):
        recv_end, send_end = multiprocessing.Pipe(False)
        p = multiprocessing.Process(target=worker, args=(i, send_end))
        jobs.append(p)
        pipe_list.append(recv_end)
        p.start()

    for proc in jobs:
        proc.join()
    result_list = [x.recv() for x in pipe_list]
    print result_list

if __name__ == '__main__':
    main()

Output:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
['0 represent!', '1 represent!', '2 represent!', '3 represent!', '4 represent!']

This solution uses fewer resources than a multiprocessing.Queue which uses

  • a Pipe
  • at least one Lock
  • a buffer
  • a thread

or a multiprocessing.SimpleQueue which uses

  • a Pipe
  • at least one Lock

It is very instructive to look at the source for each of these types.

How to use OrderBy with findAll in Spring Data

AFAIK, I don't think this is possible with a direct method naming query. You can however use the built in sorting mechanism, using the Sort class. The repository has a findAll(Sort) method that you can pass an instance of Sort to. For example:

import org.springframework.data.domain.Sort;

@Repository
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.findAll(sortByIdAsc());
    }

    private Sort sortByIdAsc() {
        return new Sort(Sort.Direction.ASC, "id");
    }
} 

How to disable textbox from editing?

You can set the ReadOnly property to true.

Quoth the link:

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

Turning off hibernate logging console output

For those who don't want elegant solutions, just a quick and dirty way to stop those messages, here is a solution that worked for me (I use Hibernate 4.3.6 and Eclipse and no answers provided above (or found on the internet) worked; neither log4j config files nor setting the logging level programatically)

public static void main(String[] args) {
    //magical - do not touch
    @SuppressWarnings("unused")
    org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.WARNING); //or whatever level you need

    ...
}

I used it in a tutorial program downloaded from this site

C-like structures in Python

The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it's values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn't.

_class_template = """\
class {typename}:
def __init__(self, *args, **kwargs):
    fields = {field_names!r}

    for x in fields:
        setattr(self, x, None)            

    for name, value in zip(fields, args):
        setattr(self, name, value)

    for name, value in kwargs.items():
        setattr(self, name, value)            

def __repr__(self):
    return str(vars(self))

def __setattr__(self, name, value):
    if name not in {field_names!r}:
        raise KeyError("invalid name: %s" % name)
    object.__setattr__(self, name, value)            
"""

def struct(typename, field_names):

    class_definition = _class_template.format(
        typename = typename,
        field_names = field_names)

    namespace = dict(__name__='struct_%s' % typename)
    exec(class_definition, namespace)
    result = namespace[typename]
    result._source = class_definition

    return result

Usage:

Person = struct('Person', ['firstname','lastname'])
generic = Person()
michael = Person('Michael')
jones = Person(lastname = 'Jones')


In [168]: michael.middlename = 'ben'
Traceback (most recent call last):

  File "<ipython-input-168-b31c393c0d67>", line 1, in <module>
michael.middlename = 'ben'

  File "<string>", line 19, in __setattr__

KeyError: 'invalid name: middlename'

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

How do I set the default page of my application in IIS7?

For those who are newbie like me, Open IIS, expand your server name, choose sites, click on your website. On new install, it is Default web site. Click it. On the right side you have Default document option. Double click it. You will see default.htm, default.asp, index.htm etc.. to the extreme right click add. Enter the full name of your file(including extension) that you want to set it as default. click ok. Open cmd prompt as admin and reset iis. Remove all files from c:\inetpub\wwwroot folder like iisstart.html, index.html etc.

Note: This will automatically create web.config file in your c:\inetpub\wwwroot folder. I didnt have any web.config files in my inetpub or wwwroot folders. This automatically created one for me.

Next time when you enter http(s)://servername, it opens the default page you set.

Declare Variable for a Query String

I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.

From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."

Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.

How can I specify the required Node.js version in package.json?

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

Using AES encryption in C#

Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

How to find minimum value from vector?

#include <iostream>
int main()
{
    int v[100] = {5,14,2,4,6};
    int n = 5;
    int mic = v[0];
    for(int i = 0; i != n; ++i)
    {
        if(v[i] < mic)
        mic = v[i];
    }
    std:cout << mic << std::endl;;
}

How do I get Bin Path?

You could do this

    Assembly asm = Assembly.GetExecutingAssembly();
    string path = System.IO.Path.GetDirectoryName(asm.Location);

Specifying a custom DateTime format when serializing with Json.Net

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

Is there a way to automatically generate getters and setters in Eclipse?

Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:

  1. Go to Window > Preferences
  2. Go to General > Keys
  3. List for "Quick Assist - Create getter/setter for field"
  4. In the "Binding" textfield below, hold the desired keys (in my case, I use ALT + SHIFT + G)
  5. Hit Apply and Ok
  6. Now in your Java editor, select the field you want to create getter/setter methods for and press the shortcut you setup in Step 4. Hit ok in this window to create the methods.

Hope this helps!

MySQL CURRENT_TIMESTAMP on create and on update

I think you maybe want ts_create as datetime (so rename -> dt_create) and only ts_update as timestamp? This will ensure it remains unchanging once set.

My understanding is that datetime is for manually-controlled values, and timestamp's a bit "special" in that MySQL will maintain it for you. In this case, datetime is therefore a good choice for ts_create.

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

Force flushing of output to a file while bash script is still running

alternative to stdbuf is awk '{print} END {fflush()}' I wish there were a bash builtin to do this. Normally it shouldn't be necessary, but with older versions there might be bash synchronization bugs on file descriptors.

Rails 3 migrations: Adding reference column?

With the two previous steps stated above, you're still missing the foreign key constraint. This should work:

  class AddUserReferenceToTester < ActiveRecord::Migration
      def change
          add_column :testers, :user_id, :integer, references: :users
      end
  end

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

Styling input radio with css

See this Fiddle

<input type="radio" id="radio-2-1" name="radio-2-set" class="regular-radio" /><label for="radio-2-1"></label>
<input type="radio" id="radio-2-2" name="radio-2-set" class="regular-radio" /><label for="radio-2-2"></label>
<input type="radio" id="radio-2-3" name="radio-2-set" class="regular-radio" /><label for="radio-2-3"></label>

.regular-radio {
    display: none;
}

.regular-radio + label {
    -webkit-appearance: none;
    background-color: #e1e1e1;
    border: 4px solid #e1e1e1;
    border-radius: 10px;
    width: 100%;
    display: inline-block;
    position: relative;
    width: 10px;
    height: 10px;
}

.regular-radio:checked + label {
    background: grey;
    border: 4px solid #e1e1e1;
}

Replacement for deprecated sizeWithFont: in iOS 7?

You can still use sizeWithFont. but, in iOS >= 7.0 method cause crashing if the string contains leading and trailing spaces or end lines \n.

Trimming text before using it

label.text = [label.text stringByTrimmingCharactersInSet:
             [NSCharacterSet whitespaceAndNewlineCharacterSet]];

That's also may apply to sizeWithAttributes and [label sizeToFit].

also, whenever you have nsstringdrawingtextstorage message sent to deallocated instance in iOS 7.0 device it deals with this.

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

PHP script to loop through all of the files in a directory?

glob() has provisions for sorting and pattern matching. Since the return value is an array, you can do most of everything else you need.

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

Configure cron job to run every 15 minutes on Jenkins

1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:

H/15 * * * *

2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’ came with JENKINS-17311:

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Examples:

  • H/15 * * * * - every fifteen minutes (perhaps at :07, :22, :37, :52):
  • H(0-29)/10 * * * * - every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
  • H 9-16/2 * * 1-5 - once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
  • H H 1,15 1-11 * - once a day on the 1st and 15th of every month except December

How to Detect Browser Back Button event - Cross Browser

I was able to use some of the answers in this thread and others to get it working in IE and Chrome/Edge. history.pushState for me wasn't supported in IE11.

if (history.pushState) {
    //Chrome and modern browsers
    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event) {
        history.pushState(null, document.title, location.href);
    });
}
else {
    //IE
    history.forward();
}

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.

But consider such code (it is for a REST controller):

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
            case 'GET':
                return $this->doGet($request, $object);
            case 'POST':
                return $this->doPost($request, $object);
            case 'PUT':
                return $this->doPut($request, $object);
            case 'DELETE':
                return $this->doDelete($request, $object);
            default:
                return $this->onBadRequest();
}

It would not be very useful to apply sanitizing here (although it would not break anything, either).

So, follow recommendations, but not blindly - rather understand why they are for :)

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

Validating Phone Numbers Using Javascript

if (charCode > 47 && charCode < 58) {
    document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
    document.getElementById("fullname").focus();
    document.getElementById("fullname").style.borderColor = 'red';
    return false;
} else {
    document.getElementById("error").innerHTML = "";
    document.getElementById("fullname").style.borderColor = '';
    return true;
}

How to run html file on localhost?

As Nora suggests, you can use the python simple server. Navigate to the folder from which you want to serve your html page, then execute python -m SimpleHTTPServer. Now you can use your web-browser and navigate to http://localhost:8000/ where your page is being served. If your page is named index.html then the server automatically loads that for you. If you want to access any other page, you'll need to browse to http://localhost:8000/{your page name}

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

How to loop in excel without VBA or macros?

Going to answer this myself (correct me if I'm wrong):

It is not possible to iterate over a group of rows (like an array) in Excel without VBA installed / macros enabled.

How do you attach and detach from Docker's process?

I had the same issue, ctrl-P and Q would not work, nor ctrl-C... eventually I opened another terminal session and I did "docker stop containerid " and "docker start containerid " and it got the job done. Weird.

What is the best open-source java charting library? (other than jfreechart)

Good question, I was just looking for alternatives to JFreeChart myself the other day. JFreeChart is excellent and very comprehensive, I've used it on several projects. My recent problem was that it meant adding 1.6mb of libraries to a 50kb applet, so I was looking for something smaller.

The JFreeChart FAQ itself lists alternatives. Compared to JFreeChart, most of them are pretty basic, and some pretty ugly. The most promising seem to be the Java Chart Construction Kit and OpenChart2.

I also found EasyCharts, which is a commercial product but seemingly free to use in some circumstances.

In the end, I went back to the tried and trusted JFreeChart and used Proguard to butcher it into a more manageable size.

I suggest that you take another look at JFreeChart. The user guide is only available to buy, but the demo shows what is possible and it's pretty easy to work out how from the API documentation. Basically you start with the ChartFactory static methods and plug the resultant JFreeChart object into a ChartPanel to display it. If you get stuck, I'm sure you'll get some quick answers to your problems on StackOverflow.

405 method not allowed Web API

In my case I had a physical folder in the project with the same name as the WebAPI route (ex. sandbox) and only the POST request was intercepted by the static files handler in IIS (obviously).

Getting a misleading 405 error instead of the more expected 404, was the reason it took me long to troubleshoot.

Not easy to fall-into this, but possible. Hope it helps someone.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

This happenes might be because you ran out of disk storage and the mysql files and starting files got corrupted

The solution to be tried as below

First we will move the tmp file to somewhere with larger space

Step 1: Copy your existing /etc/my.cnf file to make a backup

cp /etc/my.cnf{,.back-`date +%Y%m%d`}

Step 2: Create your new directory, and set the correct permissions

mkdir /home/mysqltmpdir
chmod 1777 /home/mysqltmpdir

Step 3: Open your /etc/my.cnf file

nano /etc/my.cnf

Step 4: Add below line under the [mysqld] section and save the file

tmpdir=/home/mysqltmpdir

Secondly you need to remove or error files and logs from the /var/lib/mysql/ib_* that means to remove anything that starts by "ib"

rm /var/lib/mysql/ibdata1 and rm /var/lib/mysql/ibda.... and so on

Thirdly you will need to make sure that there is a pid file available to have the database to write in

Step 1 you need to edit /etc/my.cnf

pid-file= /var/run/mysqld/mysqld.pid 

Step 2 create the directory with the file to point to

 mkdir /var/run/mysqld
 touch /var/run/mysqld/mysqld.pid
 chown -R mysql:mysql /var/run/mysqld

Last step restart mysql server

/etc/init.d/mysql restart

How to add items to a spinner in Android?

Add a spinner to the XML layout, and then add this code to the Java file:

Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);

What is the difference between SessionState and ViewState?

SessionState

  • Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
  • Can be persisted in a Database, useful for Web Farms / Web Gardens.
  • Is Cleared when the session dies - usually after 20min of inactivity.

ViewState

  • Is sent back and forth between the server and client, taking up bandwidth.
  • Has no expiration date.
  • Is useful in a Web Farm / Web Garden

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

CSV file written with Python has blank lines between each row

Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.

Instead, you should keep it in text mode, but override the newline as empty. Like so:

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.

With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

Stash only one file out of multiple files that have changed with Git?

I would use git stash save --patch. I don't find the interactivity to be annoying because there are options during it to apply the desired operation to entire files.

How to use makefiles in Visual Studio?

To answer the specific questions...

I'm using VS2008. Can somebody please suggest some online references or books where I can find out more about how to deal with them?

This link will give you a good introduction into Makefiles by mapping it with Visual Studio.

Introduction to Makefiles for Visual Studio developers

I heard a lot about makefiles and how they simplify the compilation process.

Makefiles are powerful and flexible but may not be the best solution to simplify the process. Consider CMake which abstracts the build process well which is explained in this link.

CMake for Visual Studio Developers

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

Counting the occurrences / frequency of array elements

ES6 version should be much simplifier (another one line solution)

let arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
let acc = arr.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());

console.log(acc);
// output: Map { 5 => 3, 2 => 5, 9 => 1, 4 => 1 }

A Map instead of plain Object helping us to distinguish different type of elements, or else all counting are base on strings

Showing all session data at once?

here is code:

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

How to convert decimal to hexadecimal in JavaScript

How to convert decimal to hexadecimal in JavaScript

I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.

function DecToHex(decimal) { // Data (decimal)

    length = -1;    // Base string length
    string = '';    // Source 'string'

    characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array

    do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift

        string += characters[decimal & 0xF];   // Mask byte, get that character
        ++length;                              // Increment to length of string

    } while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0

    decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'

    do
        decimal += string[length];
    while (length--); // Flip string forwards, with the prefixed '0x'

    return (decimal); // return (hexadecimal);
}

/* Original: */

D = 3678;    // Data (decimal)
C = 0xF;    // Check
A = D;        // Accumulate
B = -1;        // Base string length
S = '';        // Source 'string'
H = '0x';    // Destination 'string'

do {
    ++B;
    A& = C;

    switch(A) {
        case 0xA: A='A'
        break;

        case 0xB: A='B'
        break;

        case 0xC: A='C'
        break;

        case 0xD: A='D'
        break;

        case 0xE: A='E'
        break;

        case 0xF: A='F'
        break;

        A = (A);
    }
    S += A;

    D >>>= 0x04;
    A = D;
} while(D)

do
    H += S[B];
while (B--)

S = B = A = C = D; // Zero out variables
alert(H);    // H: holds hexadecimal equivalent

Implement division with bit-wise operator

I assume we are discussing division of integers.

Consider that I got two number 1502 and 30, and I wanted to calculate 1502/30. This is how we do this:

First we align 30 with 1501 at its most significant figure; 30 becomes 3000. And compare 1501 with 3000, 1501 contains 0 of 3000. Then we compare 1501 with 300, it contains 5 of 300, then compare (1501-5*300) with 30. At so at last we got 5*(10^1) = 50 as the result of this division.

Now convert both 1501 and 30 into binary digits. Then instead of multiplying 30 with (10^x) to align it with 1501, we multiplying (30) in 2 base with 2^n to align. And 2^n can be converted into left shift n positions.

Here is the code:

int divide(int a, int b){
    if (b != 0)
        return;

    //To check if a or b are negative.
    bool neg = false;
    if ((a>0 && b<0)||(a<0 && b>0))
        neg = true;

    //Convert to positive
    unsigned int new_a = (a < 0) ? -a : a;
    unsigned int new_b = (b < 0) ? -b : b;

    //Check the largest n such that b >= 2^n, and assign the n to n_pwr
    int n_pwr = 0;
    for (int i = 0; i < 32; i++)
    {
        if (((1 << i) & new_b) != 0)
            n_pwr = i;
    }

    //So that 'a' could only contain 2^(31-n_pwr) many b's,
    //start from here to try the result
    unsigned int res = 0;
    for (int i = 31 - n_pwr; i >= 0; i--){
        if ((new_b << i) <= new_a){
            res += (1 << i);
            new_a -= (new_b << i);
        }
    }

    return neg ? -res : res;
}

Didn't test it, but you get the idea.