Programs & Examples On #Asp.net

ASP.NET is a Microsoft web application development framework that allows programmers to build dynamic web sites, web applications and web services. It is useful to use this tag in conjunction with the project type tag e.g. [asp.net-mvc], [asp.net-webforms], or [asp.net-web-api]. Do NOT use this tag for questions about ASP.NET Core - use [asp.net-core] instead.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

I was now able to find reason behind the error guys. It's on the webhosting site settings not on my app pool or what so ever. I changed the asp.net version from 2.0 to 4.0 but I forgot to click the update button. I feel so embarrased. :( I've been struggling for days to fix this error and only to found out its on the webhosting site settings. GgrrRR.. As of now I'm facing new error but has nothing to do with this question. Anyway thanks guys for your efforts to help me. :)

Where does Console.WriteLine go in ASP.NET?

Mac, In Debug mode there is a tab for the Output. enter image description here

How to Populate a DataTable from a Stored Procedure

Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:

using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();

            da.Fill(dt);
        }
    }
}

How to get POST data in WebAPI?

It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.

public class MyParameters
{
    public string a { get; set; } 
    public string b { get; set; }
}

public MyController : ApiController
{
    public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}

Then you go to:

http://localhost:12345/api/MyController?a=par1&b=par2

Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".

See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

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

I've updated the Microsoft.Net.Compilers to version 2.0 or higher

see this

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

Datetime format Issue: String was not recognized as a valid DateTime

change the culture and try out like this might work for you

string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
     formats, new CultureInfo("en-US"), DateTimeStyles.None);

Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Might it be possible that you're using a WCF-based web service reference? By default, the ServiceThrottlingBehavior.MaxConcurrentCalls is 16.

You could try updating your service reference behavior's <serviceThrottling> element

<serviceThrottling
    maxConcurrentCalls="999" 
    maxConcurrentSessions="999" 
    maxConcurrentInstances="999" />

(Note that I'd recommend the settings above.) See MSDN for more information how to configure an appropriate <behavior> element.

"The Controls collection cannot be modified because the control contains code blocks"

First, start the code block with <%# instead of <%= :

<head id="head1" runat="server">
  <title>My Page</title>
  <link href="css/common.css" rel="stylesheet" type="text/css" />
  <script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script>
</head>

This changes the code block from a Response.Write code block to a databinding expression.
Since <%# ... %> databinding expressions aren't code blocks, the CLR won't complain. Then in the code for the master page, you'd add the following:

protected void Page_Load(object sender, EventArgs e)
{
  Page.Header.DataBind();    
}

ScriptManager.RegisterStartupScript code not working - why?

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);

ASP.NET Identity reset password

Best way to Reset Password in Asp.Net Core Identity use for Web API.

Note* : Error() and Result() are created for internal use. You can return you want.

        [HttpPost]
        [Route("reset-password")]
        public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                if (model is null)
                    return Error("No data found!");


                var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
                if (user == null)
                    return Error("No user found!");

                Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
                    await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);

                if (!checkOldPassword.Succeeded)
                    return Error("Old password does not matched.");

                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
                if (string.IsNullOrEmpty(resetToken))
                    return Error("Error while generating reset token.");

                var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);

                if (result.Succeeded)
                    return Result();
                else
                    return Error();
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I created copy of my inet folder, to make a duplicate of the site. It showed 'access denied .../App_Data/viewstate/1/6/6/0 ... '. On checking it showed that app_data folder is having IIS_IUSER addes but does not have modify or write acess checked. Just check those boxes and the instance begin to run.

Can I hide/show asp:Menu items based on role?

You can bind the menu items to a site map and use the roles attribute. You will need to enable Security Trimming in your Web.Config to do this. This is the simplest way.

Site Navigation Overview: http://msdn.microsoft.com/en-us/library/e468hxky.aspx

Security Trimming Info: http://msdn.microsoft.com/en-us/library/ms178428.aspx

SiteMap Binding Info: http://www.w3schools.com/aspnet/aspnet_navigation.asp

Good Tutorial/Overview here: http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx

Another option that works, but is less ideal is to use the loginview control which can display controls based on role. This might be the quickest (but least flexible/performant) option. You can find a guide here: http://weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx

HttpContext.Current.Session is null when routing requests

The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.

How to launch another aspx web page upon button click?

You should use:

protected void btn1_Click(object sender, EventArgs e)
{
    Response.Redirect("otherpage.aspx");
}

What is the App_Data folder used for in Visual Studio?

We use it as a temporary storage area for uploaded csv files. Once uploaded, an ajax method processes and deletes the file.

ASP.NET Core Web API Authentication

Now, after I was pointed in the right direction, here's my complete solution:

This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.

public class AuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public AuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];
        if (authHeader != null && authHeader.StartsWith("Basic"))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':');

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            if(username == "test" && password == "test" )
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
        else
        {
            // no authorization header
            context.Response.StatusCode = 401; //Unauthorized
            return;
        }
    }
}

The middleware extension needs to be called in the Configure method of the service Startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMiddleware<AuthenticationMiddleware>();

    app.UseMvc();
}

And that's all! :)

A very good resource for middleware in .Net Core and authentication can be found here: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/

How to use the ConfigurationManager.AppSettings

Your web.config file should have this structure:

<configuration>
    <connectionStrings>
        <add name="MyConnectionString" connectionString="..." />
    </connectionStrings>
</configuration>

Then, to create a SQL connection using the connection string named MyConnectionString:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

<configuration>
    <appSettings>
        <add key="MyConnectionString" value="..." />
    </appSettings>
</configuration>

And then your SqlConnection constructor would look like this:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are two possible scenario, in my case I used 2nd point.

  1. If you are facing this issue in production environment and you can easily deploy new code to the production then you can use of below solution.

    You can add below line of code before making api call,

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

  2. If you cannot deploy new code and you want to resolve with the same code which is present in the production, then this issue can be done by changing some configuration setting file. You can add either of one in your config file.

<runtime>
    <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
  </runtime>

or

<runtime>
  <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>

Can an ASP.NET MVC controller return an Image?

You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:

public class StreamResult : ViewResult
{
    public Stream Stream { get; set; }
    public string ContentType { get; set; }
    public string ETag { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = ContentType;
        if (ETag != null) context.HttpContext.Response.AddHeader("ETag", ETag);
        const int size = 4096;
        byte[] bytes = new byte[size];
        int numBytes;
        while ((numBytes = Stream.Read(bytes, 0, size)) > 0)
            context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);
    }
}

How can I retrieve Id of inserted entity using Entity framework?

I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.

Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;

var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id

However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId

All I had to do was this;

var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer}; 
context.Orders.Add(order);
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order

Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps

I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.

This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

What does IFormatProvider do?

The DateTimeFormatInfo class implements this interface, so it allows you to control the formatting of your DateTime strings.

jquery $(this).id return Undefined

Another option (just so you've seen it):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});

HTH.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

how to call an ASP.NET c# method using javascript

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

Import the jQuery library in your page mark-up:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

In my case none of the above solutions worked. I solved by right clicking on the reference

System.Net.Http.Formatting

from Visual studio and setting the property Copy Local to true.

I hope this is useful somehow.

Invalid length for a Base-64 char array

The encrypted string had two special characters, + and =.

'+' sign was giving the error, so below solution worked well:

//replace + sign

encryted_string = encryted_string.Replace("+", "%2b");

//`%2b` is HTTP encoded string for **+** sign

OR

//encode special charactes 

encryted_string = HttpUtility.UrlEncode(encryted_string);

//then pass it to the decryption process
...

Assign format of DateTime with data annotations?

Apply DataAnnotation like:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

How to convert a list into data table

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

Setting dropdownlist selecteditem programmatically

Here is the code I was looking for :

DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));

Or

DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));

Prevent textbox autofill with previously entered values

This is the answer.

_x000D_
_x000D_
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
_x000D_
_x000D_

AutoCompleteType="Disabled"

If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go

'Options' --> 'Security'(tab) --> Untick

'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.

This should solve the problem

converting list to json format - quick and easy way

If you are using WebApi, HttpResponseMessage is a more elegant way to do it

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}

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

I found a solution for ajax issue noted by Lion_cl.

global.asax:

protected void Application_Error()
    {           
        if (HttpContext.Current.Request.IsAjaxRequest())
        {
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Clear();
            RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
            rc.RouteData.Values["action"] = "AjaxGlobalError";

            // TODO: distinguish between 404 and other errors if needed
            rc.RouteData.Values["newActionName"] = "WrongRequest";

            rc.RouteData.Values["controller"] = "ErrorPages";
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(rc, "ErrorPages");
            controller.Execute(rc);
            ctx.Server.ClearError();
        }
    }

ErrorPagesController

public ActionResult AjaxGlobalError(string newActionName)
    {
        return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
    }

AjaxRedirectResult

public class AjaxRedirectResult : RedirectResult
{
    public AjaxRedirectResult(string url, ControllerContext controllerContext)
        : base(url)
    {
        ExecuteResult(controllerContext);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
            };

            result.ExecuteResult(context);
        }
        else
        {
            base.ExecuteResult(context);
        }
    }
}

AjaxRequestExtension

public static class AjaxRequestExtension
{
    public static bool IsAjaxRequest(this HttpRequest request)
    {
        return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
}

System.Security.SecurityException when writing to Event Log

For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

Finally I get the solution for my problem. The asp.net account not appear in the IIS manager because I didn't check its check Box in IIS to do this in windows 7 follow the steps

  1. Open control panel
  2. Click on” program” link (not uninstall programs)
  3. Click” turn windows features on/off” link
  4. locate” Internet Information services IIS” in the pop up window and expand its node
  5. Expand the” World Wide Web Service” node
  6. Expand “Application Development Features” node
  7. check the check box of”ASP.NET”
  8. Then click ok button

Now you will see the Asp.net account on the IIS manager and by default you see IIS account Now you should move you asp.net website from “my document” to another place the IIS have permission to access it (to any partition on your computer) Now browse your website from IIS manager and it should work.

JavaScriptSerializer - JSON serialization of enum as string

No there is no special attribute you can use. JavaScriptSerializer serializes enums to their numeric values and not their string representation. You would need to use custom serialization to serialize the enum as its name instead of numeric value.


If you can use JSON.Net instead of JavaScriptSerializer than see answer on this question provided by OmerBakhari: JSON.net covers this use case (via the attribute [JsonConverter(typeof(StringEnumConverter))]) and many others not handled by the built in .net serializers. Here is a link comparing features and functionalities of the serializers.

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

try ToString method for your desirer format use

DateTime.Now.ToString("yyyy-MM-dd"); 


OR you can use it with your variable of DateTime type

dt.ToString("yyyy-MM-dd");


where dt is a DateTime variable

Refresh an asp.net page on button click

Page reload can be done using javascript code. Use either a HTML button and implement it like...

<input type="button" value="Reload Page" onClick="document.location.reload(true)">

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

Refresh Page C# ASP.NET

Call Page_load function:

Page_Load(sender, e);

Changing CSS style from ASP.NET code

VB Version:

Class:

Protected divControl As System.Web.UI.HtmlControls.HtmlGenericControl

OnLoad/Other function:

divControl.Style("height") = "200px"

I've never tried the Add method with the styles. What if the height already exists on the DIV?

How to Publish Web with msbuild?

For generating the publish output provide one more parameter. msbuild example.sln /p:publishprofile=profilename /p:deployonbuild=true /p:configuration=debug/or any

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

How to get current page URL in MVC 3

public static string GetCurrentWebsiteRoot()
{
    return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
}

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I had the same problem after the most recent VS 2017 update (released March 14, 2017: build 26228.09). My program would debug fine in IE but would bomb out in Chrome. Killing all instances of Chrome within the Windows command line fixed the problem for me.

taskkill /im chrome.exe /f

I was then able to debug in Chrome.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

DropdownList DataSource

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        drpCategory.DataSource = CategoryHelper.Categories;
        drpCategory.DataTextField = "Name";
        drpCategory.DataValueField = "Id";
        drpCategory.DataBind();
    }
}

Problem with converting int to string in Linq to entities

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

This error message can happen if you have duplicate entries/entities and run SaveChanges().

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

How to increase time in web.config for executing sql query

SQL Server has no setting to control query timeout in the connection string, and as far as I know this is the same for other major databases. But, this doesn't look like the problem you're seeing: I'd expect to see an exception raised

Error: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

if there genuinely was a timeout executing the query.

If this does turn out to be a problem, you can change the default timeout for a SQL Server database as a property of the database itself; use SQL Server Manager for this.

Be sure that the query is exactly the same from your Web application as the one you're running directly. Use a profiler to verify this.

How can I display a messagebox in ASP.NET?

Alert message with redirect

Response.Write("<script language='javascript'>window.alert('Popup message ');window.location='webform.aspx';</script>");

Only alert message

Response.Write("<script language='javascript'>window.alert('Popup message ')</script>");

IIS7 folder permissions for web application

Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

Could not load file or assembly Exception from HRESULT: 0x80131040

Add following dll files to bin folder:

DotNetOpenAuth.AspNet.dll
DotNetOpenAuth.Core.dll
DotNetOpenAuth.OAuth.Consumer.dll
DotNetOpenAuth.OAuth.dll
DotNetOpenAuth.OpenId.dll
DotNetOpenAuth.OpenId.RelyingParty.dll

If you will not need them, delete dependentAssemblies from config named 'DotNetOpenAuth.Core' etc..

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I was experiencing a similar error message that I noticed in the Windows Event Viewer that read:

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database. [CLIENT: local machine]

The solution that resolved my problem was:

  1. Login to SqlExpress via SQL Server Management Studio
  2. Go to the "Security" directory of the database
  3. Right-click the Users directory
  4. Select "New User..."
  5. Add 'NT AUTHORITY\NETWORK SERVICE' as a new user
  6. In the Data Role Membership area, select db_owner
  7. Click OK

Here's a screenshot of the above: Screenshot of adding new user Network Service as db_owner to SqlExpress

Conditionally hide CommandField or ButtonField in Gridview

You can hide a CommandField or ButtonField based on the position (index) in the GridView.

For example, if your CommandField is in the first position (index = 0), you can hide it adding the following code in the event RowDataBound of the GridView:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((System.Web.UI.Control)e.Row.Cells[0].Controls[0]).Visible = false;
    }
}

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

Convert all first letter to upper case, rest lower for each word

When building big tables speed is a concern so Jamie Dixon's second function is best, but it doesn't completely work as is...

It fails to take all of the letters to lowercase, and it only capitalizes the first letter of the string, not the first letter of each word in the string... the below option fixes both issues:

    public string UppercaseFirstEach(string s)
    {
        char[] a = s.ToLower().ToCharArray();

        for (int i = 0; i < a.Count(); i++ )
        {
            a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i];

        }

        return new string(a);
    }

Although at this point, whether this is still the fastest option is uncertain, the Regex solution provided by George Mauer might be faster... someone who cares enough should test it.

Verify External Script Is Loaded

Merging several answers from above into an easy to use function

function GetScriptIfNotLoaded(scriptLocationAndName)
{
  var len = $('script[src*="' + scriptLocationAndName +'"]').length;

  //script already loaded!
  if (len > 0)
      return;

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptLocationAndName;
  head.appendChild(script);
}

drop down list value in asp.net

<asp:DropDownList ID="DdlMonths" runat="server">
    <asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
    <asp:ListItem Text="January" Value="1"></asp:ListItem>
    <asp:ListItem Text="February" Value="2"></asp:ListItem>
    ....
    <asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>

You can even use a RequiredFieldValidator which ignore this item, it considers it as unselected.

<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
    InitialValue="-1">
</asp:RequiredFieldValidator>

How to save SELECT sql query results in an array in C# Asp.net

Normally i use a class for this:

public class ClassName
{
    public string Col1 { get; set; }
    public int Col2 { get; set; }
}

Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
{
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();
    }
}

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

herein lies the answer... IIS Settings

IIS-->Default SMTP Virtual Server-->Properties-->Access-->Relay restrictions just add or exclude the IPs you care about, should resolve the issue.

Getting Textbox value in Javascript

Use

document.getElementById('<%= txt_model_code.ClientID %>')

instead of

document.getElementById('txt_model_code')`

Also you can use onClientClick instead of onClick.

How to get the selected value from RadioButtonList?

radiobuttonlist.selected <value> to process with your code.

Add Header and Footer for PDF using iTextsharp

Just add this line before opening the document (must be before):

        document.Header = new HeaderFooter(new Phrase("Header Text"), false);
        document.Open();

how to generate a unique token which expires after 24 hours?

I like Guffa's answer and since I can't comment I will provide the answer Udil's question here.

I needed something similar but I wanted certein logic in my token, I wanted to:

  1. See the expiration of a token
  2. Use a guid to mask validate (global application guid or user guid)
  3. See if the token was provided for the purpose I created it (no reuse..)
  4. See if the user I send the token to is the user that I am validating it for

Now points 1-3 are fixed length so it was easy, here is my code:

Here is my code to generate the token:

public string GenerateToken(string reason, MyUser user)
{
    byte[] _time     = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
    byte[] _key      = Guid.Parse(user.SecurityStamp).ToByteArray();
    byte[] _Id       = GetBytes(user.Id.ToString());
    byte[] _reason   = GetBytes(reason);
    byte[] data       = new byte[_time.Length + _key.Length + _reason.Length+_Id.Length];

    System.Buffer.BlockCopy(_time, 0, data, 0, _time.Length);
    System.Buffer.BlockCopy(_key , 0, data, _time.Length, _key.Length);
    System.Buffer.BlockCopy(_reason, 0, data, _time.Length + _key.Length, _reason.Length);
    System.Buffer.BlockCopy(_Id, 0, data, _time.Length + _key.Length + _reason.Length, _Id.Length);

    return Convert.ToBase64String(data.ToArray());
}

Here is my Code to take the generated token string and validate it:

public TokenValidation ValidateToken(string reason, MyUser user, string token)
{
    var result = new TokenValidation();
    byte[] data     = Convert.FromBase64String(token);
    byte[] _time     = data.Take(8).ToArray();
    byte[] _key      = data.Skip(8).Take(16).ToArray();
    byte[] _reason   = data.Skip(24).Take(2).ToArray();
    byte[] _Id       = data.Skip(26).ToArray();

    DateTime when = DateTime.FromBinary(BitConverter.ToInt64(_time, 0));
    if (when < DateTime.UtcNow.AddHours(-24))
    {
        result.Errors.Add( TokenValidationStatus.Expired);
    }
    
    Guid gKey = new Guid(_key);
    if (gKey.ToString() != user.SecurityStamp)
    {
        result.Errors.Add(TokenValidationStatus.WrongGuid);
    }

    if (reason != GetString(_reason))
    {
        result.Errors.Add(TokenValidationStatus.WrongPurpose);
    }

    if (user.Id.ToString() != GetString(_Id))
    {
        result.Errors.Add(TokenValidationStatus.WrongUser);
    }
    
    return result;
}

private static string GetString(byte[] reason) => Encoding.ASCII.GetString(reason);

private static byte[] GetBytes(string reason) => Encoding.ASCII.GetBytes(reason);

The TokenValidation class looks like this:

public class TokenValidation
{
    public bool Validated { get { return Errors.Count == 0; } }
    public readonly List<TokenValidationStatus> Errors = new List<TokenValidationStatus>();
}

public enum TokenValidationStatus
{
    Expired,
    WrongUser,
    WrongPurpose,
    WrongGuid
}

Now I have an easy way to validate a token, no Need to Keep it in a list for 24 hours or so. Here is my Good-Case Unit test:

private const string ResetPasswordTokenPurpose = "RP";
private const string ConfirmEmailTokenPurpose  = "EC";//change here change bit length for reason  section (2 per char)

[TestMethod]
public void GenerateTokenTest()
{
    MyUser user         = CreateTestUser("name");
    user.Id             = 123;
    user.SecurityStamp  = Guid.NewGuid().ToString();
    var token   = sit.GenerateToken(ConfirmEmailTokenPurpose, user);
    var validation    = sit.ValidateToken(ConfirmEmailTokenPurpose, user, token);
    Assert.IsTrue(validation.Validated,"Token validated for user 123");
}

One can adapt the code for other business cases easely.

Happy Coding

Walter

How to set css style to asp.net button?

I Found the coding...

 input[type="submit"]
    {
     //css coding
    }
 input[type="submit"]:Hover  
    {
     //css coding
    }

This is the solution for my issue..... Thanks everyone for the valuable answers.......

Difference between AutoPostBack=True and AutoPostBack=False?

AutoPostBack = true permits control to post back to the server. It is associated with an Event.

Example:

<asp:DropDownList id="id" runat="server" AutoPostBack="true" OnSelectIndexChanged="..."/>

The aspx page with the above drop down list does not need an asp:button to do the post back. When you change an option in the drop down list, the page gets posted back to the server.

Default value of AutoPostBack on control is false.

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

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

Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".

is that it isn’t quite URL form encoded data. By adding “=” in front like this:

=hello

it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.

However, a better solution is to use application/json when uploading a string:

POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7

"Hello"

Using HttpClient you can do it as follows:

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);

Henrik

Response Content type as CSV

Over the years I've been honing a perfect set of headers for this that work brilliantly in all browsers that I know of

// these headers avoid IE problems when using https:
// see http://support.microsoft.com/kb/812935
header("Cache-Control: must-revalidate");
header("Pragma: must-revalidate");

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=$filename.csv");

"Could not load type [Namespace].Global" causing me grief

go to configuration Manager under properties for your solution. Then make sure all projects and getting built, and this won't be a problem.

What is an HttpHandler in ASP.NET

Any Class that implements System.Web.IHttpHandler Interface becomes HttpHandler. And this class run as processes in response to a request made to the ASP.NET Site.

The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler(The Class that implements System.Web.IHttpHandler Interface).

You can create your own custom HTTP handlers that render custom output to the browser.

Some ASP.NET default handlers are:

  1. Page Handler (.aspx) – Handles Web pages
  2. User Control Handler (.ascx) – Handles Web user control pages
  3. Web Service Handler (.asmx) – Handles Web service pages
  4. Trace Handler (trace.axd) – Handles trace functionality

Get text of label with jquery

try this:

var g = $('#<%=Label1.ClientID%>').val();

or this:

var g = $('#<%=Label1.ClientID%>').html();

you are missing the #

add this in the head section:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

Call JavaScript function from C#

.aspx file in header section

<head>
    <script type="text/javascript">
        <%=YourScript %>
        function functionname1(arg1,arg2){content}
    </script>
</head>

.cs file

public string YourScript = "";
public string functionname(arg)
{
    if (condition)
    {
        YourScript = "functionname1(arg1,arg2);";
    }
}

Adding machineKey to web.config on web-farm sites

This should answer:

How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations

Web Farm Deployment Considerations

If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.

With manually generated key values, the settings should be similar to the following example.

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"       

decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.

In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.

Setting Up the Machine Key Using IIS Manager

If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.

Start the management console and then select the web site. Open the machine key configuration: The IIS web site configuration panel

The machine key control panel has the following settings:

The machine key configuration panel

Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.

Click "Generate Keys" under "Actions" on the right side of the panel.

Click "Apply".

and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.

<machineKey  
    validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
                   AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
    decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1"
    decryption="AES"
/>

Please make sure that you have a permanent backup of the machine keys and web.config file

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

Could not find a part of the path ... bin\roslyn\csc.exe

I experienced this error on a Jenkins build server running MSBuild, which outputs the build files to a separate folder location (_PublishedWebsites). Exactly the same - the roslyn folder was not in the bin directory, and all the roslyn files were lumped in with the bin files.

@igor-semin 's answer was the only thing that worked for me (as I am using the C# 6 language features, I cannot simply uninstall the nuget packages as per other answers), but as I am also running CodeAnalysis, I was getting another error on my deployment target server:

An attempt to override an existing mapping was detected for type Microsoft.CodeAnalysis.ICompilationUnitSyntax with name "", currently mapped to type Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax, to type Microsoft.CodeAnalysis.VisualBasic.Syntax.CompilationUnitSyntax.

The reason for this is that as the roslyn files are getting dumped into the main bin directory, when you run the xcopy to recreate them in the nested roslyn folder, you now have 2 copies of these files being compiled and there is a clash between them. After much frustration I decided on a 'hack' fix - an additional post-build task to delete these files from the bin directory, removing the conflict.

The .csproj of my offending projects now looks like:

................... more here ......................

 <PropertyGroup>
   <PostBuildEvent>
   if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
   start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
 </PostBuildEvent>
</PropertyGroup>
<Target Name="DeleteDuplicateAnalysisFiles" AfterTargets="AfterBuild">
   <!-- Jenkins now has copies of the following files in both the bin directory and the 'bin\rosyln' directory. Delete from bin. -->
   <ItemGroup>
     <FilesToDelete Include="$(WebProjectOutputDir)\bin\Microsoft.CodeAnalysis*.dll" />
   </ItemGroup>
   <Delete Files="@(FilesToDelete)" />
</Target>

................... more here ......................

MemoryStream - Cannot access a closed Stream

In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):

PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);

The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.

How to render a DateTime in a specific format in ASP.NET MVC 3?

I use the following approach to inline format and display a date property from the model.

@Html.ValueFor(model => model.MyDateTime, "{0:dd/MM/yyyy}")

Otherwise when populating a TextBox or Editor you could do like @Darin suggested, decorated the attribute with a [DisplayFormat] attribute.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

One DbContext per web request... why?

NOTE: This answer talks about the Entity Framework's DbContext, but it is applicable to any sort of Unit of Work implementation, such as LINQ to SQL's DataContext, and NHibernate's ISession.

Let start by echoing Ian: Having a single DbContext for the whole application is a Bad Idea. The only situation where this makes sense is when you have a single-threaded application and a database that is solely used by that single application instance. The DbContext is not thread-safe and and since the DbContext caches data, it gets stale pretty soon. This will get you in all sorts of trouble when multiple users/applications work on that database simultaneously (which is very common of course). But I expect you already know that and just want to know why not to just inject a new instance (i.e. with a transient lifestyle) of the DbContext into anyone who needs it. (for more information about why a single DbContext -or even on context per thread- is bad, read this answer).

Let me start by saying that registering a DbContext as transient could work, but typically you want to have a single instance of such a unit of work within a certain scope. In a web application, it can be practical to define such a scope on the boundaries of a web request; thus a Per Web Request lifestyle. This allows you to let a whole set of objects operate within the same context. In other words, they operate within the same business transaction.

If you have no goal of having a set of operations operate inside the same context, in that case the transient lifestyle is fine, but there are a few things to watch:

  • Since every object gets its own instance, every class that changes the state of the system, needs to call _context.SaveChanges() (otherwise changes would get lost). This can complicate your code, and adds a second responsibility to the code (the responsibility of controlling the context), and is a violation of the Single Responsibility Principle.
  • You need to make sure that entities [loaded and saved by a DbContext] never leave the scope of such a class, because they can't be used in the context instance of another class. This can complicate your code enormously, because when you need those entities, you need to load them again by id, which could also cause performance problems.
  • Since DbContext implements IDisposable, you probably still want to Dispose all created instances. If you want to do this, you basically have two options. You need to dispose them in the same method right after calling context.SaveChanges(), but in that case the business logic takes ownership of an object it gets passed on from the outside. The second option is to Dispose all created instances on the boundary of the Http Request, but in that case you still need some sort of scoping to let the container know when those instances need to be Disposed.

Another option is to not inject a DbContext at all. Instead, you inject a DbContextFactory that is able to create a new instance (I used to use this approach in the past). This way the business logic controls the context explicitly. If might look like this:

public void SomeOperation()
{
    using (var context = this.contextFactory.CreateNew())
    {
        var entities = this.otherDependency.Operate(
            context, "some value");

        context.Entities.InsertOnSubmit(entities);

        context.SaveChanges();
    }
}

The plus side of this is that you manage the life of the DbContext explicitly and it is easy to set this up. It also allows you to use a single context in a certain scope, which has clear advantages, such as running code in a single business transaction, and being able to pass around entities, since they originate from the same DbContext.

The downside is that you will have to pass around the DbContext from method to method (which is termed Method Injection). Note that in a sense this solution is the same as the 'scoped' approach, but now the scope is controlled in the application code itself (and is possibly repeated many times). It is the application that is responsible for creating and disposing the unit of work. Since the DbContext is created after the dependency graph is constructed, Constructor Injection is out of the picture and you need to defer to Method Injection when you need to pass on the context from one class to the other.

Method Injection isn't that bad, but when the business logic gets more complex, and more classes get involved, you will have to pass it from method to method and class to class, which can complicate the code a lot (I've seen this in the past). For a simple application, this approach will do just fine though.

Because of the downsides, this factory approach has for bigger systems, another approach can be useful and that is the one where you let the container or the infrastructure code / Composition Root manage the unit of work. This is the style that your question is about.

By letting the container and/or the infrastructure handle this, your application code is not polluted by having to create, (optionally) commit and Dispose a UoW instance, which keeps the business logic simple and clean (just a Single Responsibility). There are some difficulties with this approach. For instance, were do you Commit and Dispose the instance?

Disposing a unit of work can be done at the end of the web request. Many people however, incorrectly assume that this is also the place to Commit the unit of work. However, at that point in the application, you simply can't determine for sure that the unit of work should actually be committed. e.g. If the business layer code threw an exception that was caught higher up the callstack, you definitely don't want to Commit.

The real solution is again to explicitly manage some sort of scope, but this time do it inside the Composition Root. Abstracting all business logic behind the command / handler pattern, you will be able to write a decorator that can be wrapped around each command handler that allows to do this. Example:

class TransactionalCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand>
{
    readonly DbContext context;
    readonly ICommandHandler<TCommand> decorated;

    public TransactionCommandHandlerDecorator(
        DbContext context,
        ICommandHandler<TCommand> decorated)
    {
        this.context = context;
        this.decorated = decorated;
    }

    public void Handle(TCommand command)
    {
        this.decorated.Handle(command);

        context.SaveChanges();
    } 
}

This ensures that you only need to write this infrastructure code once. Any solid DI container allows you to configure such a decorator to be wrapped around all ICommandHandler<T> implementations in a consistent manner.

Parser Error when deploy ASP.NET application

I had the same issue. Ran 5 or 6 hours of researches. A simple solution seems to be working. I just had to convert my folder to application from iis. It worked fine. (this was a scenario where I had done a migration from server 2003 to server 2008 R2)

(1) Open IIS and select the website and the appropriate folder that needs to be converted. Right-click and select Convert to Application.

enter image description here

Access cell value of datatable

data d is in row 0 and column 3 for value d :

DataTable table;
String d = (String)table.Rows[0][3];

Catching "Maximum request length exceeded"

After tag

<security>
     <requestFiltering>
         <requestLimits maxAllowedContentLength="4500000" />
     </requestFiltering>
</security>

add the following tag

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="13" />
  <error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>

you can add the Url to the error page...

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

You can't need using sections in partial view.

Include in your Partial View. It execute the function after jQuery loaded. You can alter de condition clause for your code.

<script type="text/javascript">    
var time = setInterval(function () {
    if (window.jQuery != undefined) {
        window.clearInterval(time);

        //Begin
        $(document).ready(function () {
           //....
        });
        //End
    };
}, 10); </script>

Julio Spader

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Passing arguments to JavaScript function from code-behind

Look at the ScriptManager.RegisterStartupScript method if you're using a ScriptManager or any Ajax controls/asynchronous postbacks.

Edit:

Actually, the function you want is probably ScriptManager.RegisterClientScriptBlock

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

When trying to set up a .NET Core 1.0 website I got this error, and tried everything else I could find with no luck, including checking the web.config file, IIS_IUSRS permissions, IIS URL rewrite module, etc. In the end, I installed DotNetCore.1.0.0-WindowsHosting.exe from this page: https://www.microsoft.com/net/download and it started working right away.

Specific link to download: https://go.microsoft.com/fwlink/?LinkId=817246

Passing multiple argument through CommandArgument of Button in Asp.net

My approach is using the attributes collection to add HTML data- attributes from code behind. This is more inline with jquery and client side scripting.

// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();


// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );

Then retrieve the values through the attribute collection

string val = targetBtn.Attributes["data-{your data name here}"].ToString();

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Below step solved my issue:

Open CMD Prompt with Admin Privileges.

Run : iisreset.

Hope this helps.

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

How do I overload the square-bracket operator in C#?

public class CustomCollection : List<Object>
{
    public Object this[int index]
    {
        // ...
    }
}

How can I implement a tree in Python?

Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be:

class Tree:
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

You can use it like this:

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

If you need an arbitrary number of children per node, then use a list of children:

class Tree:
    def __init__(self, data):
        self.children = []
        self.data = data

left = Tree("left")
middle = Tree("middle")
right = Tree("right")
root = Tree("root")
root.children = [left, middle, right]

How to inherit constructors?

You may be able to adapt a version of the C++ virtual constructor idiom. As far as I know, C# doesn't support covariant return types. I believe that's on many peoples' wish lists.

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

import android packages cannot be resolved

This import android packages cannot be resolved is also occurs when your using some library and that library is not in the same path where your application is there, or if you are importing the library and not coping library to the workspace

Android SDK location

The question doesn't seem to require a programmatic solution, but my Google search brought me here anyway. Here's my C# attempt at detecting where the SDK is installed, based on the most common installation paths.

static string FindAndroidSDKPath()
{
    string uniqueFile = Path.Combine("platform-tools", "adb.exe"); // look for adb in Android folders
    string[] searchDirs =
    {
        // User/AppData/Local
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        // Program Files
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
        // Program Files (x86) (it's okay if we're on 32-bit, we check if this folder exists first)
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " (x86)",
        // User/AppData/Roaming
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    };
    foreach (string searchDir in searchDirs)
    {
        string androidDir = Path.Combine(searchDir, "Android");
        if (Directory.Exists(androidDir))
        {
            string[] subDirs = Directory.GetDirectories(androidDir, "*sdk*", SearchOption.TopDirectoryOnly);
            foreach (string subDir in subDirs)
            {
                string path = Path.Combine(subDir, uniqueFile);
                if (File.Exists(path))
                {
                    // found unique file at DIR/Android
                    return subDir;
                }
            }
        }
    }
    // no luck finding SDK! :(
    return null;
}

I need this because I'm writing an extension to a C# program to work with Android Studio/Gradle. Hopefully someone else will find this approach useful.

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

How to set a value for a selectize.js input?

Here is my full code using tag from remote search. Hope this is helpful.

$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
},
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
            selected_items.push(obj.id);
        });
        selectize.setValue(selected_items); //this will set option values as default
    });
}
});

Convert data.frame column to a vector?

You could use $ extraction:

class(aframe$a1)
[1] "numeric"

or the double square bracket:

class(aframe[["a1"]])
[1] "numeric"

How to run code after some delay in Flutter?

Figured it out

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

How to implement a Map with multiple keys?

How about using a trie data structure ?

http://en.wikipedia.org/wiki/Trie

The root of the trie will by blank. The first level siblings will be your primary keys of the map, the second level siblings will be your secondary keys and the third level will be the terminal nodes which will have the value along will null to indicate termination of that branch. You can also add more than two keys using the same scheme.

Look up is simple DFS.

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

how to kill the tty in unix

I had the same problem today. I had NO remaining processes, but the remaining finger entry of user "xxx", which prevent me the deletion of this user using "userdel xxx".

Error message was: userdel: account `xxx' is currently in use.

It looked like a crashed terminal session. So I rebooted, but the issue remained.

last xxx
xxx      pts/5        10.1.2.3     Fri Feb  7 10:25 - crash  (01:27)

So I (re)moved the /var/run/utmp file:

mv /var/run/utmp /var/run/utmp.save ; touch /var/run/utmp

This cleared all finger entries. Unfortunately in this way even the current running sessions will be cleared. If this is an issue for you, you have to reboot, after you (re)moved the utmp file.

However in my case this was the solution. Afterwards I was able to successfully delete the user, using "userdel xxx".

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

Delete item from state array in react

const array = [...this.state.people];
array.splice(i, 1);
this.setState({people: array});         

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

How to add text to JFrame?

You can add a multi-line label with the following:

JLabel label = new JLabel("My label");

label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");

From here, simply add the label to the frame using the add() method, and you're all set!

How do I implement basic "Long Polling"?

I think the client looks like a normal asynchronous AJAX request, but you expect it to take a "long time" to come back.

The server then looks like this.

while (!hasNewData())
    usleep(50);

outputNewData();

So, the AJAX request goes to the server, probably including a timestamp of when it was last update so that your hasNewData() knows what data you have already got. The server then sits in a loop sleeping until new data is available. All the while, your AJAX request is still connected, just hanging there waiting for data. Finally, when new data is available, the server gives it to your AJAX request and closes the connection.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrapping the existing formula in IFERROR will not achieve:

the average of cells that contain non-zero, non-blank values.

I suggest trying:

=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")

Python unittest passing arguments

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

that will let you run with:

python mytests.py ausername apassword

You need the argv.pops so your command line params don't mess with unittest's own...

[update] The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)            
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

That will let you run with:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...

How do I exit the Vim editor?

Hit the Esc key to enter "Normal mode". Then you can type : to enter "Command-line mode". A colon (:) will appear at the bottom of the screen and you can type in one of the following commands. To execute a command, press the Enter key.

  • :q to quit (short for :quit)
  • :q! to quit without saving (short for :quit!)
  • :wq to write and quit
  • :wq! to write and quit even if file has only read permission (if file does not have write permission: force write)
  • :x to write and quit (similar to :wq, but only write if there are changes)
  • :exit to write and exit (same as :x)
  • :qa to quit all (short for :quitall)
  • :cq to quit without saving and make Vim return non-zero error (i.e. exit with error)

You can also exit Vim directly from "Normal mode" by typing ZZ to save and quit (same as :x) or ZQ to just quit (same as :q!). (Note that case is important here. ZZ and zz do not mean the same thing.)

Vim has extensive help - that you can access with the :help command - where you can find answers to all your questions and a tutorial for beginners.

How to autoplay HTML5 mp4 video on Android?

I simplified the Javascript to trigger the video to start.

_x000D_
_x000D_
 var bg = document.getElementById ("bg"); _x000D_
 function playbg() {_x000D_
   bg.play(); _x000D_
 }
_x000D_
<video id="bg" style="min-width:100%; min-height:100%;"  playsinline autoplay loop muted onload="playbg(); "><source src="Files/snow.mp4" type="video/mp4"></video>_x000D_
</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

*"Files/snow.mp4" is just sample url

setting system property

System.setProperty("gate.home", "/some/directory");

For more information, see:

Difference between break and continue in PHP?

break will stop the current loop (or pass an integer to tell it how many loops to break from).

continue will stop the current iteration and start the next one.

PostgreSQL 'NOT IN' and subquery

When using NOT IN you should ensure that none of the values are NULL:

SELECT mac, creation_date 
FROM logs 
WHERE logs_type_id=11
AND mac NOT IN (
    SELECT mac
    FROM consols
    WHERE mac IS NOT NULL -- add this
)

CKEditor, Image Upload (filebrowserUploadUrl)

With CKeditor version 4 something, the editor expects JSON in return from the server side. Older version may need a text/html type of response, bearing a javascript snippet. See this link for an explanation of that Explanation of return formats. On the server side, and if you are using C#, you can make a data model like this:

namespace editors.Models
{
    public class PostModel
    {
        public string CKEditor { get; set; }  // for older editors
        public string CKEditorFuncNum { get; set; }  // for older editors
        public string langCode { get; set; }  // for older editors
        public int uploaded { get; set; } 
        public string filename { get; set; }
    }
}

And return the result from your upload routine with this:

PostModel fez = new PostModel { CKEditor = "TheEditor1", CKEditorFuncNum = "1", langCode = "en", uploaded = 1, filename = "/images/in/" + filenameVariable };
return Ok(fez);

Although .net most probably makes json of it automatically, ensure you are returning content-type application/json.

As a side-note for those wanting to check if the uploaded file really is an image file; if you are using Asp.net core, the system.drawing library needs to be installed in a non-standard way. Here's how to do that

Also note that you can change the type of posting in the config.js file to config.filebrowserUploadMethod='form'; , as opposed to config.filebrowserUploadMethod='xhr';

How can I load the contents of a text file into a batch file variable?

for /f "delims=" %%i in (count.txt) do set c=%%i
echo %c%
pause

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

Difference Between Cohesion and Coupling

I think the differences can be put as the following:

  • Cohesion represents the degree to which a part of a code base forms a logically single, atomic unit.
  • Coupling represents the degree to which a single unit is independent from others.
  • It’s impossible to archive full decoupling without damaging cohesion, and vice versa.

In this blog post I write about it in more detail.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
    setTimeout(function () {
    window.location = weburl; // http://itunes.apple.com/..
    }, 100);
}, 600);

document.webkitHidden is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com

How to pass arguments to a Button command in Tkinter?

The reason it invokes the method immediately and pressing the button does nothing is that action(somenumber) is evaluated and its return value is attributed as the command for the button. So if action prints something to tell you it has run and returns None, you just run action to evaluate its return value and given None as the command for the button.

To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:

import Tkinter as Tk

frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
frame.grid(row=2,column=2)
frame.pack(fill=Tk.X, padx=5, pady=5)
def action():
    global output
    global variable
    output.insert(Tk.END,variable.get())
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
variable = Tk.Entry(master=frame)
variable.pack()
output = Tk.Text(master=frame)
output.pack()

if __name__ == '__main__':
    Tk.mainloop()

What I would do is make a class whose objects would contain every variable required and methods to change those as needed:

import Tkinter as Tk
class Window:
    def __init__(self):
        self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
        self.frame.grid(row=2,column=2)
        self.frame.pack(fill=Tk.X, padx=5, pady=5)

        self.button = Tk.Button(master=self.frame, text='press', command=self.action)
        self.button.pack()

        self.variable = Tk.Entry(master=self.frame)
        self.variable.pack()

        self.output = Tk.Text(master=self.frame)
        self.output.pack()

    def action(self):
        self.output.insert(Tk.END,self.variable.get())

if __name__ == '__main__':
    window = Window()
    Tk.mainloop()

Attaching click to anchor tag in angular

<a href="#" (click)="onGoToPage2()">Go to page 2</a>

npm install gives error "can't find a package.json file"

In my case there was mistake in my package.json:

npm ERR! package.json must be actual JSON, not just JavaScript.

How can I center text (horizontally and vertically) inside a div block?

Common techniques as of 2014:


  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

    .container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
    

  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

    html, body, .container {
        height: 100%;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto assuming the element is block level.

    html, body {
        height: 100%;
    }
    .parent {
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
    }
    .parent > .child {
        display: table-cell;
        vertical-align: middle;
    }
    

  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

    html, body, .container {
        height: 100%;
    }
    .container {
        position: relative;
        text-align: center;
    }
    .container > p {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        margin-top: -9px;
    }
    

  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

    .parent {
        height: 200px;
        width: 400px;
        text-align: center;
    }
    .parent > .child {
        line-height: 200px;
    }
    

Methods 4 and 5 aren't the most reliable. Go with one of the first 3.

Docker error response from daemon: "Conflict ... already in use by container"

No issues with the latest kartoza/qgis-desktop

I ran

docker pull kartoza/qgis-desktop

followed by

docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest

I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.

Unresolved external symbol on static class members

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

Clean up a fork and restart it from the upstream

Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.

remote: error: GH003: Sorry, force-pushing to master is not allowed.

If you get an error message like this one please try the following steps.

To effectively reset your fork you need to follow these steps :

git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin

Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :

git checkout master
git push --force origin

Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :

git push origin --delete tmp_master
git branch -D tmp_master

Other answers warning about lossing your change still apply, be carreful.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Aha! I beat this problem! My god, it was a beast for someone like me with limited IIS experience. I really thought I was going to be spending all weekend fixing it.

Here's the solution for anyone else who ever comes this evil problem.

First thing to be aware of: If you're hoping this is your solution, make sure that you have the same Error Code (0x8007000d) and Config Source (-1: 0:). If not, this isn't your solution.

Next thing to be aware of: AJAX is not properly installed in your web.config!

Fix that by following this guide:
http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

Then, install the AJAX 1.0 extensions on your production server, from this link:

http://www.asp.net/ajax/downloads/archive/
Update: Microsoft seems to have removed the above page :(

That's it!

How do I execute a *.dll file

While many people have pointed out that you can't execute dlls directly and should use rundll32.exe to execute exported functions instead, here is a screenshot of an actual dll file running just like an executable:

enter image description here

While you cannot run dll files directly, I suspect it is possible to run them from another process using a WinAPI function CreateProcess:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

For existing mysql 8.0 installs on Windows 10 mysql,

  1. launch installer,

  2. click "Reconfigure" under QuickAction (to the left of MySQL Server), then

  3. click next to advance through the next 2 screens until arriving

  4. at "Authentication Method", select "Use Legacy Authentication Method (Retain MySQL 5.x compatibility"

  5. Keep clicking until install is complete

How would I run an async Task<T> method synchronously?

If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.

Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await operator.

Most of the time, you'll be using await on an expression of type Task. Task's implementation of the await pattern is "smart" in that it defers to the SynchronizationContext, which basically causes the following to happen:

  1. If the thread entering the await is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.
  2. If the thread entering the await is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.

That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.

.... backing up! ....

I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:

  1. [Top] WebRequest.GetResponse()
  2. YourCode.HelperMethod()
  3. YourCode.AnotherMethod()
  4. YourCode.EventHandlerMethod()
  5. [UI Code].Plumbing() - WPF or WinForms Code
  6. [Message Loop] - WPF or WinForms Message Loop

Then once the code has been transformed to use async, you'll typically end up with

  1. [Top] WebRequest.GetResponseAsync()
  2. YourCode.HelperMethodAsync()
  3. YourCode.AnotherMethodAsync()
  4. YourCode.EventHandlerMethodAsync()
  5. [UI Code].Plumbing() - WPF or WinForms Code
  6. [Message Loop] - WPF or WinForms Message Loop

Actually Answering

The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.

Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:

var customerList = TaskEx.RunEx(GetCustomers).Result;

The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).

How to insert a new line in strings in Android

Try using System.getProperty("line.separator") to get a new line.

Iterate over values of object

You could use underscore.js and the each function:

_.each({key1: "value1", key2: "value2"}, function(value) {
  console.log(value);
});

Response::json() - Laravel 5.1

After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']); . Or you can just return the array return array('success' => 'hi, atiq'); which will be rendered as json in Laravel version 5.2 .

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to prevent XSS with HTML/PHP?

Cross-posting this as a consolidated reference from the SO Documentation beta which is going offline.

Problem

Cross-site scripting is the unintended execution of remote code by a web client. Any web application might expose itself to XSS if it takes input from a user and outputs it directly on a web page. If input includes HTML or JavaScript, remote code can be executed when this content is rendered by the web client.

For example, if a 3rd party side contains a JavaScript file:

// http://example.com/runme.js
document.write("I'm running");

And a PHP application directly outputs a string passed into it:

<?php
echo '<div>' . $_GET['input'] . '</div>';

If an unchecked GET parameter contains <script src="http://example.com/runme.js"></script> then the output of the PHP script will be:

<div><script src="http://example.com/runme.js"></script></div>

The 3rd party JavaScript will run and the user will see "I'm running" on the web page.

Solution

As a general rule, never trust input coming from a client. Every GET parameter, POST or PUT content, and cookie value could be anything at all, and should therefore be validated. When outputting any of these values, escape them so they will not be evaluated in an unexpected way.

Keep in mind that even in the simplest applications data can be moved around and it will be hard to keep track of all sources. Therefore it is a best practice to always escape output.

PHP provides a few ways to escape output depending on the context.

Filter Functions

PHPs Filter Functions allow the input data to the php script to be sanitized or validated in many ways. They are useful when saving or outputting client input.

HTML Encoding

htmlspecialchars will convert any "HTML special characters" into their HTML encodings, meaning they will then not be processed as standard HTML. To fix our previous example using this method:

<?php
echo '<div>' . htmlspecialchars($_GET['input']) . '</div>';
// or
echo '<div>' . filter_input(INPUT_GET, 'input', FILTER_SANITIZE_SPECIAL_CHARS) . '</div>';

Would output:

<div>&lt;script src=&quot;http://example.com/runme.js&quot;&gt;&lt;/script&gt;</div>

Everything inside the <div> tag will not be interpreted as a JavaScript tag by the browser, but instead as a simple text node. The user will safely see:

<script src="http://example.com/runme.js"></script>

URL Encoding

When outputting a dynamically generated URL, PHP provides the urlencode function to safely output valid URLs. So, for example, if a user is able to input data that becomes part of another GET parameter:

<?php
$input = urlencode($_GET['input']);
// or
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_URL);
echo '<a href="http://example.com/page?input="' . $input . '">Link</a>';

Any malicious input will be converted to an encoded URL parameter.

Using specialised external libraries or OWASP AntiSamy lists

Sometimes you will want to send HTML or other kind of code inputs. You will need to maintain a list of authorised words (white list) and un-authorized (blacklist).

You can download standard lists available at the OWASP AntiSamy website. Each list is fit for a specific kind of interaction (ebay api, tinyMCE, etc...). And it is open source.

There are libraries existing to filter HTML and prevent XSS attacks for the general case and performing at least as well as AntiSamy lists with very easy use. For example you have HTML Purifier

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

What is the syntax to insert one list into another list in python?

The question does not make clear what exactly you want to achieve.

List has the append method, which appends its argument to the list:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]

There's also the extend method, which appends items from the list you pass as an argument:

>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]

And of course, there's the insert method which acts similarly to append but allows you to specify the insertion point:

>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]

To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):

>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]

List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:

>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Do you have Excel installed on the server? The interop interfaces you're using are used to automate Excel which requires that the Excel application is installed there. Each page request cycle will potentially launch a separate instance of excel.exe. I would strongly advise against doing this as part of a web application.

Why do you want to do this? If you are wanting to generate Excel documents, there are much better ways to do this, including OpenXML as mentioned elsewhere on this thread. Please do not run Excel on the server!

Link to OpenXML SDK download: http://www.microsoft.com/en-us/download/details.aspx?id=5124

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Correct path for img on React.js

If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.

public/images/

<img src="/images/logo.png" />

Making a WinForms TextBox behave like your browser's address bar

Click event of textbox? Or even MouseCaptureChanged event works for me. - OK. doesn't work.

So you have to do 2 things:

private bool f = false;

private void textBox_MouseClick(object sender, MouseEventArgs e)
{ 
  if (this.f) { this.textBox.SelectAll(); }
  this.f = false;
}

private void textBox_Enter(object sender, EventArgs e)
{
  this.f = true;
  this.textBox.SelectAll();
}
private void textBox_MouseMove(object sender, MouseEventArgs e) // idea from the other answer
{
  this.f = false; 
}

Works for tabbing (through textBoxes to the one) as well - call SelectAll() in Enter just in case...

How do I use raw_input in Python 3

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.

From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.

Use a command-prompt

When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Weeble\My Python Program>_

To run your program, type the following (substituting your script name):

    python myscript.py

...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.

Use IDLE

IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.

When to use setAttribute vs .attribute= in JavaScript?

methods for setting attributes(for example class) on an element: 1. el.className = string 2. el.setAttribute('class',string) 3. el.attributes.setNamedItem(object) 4. el.setAttributeNode(node)

I have made a simple benchmark test (here)

and it seems that setAttributeNode is about 3 times faster then using setAttribute.

so if performance is an issue - use "setAttributeNode"

Why is 1/1/1970 the "epoch time"?

Short answer: Why not?

Longer answer: The time itself doesn't really matter, as long as everyone who uses it agrees on its value. As 1/1/70 has been in use for so long, using it will make you code as understandable as possible for as many people as possible.

There's no great merit in choosing an arbitrary epoch just to be different.

What's the difference between UTF-8 and UTF-8 without BOM?

As mentioned above, UTF-8 with BOM may cause problems with non-BOM-aware (or compatible) software. I once edited HTML files encoded as UTF-8 + BOM with the Mozilla-based KompoZer, as a client required that WYSIWYG program.

Invariably the layout would get destroyed when saving. It took my some time to fiddle my way around this. These files then worked well in Firefox, but showed a CSS quirk in Internet Explorer destroying the layout, again. After fiddling with the linked CSS files for hours to no avail I discovered that Internet Explorer didn't like the BOMfed HTML file. Never again.

Also, I just found this in Wikipedia:

The shebang characters are represented by the same two bytes in extended ASCII encodings, including UTF-8, which is commonly used for scripts and other text files on current Unix-like systems. However, UTF-8 files may begin with the optional byte order mark (BOM); if the "exec" function specifically detects the bytes 0x23 0x21, then the presence of the BOM (0xEF 0xBB 0xBF) before the shebang will prevent the script interpreter from being executed. Some authorities recommend against using the byte order mark in POSIX (Unix-like) scripts,[15] for this reason and for wider interoperability and philosophical concerns

image processing to improve tesseract OCR accuracy

What was EXTREMLY HELPFUL to me on this way are the source codes for Capture2Text project. http://sourceforge.net/projects/capture2text/files/Capture2Text/.

BTW: Kudos to it's author for sharing such a painstaking algorithm.

Pay special attention to the file Capture2Text\SourceCode\leptonica_util\leptonica_util.c - that's the essence of image preprocession for this utility.

If you will run the binaries, you can check the image transformation before/after the process in Capture2Text\Output\ folder.

P.S. mentioned solution uses Tesseract for OCR and Leptonica for preprocessing.

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

iPhone SDK on Windows (alternative solutions)

You could do what saurik of Cydia does, and write your code on a PC then build it on the iPhone itself (it is a Mac, technically!) after you jailbreak it. However, you don't get Interface Builder, so you're basically creating UIs in code by hand. It'd also be pretty tough to actually submit your app without a Mac.

How to implement linear interpolation?

def interpolate(x1: float, x2: float, y1: float, y2: float, x: float):
    """Perform linear interpolation for x between (x1,y1) and (x2,y2) """

    return ((y2 - y1) * x + x2 * y1 - x1 * y2) / (x2 - x1)

PHP script to loop through all of the files in a directory?

If you don't have access to DirectoryIterator class try this:

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.

How to add two strings as if they were numbers?

document.getElementById(currentInputChoosen).value -= +-100;

Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.

Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.

Don't know if it is a dirty workaround, or actually legit.

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

Removing all script tags from html with JS Regular Expression

This Regex should work too:

<script(?:(?!\/\/)(?!\/\*)[^'"]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/.*(?:\n)|\/\*(?:(?:.|\s))*?\*\/)*?<\/script>

It even allows to have "problematic" variable strings like these inside:

<script type="text/javascript">
   var test1 = "</script>";
   var test2 = '\'</script>';
   var test1 = "\"</script>";
   var test1 = "<script>\"";
   var test2 = '<scr\'ipt>';
   /* </script> */
   // </script>
   /* ' */
   // var foo=" '
</script>

It seams that jQuery and Prototype fail on these ones...

Edit July 31 '17: Added a) non-capturing groups for better performance (and no empty groups) and b) support for JavaScript comments.

jQuery ui datepicker with Angularjs

var selectDate = element.datepicker({
    dateFormat:'dd/mm/yy',
    onSelect:function (date) {
        ngModelCtrl.$setViewValue(date);
        scope.$apply();
    }
}).on('changeDate', function(ev) {
    selectDate.hide();
    ngModelCtrl.$setViewValue(element.val());
    scope.$apply();
});                            

How to make full screen background in a web page

I found the reason why there is always a white boder of the background image, if I put the image in a 'div' element inside 'body'. But the image can be full screen, if I put it as background image of 'body'.

Because the default 'margin' of 'body' is not zero. After add this css, the background image can be full screen even I put it in 'div'.

body {
    margin: 0px;
}

SQL Server - SELECT FROM stored procedure

You can

  1. create a table variable to hold the result set from the stored proc and then
  2. insert the output of the stored proc into the table variable, and then
  3. use the table variable exactly as you would any other table...

... sql ....

Declare @T Table ([column definitions here])
Insert @T Exec storedProcname params 
Select * from @T Where ...

ASP.NET: Session.SessionID changes between requests

in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.

In summary

pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

TypeError: $(...).autocomplete is not a function

Just add these to libraries to your project:

<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

Save and reload. You're good to go.

Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Can I change the checkbox size using CSS?

you can chnage the height and width in the code below

_x000D_
_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 20px;_x000D_
    width: 20px;_x000D_
    border-radius:5px;_x000D_
    border:1px solid #ff7e02;_x000D_
}
_x000D_
<div class="check">_x000D_
_x000D_
     <label class="container1">Architecture/Landscape_x000D_
            _x000D_
_x000D_
    <input type="checkbox" checked="checked">_x000D_
            _x000D_
_x000D_
    <span class="checkmark"></span>_x000D_
         _x000D_
_x000D_
 </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to replace all dots in a string using JavaScript

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

You could try this :

"okay.this.is.a.string".split(".").join("")

Greetings

Printing tuple with string formatting in Python

Try this to get an answer:

>>>d = ('1', '2') 
>>> print("Value: %s" %(d))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

If we put only-one tuple inside (), it makes a tuple itself:

>>> (d)
('1', '2')

This means the above print statement will look like: print("Value: %s" %('1', '2')) which is an error!

Hence:

>>> (d,)
(('1', '2'),)
>>> 

Above will be fed correctly to the print's arguments.

How do I ignore ampersands in a SQL script running from SQL Plus?

If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in || Chr(38) || or append it as a single character as in || '&' ||.

C++ undefined reference to defined function

The declaration and definition of insertLike are different

In your header file:

void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);

In your 'function file':

void insertLike(const char sentence[], const int lengthTo, const int length,char writeTo[]);

C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.

In this case, insertLike which takes const char* as its fourth parameter and insertLike which takes char * as its fourth parameter are different functions.

Responsive design with media query : screen size?

i will provide mine because @muni s solution was a bit overkill for me

note: if you want to add custom definitions for several resolutions together, say something like this:

//mobile generally   
 @media screen and (max-width: 1199)  {

      .irns-desktop{
        display: none;
      }

      .irns-mobile{
        display: initial;
      }

    }

Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')

//here all definitions to apply globally


//desktop
@media only screen
and (min-width : 1200) {


}

//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px)  {

} // end media query

//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px)  {

}//end media definition


//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px)  {

}//end media query



//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {

}

//end media query

PHP ternary operator vs null coalescing operator

When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Here's some example code to demonstrate this:

<?php

$a = null;

print $a ?? 'b'; // b
print "\n";

print $a ?: 'b'; // b
print "\n";

print $c ?? 'a'; // a
print "\n";

print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";

$b = array('a' => null);

print $b['a'] ?? 'd'; // d
print "\n";

print $b['a'] ?: 'd'; // d
print "\n";

print $b['c'] ?? 'e'; // e
print "\n";

print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";

The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.

Execute the code: https://3v4l.org/McavC

Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.

So:

$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'

would then have $a be equal to false and $b equal to 'g'.

Php artisan make:auth command is not defined

In short and precise, all you need to do is

composer require laravel/ui --dev

php artisan ui vue --auth and then the migrate php artisan migrate.

Just for an overview of Laravel Authentication

Laravel Authentication facilities comes with Guard and Providers, Guards define how users are authenticated for each request whereas Providers define how users are retrieved from you persistent storage.

Database Consideration - By default Laravel includes an App\User Eloquent Model in your app directory.

Auth Namespace - App\Http\Controllers\Auth

Controllers - RegisterController, LoginController, ForgotPasswordController and ResetPasswordController, all names are meaningful and easy to understand!

Routing - Laravel/ui package provides a quick way to scaffold all the routes and views you need for authentication using a few simple commands (as mentioned in the start instead of make:auth).

You can disable any newly created controller, e. g. RegisterController and modify your route declaration like, Auth::routes(['register' => false]); For further detail please look into the Laravel Documentation.

What is the difference between bool and Boolean types in C#

No actual difference unless you get the type string. There when you use reflection or GetType() you get {Name = "Boolean" FullName = "System.Boolean"} for both.

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

Changing Background Image with CSS3 Animations

You can follow by this code:

_x000D_
_x000D_
#cd{_x000D_
  position: relative;_x000D_
  margin: 0 auto;_x000D_
  height: 281px;_x000D_
  width: 450px;_x000D_
}_x000D_
#cf img{_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  -moz-transition: opacity 1s ease-in-out;_x000D_
  transition: opacity 1s ease-in-out;_x000D_
}_x000D_
#cf img.top:hover{_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div id="cf">_x000D_
  <img class="button" src="Birdman.jpg" />_x000D_
  <img src="Turtle.jpg" class="top" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Set Scrollview in view

  - (void)textFieldDidBeginEditing:(UITextField *)textField
    {
     CGPoint point;
    if(textField == txtEmail){
      // -90 is for my you can change as per your postion
      point = CGPointMake(0, textField.frame.origin.y - 90);
    }
    else if (textField == txtContact){
      point = CGPointMake(0, textField.frame.origin.y - 90);
    }
      [scrollV setContentOffset:point animated:YES];
    }

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.

  1. Generate CA and the certificates (you can use openssl: Generating CA and self-signed certificates.
  2. Install root certificate (*.cer file) on the device - you can open it by Safari and it should redirect you to Settings
  3. When the certificated is installed, go to Certificate Trust Settings (Settings > General > About > Certificate Trust Settings) as in MattP answer.

If it is not possible then you need to change server trust evaluation.

More info in this document: Technical Q&A QA1948 HTTPS and Test Servers

CMake not able to find OpenSSL library

I had the same problem (openssl) and this worked for me on Ubuntu 14.04.1 LTS. The solution is the same up to Ubuntu 18.04 (tested).

sudo apt-get install libssl-dev

Open images? Python

Instead of

Image.open(picture.jpg)
Img.show

You should have

from PIL import Image

#...

img = Image.open('picture.jpg')
img.show()

You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using %s or .format()).

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

  1. Execute: cordova plugin rm cordova-plugin-compat --force
  2. Execute: cordova plugin add [email protected]
  3. Change : config.xml in your project folder use "6.2.3" not "^6.2.3", then delete the platforms/android folder, re-run cordova prepare android, and cordova build android

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

How to POST request using RestSharp

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }

Swift 3 - Comparing Date objects

I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.

let date1 = Date()
let date2 = Date().addingTimeInterval(100)

if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

I tried majority of the solutions provided in this answer blog, however none of them worked, I had this ssl certificant error as I try to install python packages.

I succeed by following command:

python -m pip install PACKAGENAME --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org 

Storing money in a decimal column - what precision and scale?

The money datatype on SQL Server has four digits after the decimal.

From SQL Server 2000 Books Online:

Monetary data represents positive or negative amounts of money. In Microsoft® SQL Server™ 2000, monetary data is stored using the money and smallmoney data types. Monetary data can be stored to an accuracy of four decimal places. Use the money data type to store values in the range from -922,337,203,685,477.5808 through +922,337,203,685,477.5807 (requires 8 bytes to store a value). Use the smallmoney data type to store values in the range from -214,748.3648 through 214,748.3647 (requires 4 bytes to store a value). If a greater number of decimal places are required, use the decimal data type instead.

SQL: Insert all records from one table to another table without specific the columns

You need to have at least the same number of columns and each column has to be defined in exactly the same way, i.e. a varchar column can't be inserted into an int column.

For bulk transfer, check the documentation for the SQL implementation you're using. There are often tools available to bulk transfer data from one table to another. For SqlServer 2005, for example, you could use the SQL Server Import and Export Wizard. Right-click on the database you're trying to move data around in and click Export to access it.

How can one check to see if a remote file exists using PHP?

PHP's inbuilt functions may not work for checking URL if allow_url_fopen setting is set to off for security reasons. Curl is a better option as we would not need to change our code at later stage. Below is the code I used to verify a valid URL:

$url = str_replace(' ', '%20', $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
curl_close($ch);
if($httpcode>=200 && $httpcode<300){  return true; } else { return false; } 

Kindly note the CURLOPT_SSL_VERIFYPEER option which also verify the URL's starting with HTTPS.

What is the difference between POST and GET?

POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.

POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.

Path of assets in CSS files in Symfony 2

I have came across the very-very-same problem.

In short:

  • Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)
  • Willing to have the images in the "public" dir (Resources/public/images/devil.png)
  • Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png

I have made a test with ALL possible (sane) combinations of the following:

  • @notation, relative notation
  • Parse with cssrewrite, without it
  • CSS image background vs direct <img> tag src= to the very same image than CSS
  • CSS parsed with assetic and also without parsing with assetic direct output
  • And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).

This gave me a total of 14 combinations on the same twig, and this route was launched from

  • "/app_dev.php/"
  • "/app.php/"
  • and "/"

thus giving 14 x 3 = 42 tests.

Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.

The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.

I observed the following:

Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.

These are the results:

  1. Result launched with /app_dev.php/ Result launched with /app_dev.php/

  2. Result launched with /app.php/ Result launched with /app.php/

  3. Result launched with / enter image description here

So... ONLY - The second image - Div B - Div C are the allowed syntaxes.

Here there is the TWIG code:

<html>
    <head>
            {% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: ABCDEF #}

            <link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets 'bundles/commondirty/css_original/d.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: GHIJKL #}

            <link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    </head>
    <body>
        <div class="container">
            <p>
                <img alt="Devil" src="../bundles/commondirty/images/devil.png">
                <img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
            </p>
            <p>
                <div class="a">
                    A
                </div>
                <div class="b">
                    B
                </div>
                <div class="c">
                    C
                </div>
                <div class="d">
                    D
                </div>
                <div class="e">
                    E
                </div>
                <div class="f">
                    F
                </div>
            </p>
            <p>
                <div class="g">
                    G
                </div>
                <div class="h">
                    H
                </div>
                <div class="i">
                    I
                </div>
                <div class="j">
                    J
                </div>
                <div class="k">
                    K
                </div>
                <div class="l">
                    L
                </div>
            </p>
        </div>
    </body>
</html>

The container.css:

div.container
{
    border: 1px solid red;
    padding: 0px;
}

div.container img, div.container div 
{
    border: 1px solid green;
    padding: 5px;
    margin: 5px;
    width: 64px;
    height: 64px;
    display: inline-block;
    vertical-align: top;
}

And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.

.a
{
    background: red url('../images/devil.png');
}

The "directories" structure is:

Directories Directories

All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.

But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:

Compilation process Compilation process

Note I do this for the --env=prod environment.

Just a few final thoughts:

  • This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.

  • Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.

  • Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.

BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.

So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.

The winner is C

The winner is C

JSON.stringify doesn't work with normal Javascript array

JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.

The JSON array data type cannot have named keys on an array.

When you pass a JavaScript array to JSON.stringify the named properties will be ignored.

If you want named properties, use an Object, not an Array.

_x000D_
_x000D_
const test = {}; // Object_x000D_
test.a = 'test';_x000D_
test.b = []; // Array_x000D_
test.b.push('item');_x000D_
test.b.push('item2');_x000D_
test.b.push('item3');_x000D_
test.b.item4 = "A value"; // Ignored by JSON.stringify_x000D_
const json = JSON.stringify(test);_x000D_
console.log(json);
_x000D_
_x000D_
_x000D_

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

In where shall I use isset() and !empty()

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

The more secure option would be to add allowedHosts to your Webpack config like this:

module.exports = {
devServer: {
 allowedHosts: [
  'host.com',
  'subdomain.host.com',
  'subdomain2.host.com',
  'host2.com'
   ]
  }
};

The array contains all allowed host, you can also specify subdomians. check out more here

new DateTime() vs default(DateTime)

No, they are identical.

default(), for any value type (DateTime is a value type) will always call the parameterless constructor.

How do I add a margin between bootstrap columns without wrapping

Change the number of @grid-columns. Then use -offset. Changing the number of columns will allow you to control the amount of space between columns. E.g.

variables.less (approx line 294).

@grid-columns:              20;

someName.html

<div class="row">
  <div class="col-md-4 col-md-offset-1">First column</div>
  <div class="col-md-13 col-md-offset-1">Second column</div>
</div>

Copy table from one database to another

If you need the entire table structure (not just the basic data layout), use Task>Script Table As>Create To>New Query Window and run in your new database. Then you can copy the data at your leisure.

Most efficient way to reverse a numpy array

I will expand on the earlier answer about np.fliplr(). Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock() will be used to keep time, which is presented in terms of seconds.

import time
import numpy as np

start = time.clock()
x = np.array(range(3))
#transform to 2d
x = np.atleast_2d(x)
#flip array
x = np.fliplr(x)
#take first (and only) element
x = x[0]
#print x
end = time.clock()
print end-start

With print statement uncommented:

[2 1 0]
0.00203907123594

With print statement commented out:

5.59799927506e-05

So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.

np.fliplr(np.atleast_2d(np.array(range(3))))[0]

ReactJS: Warning: setState(...): Cannot update during an existing state transition

THE PROBLEM is here: onClick={this.handleButtonChange(false)}

When you pass this.handleButtonChange(false) to onClick, you are actually calling the function with value = false and setting onClick to the function's return value, which is undefined. Also, calling this.handleButtonChange(false) then calls this.setState() which triggers a re-render, resulting in an infinite render loop.

THE SOLUTION is to pass the function in a lambda: onClick={() => this.handleButtonChange(false)}. Here you are setting onClick to equal a function that will call handleButtonChange(false) when the button is clicked.

The below example may help:

function handleButtonChange(value){
  console.log("State updated!")
}

console.log(handleButtonChange(false))
//output: State updated!
//output: undefined

console.log(() => handleButtonChange(false))
//output: ()=>{handleButtonChange(false);}

Image Greyscale with CSS & re-color on mouse-over?

You can use a sprite which has both version—the colored and the monochrome—stored into it.

RegExp matching string not starting with my

^(?!my)\w+$

should work.

It first ensures that it's not possible to match my at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$. In this case, backreference 1 will contain the name of the variable.

And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_], use

^(?!my)[A-Za-z_]\w*$

Note the change from + to *.

Android OnClickListener - identify a button

Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.button1){
        Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
    }
}

Check this article for more details

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to print Unicode character in Python?

I use Portable winpython in Windows, it includes IPython QT console, I could achieve the following.

>>>print ("??")
??

>>>print ("????")
????

>>>str = "??"


>>>print (str)
??

your console interpreter should support unicode in order to show unicode characters.

Extracting jar to specified directory

There is no such option available in jar command itself. Look into the documentation:

-C dir Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument. Its operation is intended to be similar to the -C option of the UNIX tar utility. For example: jar uf foo.jar -C classes bar.class changes to the classes directory and add the bar.class from that directory to foo.jar. The following command, jar uf foo.jar -C classes . -C bin xyz.class changes to the classes directory and adds to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then changes back to the original directory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files bar1 and bar2, then here's what the jar file contains using jar tf foo.jar: META-INF/

META-INF/MANIFEST.MF

bar1

bar2

xyz.class

CSS full screen div with text in the middle

The accepted answer works, but if:

  • you don't know the content's dimensions
  • the content is dynamic
  • you want to be future proof

use this:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

More information about centering content in this excellent CSS-Tricks article.


Also, if you don't need to support old browsers: a flex-box makes this a piece of cake:

.center{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

<uses-library
            android:name="com.google.android.maps"
            android:required="false" />

if required is true, maybe you need to change

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

If you look at the code for the $.click function, I'll bet there is a conditional statement that checks to see if the element has listeners registered for theclick event before it proceeds. Why not just get the href attribute from the link and manually change the page location?

 window.location.href = $('a').attr('href');

Here is why it doesn't click through. From the trigger function, jQuery source for version 1.3.2:

 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
 if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
     event.result = false;

 // Trigger the native events (except for clicks on links)
 if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
     this.triggered = true;
     try {
         elem[ type ]();
         // Prevent Internet Explorer from throwing an error for some hidden elements
     }
     catch (e)
     {
     }
 }

After it calls handlers (if there are any), jQuery triggers an event on the object. However it only calls native handlers for click events if the element is not a link. I guess this was done purposefully for some reason. This should be true though whether an event handler is defined or not, so I'm not sure why in your case attaching an event handler caused the native onClick handler to be called. You'll have to do what I did and step through the execution to see where it is being called.

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides ld-linux.so.2

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    : ld-linux.so.2

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

ASP.NET MVC Razor pass model to layout

old question but just to mention the solution for MVC5 developers, you can use the Model property same as in view.

The Model property in both view and layout is assosiated with the same ViewDataDictionary object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName in the layout.

But notice that when you use @Model.XXX in the layout the intelliSense context menu will not appear because the Model here is a dynamic object just like ViewBag.

Counting number of lines, words, and characters in a text file

in.next(); is consuming all the lines in the first while(). After the end of your first while loop, there are no more characters to be read at the input stream.

You should nest your character and word-counting within a while loop counting lines.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This happened if you change something in data set using native sql query but persisted object for same data set is present in session cache. Use session.evict(yourObject);

SQL "select where not in subquery" returns no results

Let's suppose these values for common_id:

Common - 1
Table1 - 2
Table2 - 3, null

We want the row in Common to return, because it doesn't exist in any of the other tables. However, the null throws in a monkey wrench.

With those values, the query is equivalent to:

select *
from Common
where 1 not in (2)
and 1 not in (3, null)

That is equivalent to:

select *
from Common
where not (1=2)
and not (1=3 or 1=null)

This is where the problem starts. When comparing with a null, the answer is unknown. So the query reduces to

select *
from Common
where not (false)
and not (false or unkown)

false or unknown is unknown:

select *
from Common
where true
and not (unknown)

true and not unkown is also unkown:

select *
from Common
where unknown

The where condition does not return records where the result is unkown, so we get no records back.

One way to deal with this is to use the exists operator rather than in. Exists never returns unkown because it operates on rows rather than columns. (A row either exists or it doesn't; none of this null ambiguity at the row level!)

select *
from Common
where not exists (select common_id from Table1 where common_id = Common.common_id)
and not exists (select common_id from Table2 where common_id = Common.common_id)

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

How can you get the active users connected to a postgreSQL database via SQL?

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

Select rows of a matrix that meet a condition

m <- matrix(1:20, ncol = 4) 
colnames(m) <- letters[1:4]

The following command will select the first row of the matrix above.

subset(m, m[,4] == 16)

And this will select the last three.

subset(m, m[,4] > 17)

The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with

mf <- data.frame(m)

Then you can select with

mf[ mf$a == 16, ]

Or, you could use the subset command.

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

Add newline to VBA or Visual Basic 6

Visual Basic has built-in constants for newlines:

vbCr = Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family

vbLf = Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X

vbCrLf = Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows

vbNewLine = the same as vbCrLf

if statements matching multiple values

Using Linq,

if(new int[] {1, 2}.Contains(value))

But I'd have to think that your original if is faster.

Converting int to string in C

Like Edwin suggested, use snprintf:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    int n = 1234;
    char buf[10];
    snprintf(buf, 10, "%d", n);
    printf("%s\n", buf);
    return 0;
}

How can I clone a private GitLab repository?

You have your ssh clone statement wrong: git clone username [email protected]:root/test.git

That statement would try to clone a repository named username into the location relative to your current path, [email protected]:root/test.git.

You want to leave out username:

git clone [email protected]:root/test.git

Socket.IO - how do I get a list of connected sockets/clients?

After socket.io 1.0 we cannot use

io.sockets.clients(); 
or
io.sockets.clients('room'); 

anymore. Instead you can use the following

var clients_in_the_room = io.sockets.adapter.rooms[roomId]; 
for (var clientId in clients_in_the_room ) {
  console.log('client: %s', clientId); //Seeing is believing 
  var client_socket = io.sockets.connected[clientId];//Do whatever you want with this
}

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

The split() method in Java does not work on a dot (.)

java.lang.String.split splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Difference between <? super T> and <? extends T> in Java

You can go through all the answers above to understand why the .add() is restricted to '<?>', '<? extends>', and partly to '<? super>'.

But here's the conclusion of it all if you want to remember it, and dont want to go exploring the answer every time:

List<? extends A> means this will accept any List of A and subclass of A. But you cannot add anything to this list. Not even objects of type A.

List<? super A> means this will accept any list of A and superclass of A. You can add objects of type A and its subclasses.

Solving a "communications link failure" with JDBC and MySQL

In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:

version: '2'

services:
    mdb:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        …

White spaces are required between publicId and systemId

Change the order of statments. For me, changing the block of code

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/beans/spring-beans.xsd" 

with

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context"

is valid.

how to get the value of a textarea in jquery?

Value of textarea is also taken with val method:

var message = $('textarea#message').val();

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

Change Oracle port from port 8080

Oracle (database) can use many ports. when you install the software it scans for free ports and decides which port to use then.

The database listener defaults to 1520 but will use 1521 or 1522 if 1520 is not available. This can be adjusted in the listener.ora files.

The Enterprise Manager, web-based database administration tool defaults to port 80 but will use 8080 if 80 is not available.

See here for details on how to change the port number for enterprise manager: http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

iOS: Modal ViewController with transparent background

This following code only works on the iPad.

self.view.backgroundColor = [UIColor clearColor];
self.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentModalViewController:modalVC animated:YES];

I would go with adding a sub view.

Here is a very good discussion. Look at the comments specifically. Not only the answer.

Modal View

If I were you I wouldn't do it. I would add a sub view and do it. It seems to give me a better control over things.

EDIT:

As mentioned by Paul Linsay, since iOS 8 all that's needed is UIModalPresentationOverFullScreen for the modalPresentationStyle of the ViewController being presented. This would also cover of navigationBar and tabBar buttons.

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How to leave a message for a github.com user

Does GitHub have this social feature?

If the commit email is kept private, GitHub now (July 2020) proposes:

Users and organizations can now add Twitter usernames to their GitHub profiles

You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.

We've also added the latest changes:

  • Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
  • All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
  • When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.

That could be a workaround to leave a message to a GitHub user.

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

That gives me the following output on my machine:

Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

gives

Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

How to pass multiple values through command argument in Asp.net?

Use OnCommand event of imagebutton. Within it do

<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>

Code-behind:

void CommandBtn_Click(Object sender, CommandEventArgs e) 
{    
    switch(e.CommandName)
    {
        case "Something":
            // Do your code
            break;
        default:              
            break; 

    }
}

Unexpected token < in first line of HTML

I had the same issue. I published the angular/core application on iis.

To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

Enabling error display in PHP via htaccess only

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess. This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

How can I build for release/distribution on the Xcode 4?

They've bundled all the target/build configuration/debugging options stuff into "schemes". The transition guide has a good explanation.

Android: Go back to previous activity

You can try this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Targeting only Firefox with CSS

Using -engine specific rules ensures effective browser targeting.

<style type="text/css">

    //Other browsers
    color : black;


    //Webkit (Chrome, Safari)
    @media screen and (-webkit-min-device-pixel-ratio:0) { 
        color:green;
    }

    //Firefox
    @media screen and (-moz-images-in-menus:0) {
        color:orange;
    }
</style>

//Internet Explorer
<!--[if IE]>
     <style type='text/css'>
        color:blue;
    </style>
<![endif]-->

Transposing a 1D NumPy array

The transpose of

x = [[0 1],
     [2 3]]

is

xT = [[0 2],
      [1 3]]

well the code is:

x = array([[0, 1],[2, 3]]);
np.transpose(x)        

this a link for more information:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html

How to concat string + i?

Try the following:

for i = 1:4
    result = strcat('f',int2str(i));
end

If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning:

filename = strcat('c:\...\name',int2str(i),'.png'); 

Radio Buttons "Checked" Attribute Not Working

_x000D_
_x000D_
**Radio button aria-checked: true or false one at a time**_x000D_
_x000D_
$('input:radio[name=anynameofinput]').change(function() {_x000D_
            if (this.value === 'value1') {_x000D_
                $("#id1").attr("aria-checked","true");_x000D_
                $("#id2").attr("aria-checked","false");_x000D_
            }_x000D_
            else if (this.value === 'value2') {;_x000D_
                $("#id2").attr("aria-checked","true");_x000D_
                $("#id1").attr("aria-checked","false");_x000D_
            }_x000D_
   });
_x000D_
_x000D_
_x000D_

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

protected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
        doPost(request, response);
}

And Voila!

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

Creating custom function in React component

Another way:

export default class Archive extends React.Component { 

  saySomething = (something) => {
    console.log(something);
  }

  handleClick = (e) => {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick} value="Click me" />;
  }
}

In this format you don't need to use bind

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.

Convert integer into byte array (Java)

Here's a method that should do the job just right.

public byte[] toByteArray(int value)
{
    final byte[] destination = new byte[Integer.BYTES];
    for(int index = Integer.BYTES - 1; index >= 0; index--)
    {
        destination[i] = (byte) value;
        value = value >> 8;
    };
    return destination;
};

How to print the current time in a Batch-File?

You can use the command time /t for the time and date /t for the date, here is an example:

@echo off
time /t >%tmp%\time.tmp
date /t >%tmp%\date.tmp
set ttime=<%tmp%\time.tmp
set tdate=<%tmp%\date.tmp
del /f /q %tmp%\time.tmp
del /f /q %tmp%\date.tmp
echo Time: %ttime%
echo Date: %tdate%
pause >nul

You can also use the built in variables %time% and %date%, here is another example:

@echo off
echo Time: %time:~0,5%
echo Date: %date%
pause >nul

How to create a <style> tag with Javascript?

This object variable will append style tag to the head tag with type attribute and one simple transition rule inside that matches every single id/class/element. Feel free to modify content property and inject as many rules as you need. Just make sure that css rules inside content remain in one line (or 'escape' each new line, if You prefer so).

var script = {

  type: 'text/css', style: document.createElement('style'), 
  content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000); }",
  append: function() {

    this.style.type = this.type;
    this.style.appendChild(document.createTextNode(this.content));
    document.head.appendChild(this.style);

}}; script.append();

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

How to fix Error: listen EADDRINUSE while using nodejs?

The error EADDRINUSE (Address already in use) reports that there is already another process on the local system occupying that address / port.

There is a npm package called find-process which helps finding (and closing) the occupying process.

Here is a little demo code:

const find = require('find-process')

const PORT = 80

find('port', PORT)
.then((list) => {
  console.log(`Port "${PORT}" is blocked. Killing blocking applications...`)
  const processIds = list.map((item) => item.pid)
  processIds.forEach((pid) => process.kill(pid, 10))
})

I prepared a small sample which can reproduce the EADDRINUSE error. If you launch the following program in two separate terminals, you will see that the first terminal will start a server (on port "3000") and the second terminal will close the already running server (because it blocks the execution of the second terminal, EADDRINUSE):

Minimal Working Example:

const find = require('find-process')
const http = require('http')

const PORT = 3000

// Handling exceptions
process.on('uncaughtException', (error) => {
  if (error.code === 'EADDRINUSE') {
    find('port', PORT)
      .then((list) => {
        const blockingApplication = list[0]
        if (blockingApplication) {
          console.log(`Port "${PORT}" is blocked by "${blockingApplication.name}".`)
          console.log('Shutting down blocking application...')
          process.kill(blockingApplication.pid)
          // TODO: Restart server
        }
      })
  }
})

// Starting server
const server = http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'})
  response.write('Hello World!')
  response.end()
})

server.listen(PORT, () => console.log(`Server running on port "${PORT}"...`))

Generate a dummy-variable

I use such a function (for data.table):

# Ta funkcja dla obiektu data.table i zmiennej var.name typu factor tworzy dummy variables o nazwach "var.name: (level1)"
factorToDummy <- function(dtable, var.name){
  stopifnot(is.data.table(dtable))
  stopifnot(var.name %in% names(dtable))
  stopifnot(is.factor(dtable[, get(var.name)]))

  dtable[, paste0(var.name,": ",levels(get(var.name)))] -> new.names
  dtable[, (new.names) := transpose(lapply(get(var.name), FUN = function(x){x == levels(get(var.name))})) ]

  cat(paste("\nDodano zmienne dummy: ", paste0(new.names, collapse = ", ")))
}

Usage:

data <- data.table(data)
data[, x:= droplevels(x)]
factorToDummy(data, "x")

Expand a div to fill the remaining width

Thanks for the plug of Simpl.css!

remember to wrap all your columns in ColumnWrapper like so.

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>

I am about to release version 1.0 of Simpl.css so help spread the word!

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

How to set Status Bar Style in Swift 3

  1. Chose Light Contententer image description here

  2. Add View controller-based status bar appearance with NO to .plist enter image description here

How can I get current location from user in iOS

You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.

Adding local .aar files to Gradle build using "flatDirs" is not working

The easiest way now is to add it as a module

enter image description here

This will create a new module containing the aar file, so you just need to include that module as a dependency afterwards

How does one check if a table exists in an Android SQLite database?

Yep, turns out the theory in my edit was right: the problem that was causing the onCreate method not to run, was the fact that SQLiteOpenHelper objects should refer to databases, and not have a separate one for each table. Packing both tables into one SQLiteOpenHelper solved the problem.

How do I capture all of my compiler's output to a file?

Based on an earlier reply by @dmckee

make | tee makelog.txt

This gives you real-time scrolling output while compiling, and simultaneously write to the makelog.txt file.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Match the .env file and the config.php file with your username and password and your hostname in the database settings.if they are not equal,relation will not connect.

How do I find the mime-type of a file with php?

I haven't used it, but there's a PECL extension for getting a file's mimetype. The official documentation for it is in the manual.

Depending on your purposes, a file extension can be ok, but it's not incredibly reliable since it's so easily changed.

COPYing a file in a Dockerfile, no such file or directory?

I had this problem even though my source directory was in the correct build context. Found the reason was that my source directory was a symbolic link to a location outside the build context.

For example my Dockerfile contains the following:

COPY dir1 /tmp

If dir1 is a symbolic link the COPY command is not working in my case.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.

What is the difference between :focus and :active?

Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.

The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).

Export a list into a CSV or TXT file in R

Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000

Exporting large lists in R as .txt or .csv

macOS on VMware doesn't recognize iOS device

I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding

usb.quirks.device0 = "0xvid:0xpid skip-refresh"

Detail as below:


To add quirks:
  1. Shut down the virtual machine and quit Workstation/Fusion.

    Caution: Do not skip this step.
     
  2. Open the vmware.log file within the virtual machine bundle. For more information, see Locating a virtual machine bundle in VMware Workstation/Fusion (1007599).
  3. In the Filter box at the top of the Console window, enter the name of the device manufacturer.

    For example, if you enter the name Apple, you see a line that looks similar to:

    vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]



    The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
     

  4. Open the .vmx file using a text editor. For more information, see Editing the .vmx file for your Workstation/Fusion virtual machine (1014782).
  5. Add this line to the .vmx file, replacing vid and pid with the values noted in Step 2, each prefixed by the number 0 and the letter x .

    usb.quirks.device0 = "0xvid:0xpid skip-reset"

    For example, for the Apple device found in step 2, this line is:

    usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
     

  6. Save the .vmx file.
  7. Re-open Workstation/Fusion. The edited .vmx file is reloaded with the changes.
  8. Start the virtual machine, and connect the device.
  9. If the issue is not resolved, replace the quirks line added in Step 4 with one of these lines, in the order provided, and repeat Steps 5 to 8:
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"

Notes:

  • Use one of these lines at a time. If one does not work, replace it with another one in the list. Do not add more than one of these in the .vmx file at a time.
  • The last line uses all three quirks in combination. Use this only if the other three lines do not work.

Refer this to see in detail.

Magento - How to add/remove links on my account navigation?

You can also disable the menu items through the backend, without having to touch any code. Go into:

System > Configuration > Advanced

You'll be presented with a long list of options. Here are some of the key modules to set to 'Disabled' :

Mage_Downloadable -> My Downloadable Products
Mage_Newsletter -> My Newsletter
Mage_Review -> My Reviews
Mage_Tag -> My Tags
Mage_Wishlist -> My Wishlist

I also disabled Mage_Poll, as it has a tendency to show up in other page templates and can be annoying if you're not using it.

Iterating through a string word by word

for word in string.split():
    print word

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

Proper MIME type for .woff2 fonts

In IIS you can declare the mime type for WOFF2 font files by adding the following to your project's web.config:

<system.webServer>
  <staticContent>
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

Update: The mime type may be changing according to the latest W3C Editor's Draft WOFF2 spec. See Appendix A: Internet Media Type Registration section 6.5. WOFF 2.0 which states the latest proposed format is font/woff2

How to convert a string to number in TypeScript?

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

var x = "32";
var y: number = +x;

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Conversion table Table taken from this answer

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Seems there is missing MongoDB driver. Include the following dependency to pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

count number of rows in a data frame in R based on group

Suppose we have a df_data data frame as below

> df_data
   ID MONTH-YEAR VALUE
1 110   JAN.2012  1000
2 111   JAN.2012  2000
3 121   FEB.2012  3000
4 131   FEB.2012  4000
5 141   MAR.2012  5000

To count number of rows in df_data grouped by MONTH-YEAR column, you can use:

> summary(df_data$`MONTH-YEAR`)

FEB.2012 JAN.2012 MAR.2012 
   2        2        1 

enter image description here summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I just had to solve the same problem: json-encoding an entity ("User") having a One-To-Many Bidirectional Association to another Entity ("Location").

I tried several things and I think now I found the best acceptable solution. The idea was to use the same code as written by David, but somehow intercept the infinite recursion by telling the Normalizer to stop at some point.

I did not want to implement a custom normalizer, as this GetSetMethodNormalizer is a nice approach in my opinion (based on reflection etc.). So I've decided to subclass it, which is not trivial at first sight, because the method to say if to include a property (isGetMethod) is private.

But, one could override the normalize method, so I intercepted at this point, by simply unsetting the property that references "Location" - so the inifinite loop is interrupted.

In code it looks like this:

class GetSetMethodNormalizer extends \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer {

    public function normalize($object, $format = null)
    {
        // if the object is a User, unset location for normalization, without touching the original object
        if($object instanceof \Leonex\MoveBundle\Entity\User) {
            $object = clone $object;
            $object->setLocations(new \Doctrine\Common\Collections\ArrayCollection());
        }

        return parent::normalize($object, $format);
    }

} 

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.