Programs & Examples On #Dataformat

How can I get dict from sqlite query?

From PEP 249:

Question: 

   How can I construct a dictionary out of the tuples returned by
   .fetch*():

Answer:

   There are several existing tools available which provide
   helpers for this task. Most of them use the approach of using
   the column names defined in the cursor attribute .description
   as basis for the keys in the row dictionary.

   Note that the reason for not extending the DB API specification
   to also support dictionary return values for the .fetch*()
   methods is that this approach has several drawbacks:

   * Some databases don't support case-sensitive column names or
     auto-convert them to all lowercase or all uppercase
     characters.

   * Columns in the result set which are generated by the query
     (e.g.  using SQL functions) don't map to table column names
     and databases usually generate names for these columns in a
     very database specific way.

   As a result, accessing the columns through dictionary keys
   varies between databases and makes writing portable code
   impossible.

So yes, do it yourself.

Locating child nodes of WebElements in selenium

According to JavaDocs, you can do this:

WebElement input = divA.findElement(By.xpath(".//input"));

How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?

WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));

The XPath spec is a suprisingly good read on this.

How to save a data.frame in R?

There are several ways. One way is to use save() to save the exact object. e.g. for data frame foo:

save(foo,file="data.Rda")

Then load it with:

load("data.Rda")

You could also use write.table() or something like that to save the table in plain text, or dput() to obtain R code to reproduce the table.

Switch tabs using Selenium WebDriver with Java

With Selenium 2.53.1 using firefox 47.0.1 as the WebDriver in Java: no matter how many tabs I opened, "driver.getWindowHandles()" would only return one handle so it was impossible to switch between tabs.

Once I started using Chrome 51.0, I could get all handles. The following code show how to access multiple drivers and multiple tabs within each driver.

// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());

// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver1.getWindowHandles());

// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   driver1.switchTo().window(tabs1.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   drvier2.switchTo().window(tabs2.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

Hopefully that gives you a good idea of how to manipulate multiple tabs in multiple browser windows.

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

How to get HttpContext.Current in ASP.NET Core?

Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory
    )
    {

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)
    {

Next, create a replacement class for System.Web:

namespace System.Web
{

    namespace Hosting
    {
        public static class HostingEnvironment 
        {
            public static bool m_IsHosted;

            static HostingEnvironment()
            {
                m_IsHosted = false;
            }

            public static bool IsHosted
            {
                get
                {
                    return m_IsHosted;
                }
            }
        }
    }


    public static class HttpContext
    {
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }


    } // End Class HttpContext 


}

Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;


    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false

    });

Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.


Perhaps a more maintainable method would be adding this helper class

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }


    }


}

And then calling HttpContext.Configure in Startup->Configure

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


    System.Web.HttpContext.Configure(app.ApplicationServices.
        GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
    );

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

Show an image preview before upload

Here I did with jQuery using FileReader API.

Html Markup:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message

$("#fileUpload").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

Cast to generic type in C#

Please see if following solution works for you. The trick is to define a base processor interface which takes a base type of message.

interface IMessage
{
}

class LoginMessage : IMessage
{
}

class LogoutMessage : IMessage
{
}

class UnknownMessage : IMessage
{
}

interface IMessageProcessor
{
    void PrcessMessageBase(IMessage msg);
}

abstract class MessageProcessor<T> : IMessageProcessor where T : IMessage
{
    public void PrcessMessageBase(IMessage msg)
    {
        ProcessMessage((T)msg);
    }

    public abstract void ProcessMessage(T msg);

}

class LoginMessageProcessor : MessageProcessor<LoginMessage>
{
    public override void ProcessMessage(LoginMessage msg)
    {
        System.Console.WriteLine("Handled by LoginMsgProcessor");
    }
}

class LogoutMessageProcessor : MessageProcessor<LogoutMessage>
{
    public override void ProcessMessage(LogoutMessage msg)
    {
        System.Console.WriteLine("Handled by LogoutMsgProcessor");
    }
}

class MessageProcessorTest
{
    /// <summary>
    /// IMessage Type and the IMessageProcessor which would process that type.
    /// It can be further optimized by keeping IMessage type hashcode
    /// </summary>
    private Dictionary<Type, IMessageProcessor> msgProcessors = 
                                new Dictionary<Type, IMessageProcessor>();
    bool processorsLoaded = false;

    public void EnsureProcessorsLoaded()
    {
        if(!processorsLoaded)
        {
            var processors =
                from processorType in Assembly.GetExecutingAssembly().GetTypes()
                where processorType.IsClass && !processorType.IsAbstract &&
                      processorType.GetInterface(typeof(IMessageProcessor).Name) != null
                select Activator.CreateInstance(processorType);

            foreach (IMessageProcessor msgProcessor in processors)
            {
                MethodInfo processMethod = msgProcessor.GetType().GetMethod("ProcessMessage");
                msgProcessors.Add(processMethod.GetParameters()[0].ParameterType, msgProcessor);
            }

            processorsLoaded = true;
        }
    }

    public void ProcessMessages()
    {
        List<IMessage> msgList = new List<IMessage>();
        msgList.Add(new LoginMessage());
        msgList.Add(new LogoutMessage());
        msgList.Add(new UnknownMessage());

        foreach (IMessage msg in msgList)
        {
            ProcessMessage(msg);
        }
    }

    public void ProcessMessage(IMessage msg)
    {
        EnsureProcessorsLoaded();
        IMessageProcessor msgProcessor = null;
        if(msgProcessors.TryGetValue(msg.GetType(), out msgProcessor))
        {
            msgProcessor.PrcessMessageBase(msg);
        }
        else
        {
            System.Console.WriteLine("Processor not found");
        }
    }

    public static void Test()
    {
        new MessageProcessorTest().ProcessMessages();
    }
}

PHP json_decode() returns NULL with valid JSON?

You could try with it.

json_decode(stripslashes($_POST['data']))

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

PHP function to make slug (URL string)

Don't use preg_replace for this. There's a php function built just for the task: strtr() http://php.net/manual/en/function.strtr.php

Taken from the comments in the above link (and I tested it myself; it works:

function normalize ($string) {
    $table = array(
        'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'd'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
        'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'R'=>'R', 'r'=>'r',
    );

    return strtr($string, $table);
}

Characters allowed in GET parameter

"." | "!" | "~" | "*" | "'" | "(" | ")" are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.

How does one add keyboard languages and switch between them in Linux Mint 16?

Go to menu , search for Regional Settings. Switch to Keyboard layouts tab. Click Options button. Search for Key(s) to change layout. There isn't a default one so you have to tick the combination you like. Enjoy.

super() raises "TypeError: must be type, not classobj" for new-style class

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.

What is __pycache__?

When you import a module,

import file_name

Python stores the compiled bytecode in __pycache__ directory so that future imports can use it directly, rather than having to parse and compile the source again.

It does not do that for merely running a script, only when a file is imported.

(Previous versions used to store the cached bytecode as .pyc files that littered up the same directory as the .py files, but starting in Python 3 they were moved to a subdirectory to make things tidier.)

PYTHONDONTWRITEBYTECODE ---> If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.

How do I call a JavaScript function on page load?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>Test</title>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript">_x000D_
        function codeAddress() {_x000D_
            alert('ok');_x000D_
        }_x000D_
        window.onload = codeAddress;_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
    _x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Trying to get property of non-object - Laravel 5

I had also this problem. Add code like below in the related controller (e.g. UserController)

$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

PowerShell equivalent to grep -f

I find out a possible method by "filter" and "alias" of PowerShell, when you want use grep in pipeline output(grep file should be similar):

first define a filter:

filter Filter-Object ([string]$pattern)
{
    Out-String -InputObject $_ -Stream | Select-String -Pattern "$pattern"
}

then define alias:

New-Alias -Name grep -Value Filter-Object

final, put the former filter and alias in your profile:

$Home[My ]Documents\PowerShell\Microsoft.PowerShell_profile.ps1

Restart your PS, you can use it:

alias | grep 'grep'

==================================================================

relevent Reference

  1. alias: Set-Aliasenter link description here New-Aliasenter link description here

  2. Filter(Special function)enter link description here

  3. Profiles(just like .bashrc for bash):enter link description here

  4. out-string(this is the key)enter link description here:in PowerShell Output is object-basedenter link description here,so the key is convert object to string and grep the string.

  5. Select-Stringenter link description here:Finds text in strings and files

Difference between session affinity and sticky session?

They are the same.

Both mean that when coming in to the load balancer, the request will be directed to the server that served the first request (and has the session).

Remove HTML Tags from an NSString on the iPhone

If you want to get the content without the html tags from the web page (HTML document) , then use this code inside the UIWebViewDidfinishLoading delegate method.

  NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];

CSS class for pointer cursor

You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e

<html-element role="button" />

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

How to center a checkbox in a table cell?

How about this... http://jsfiddle.net/gSaPb/


Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:

_x000D_
_x000D_
td {
  text-align: center;
  /* center checkbox horizontally */
  vertical-align: middle;
  /* center checkbox vertically */
}

table {
  border: 1px solid;
  width: 200px;
}

tr {
  height: 80px;
}
_x000D_
<table>
  <tr>
    <td>
      <input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Just made this in a few minutes:

using System;
using System.Management;

namespace WindowsFormsApplication_CS
{
  class NetworkManagement
  {
    public void setIP(string ip_address, string subnet_mask)
    {
      ManagementClass objMC =
        new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setIP;
          ManagementBaseObject newIP =
            objMO.GetMethodParameters("EnableStatic");

          newIP["IPAddress"] = new string[] { ip_address };
          newIP["SubnetMask"] = new string[] { subnet_mask };

          setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
        }
      }
    }

    public void setGateway(string gateway)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setGateway;
          ManagementBaseObject newGateway =
            objMO.GetMethodParameters("SetGateways");

          newGateway["DefaultIPGateway"] = new string[] { gateway };
          newGateway["GatewayCostMetric"] = new int[] { 1 };

          setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
        }
      }
    }

    public void setDNS(string NIC, string DNS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          // if you are using the System.Net.NetworkInformation.NetworkInterface
          // you'll need to change this line to
          // if (objMO["Caption"].ToString().Contains(NIC))
          // and pass in the Description property instead of the name 
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject newDNS =
              objMO.GetMethodParameters("SetDNSServerSearchOrder");
            newDNS["DNSServerSearchOrder"] = DNS.Split(',');
            ManagementBaseObject setDNS =
              objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
          }
        }
      }
    }

    public void setWINS(string NIC, string priWINS, string secWINS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject setWINS;
            ManagementBaseObject wins =
            objMO.GetMethodParameters("SetWINSServer");
            wins.SetPropertyValue("WINSPrimaryServer", priWINS);
            wins.SetPropertyValue("WINSSecondaryServer", secWINS);

            setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
          }
        }
      }
    } 
  }
}

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

Calling startActivity() from outside of an Activity?

For Multiple Instance of the same activity , use the following snippet,

Note : This snippet, I am using outside of my Activity. Make sure your AndroidManifest file doesn't contain android:launchMode="singleTop|singleInstance". if needed, you can change it to android:launchMode="standard".

Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);

This works fine for me. Hope, this saves times for someone. If anybody finds a better way, please share with us.

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

RecyclerView - Get view at particular position

You can make ArrayList of ViewHolder :

 ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
 ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();

and, all store ViewHolder(s) in the list like :

 @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        final String str = arrayList.get(position);

        myViewHolders.add(position,holder);
}

and add/remove other ViewHolder in the ArrayList as per your requirement.

How do I replace all line breaks in a string with <br /> elements?

This works for input coming from a textarea

str.replace(new RegExp('\r?\n','g'), '<br />');

Why can templates only be implemented in the header file?

If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.

BitBucket - download source as ZIP

For git repositories, to download the latest commit, you can use:

https://bitbucket.org/owner/repository/get/HEAD.zip

For mercurial repositories:

https://bitbucket.org/owner/repository/get/tip.zip

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

denied: requested access to the resource is denied : docker

I know this question has many answers already, but none of them were helpful to me.

What I observed was that building the image was extremely fast and pushing to docker.io resulted in the error:

denied: requested access to the resource is denied

what I also noticed was that doing an

docker image ls

revealed that the latest build of my image was several days old.

I had to do a

docker container prune 

to get rid of stopped containers, and a

docker images prune -a

to get rid of old images. Then I could successfully build and push my image.

The 'denied: requested access to the resource is denied' is not from docker.io, but from local docker. Funny though that it is not failing during build.

Label encoding across multiple columns in scikit-learn

As mentioned by larsmans, LabelEncoder() only takes a 1-d array as an argument. That said, it is quite easy to roll your own label encoder that operates on multiple columns of your choosing, and returns a transformed dataframe. My code here is based in part on Zac Stewart's excellent blog post found here.

Creating a custom encoder involves simply creating a class that responds to the fit(), transform(), and fit_transform() methods. In your case, a good start might be something like this:

import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline

# Create some toy data in a Pandas dataframe
fruit_data = pd.DataFrame({
    'fruit':  ['apple','orange','pear','orange'],
    'color':  ['red','orange','green','green'],
    'weight': [5,6,3,4]
})

class MultiColumnLabelEncoder:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode

    def fit(self,X,y=None):
        return self # not relevant here

    def transform(self,X):
        '''
        Transforms columns of X specified in self.columns using
        LabelEncoder(). If no columns specified, transforms all
        columns in X.
        '''
        output = X.copy()
        if self.columns is not None:
            for col in self.columns:
                output[col] = LabelEncoder().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelEncoder().fit_transform(col)
        return output

    def fit_transform(self,X,y=None):
        return self.fit(X,y).transform(X)

Suppose we want to encode our two categorical attributes (fruit and color), while leaving the numeric attribute weight alone. We could do this as follows:

MultiColumnLabelEncoder(columns = ['fruit','color']).fit_transform(fruit_data)

Which transforms our fruit_data dataset from

enter image description here to

enter image description here

Passing it a dataframe consisting entirely of categorical variables and omitting the columns parameter will result in every column being encoded (which I believe is what you were originally looking for):

MultiColumnLabelEncoder().fit_transform(fruit_data.drop('weight',axis=1))

This transforms

enter image description here to

enter image description here.

Note that it'll probably choke when it tries to encode attributes that are already numeric (add some code to handle this if you like).

Another nice feature about this is that we can use this custom transformer in a pipeline:

encoding_pipeline = Pipeline([
    ('encoding',MultiColumnLabelEncoder(columns=['fruit','color']))
    # add more pipeline steps as needed
])
encoding_pipeline.fit_transform(fruit_data)

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Here Integer.toString calls the static method in the class Integer. It does not require the object to call.

If you call new Integer(i) you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. Then you call the toString method on it to ask it to return a string representation of itself.

Git Commit Messages: 50/72 Formatting

Regarding “thought leaders”: Linus emphatically advocates line wrapping for the full commit message:

[…] we use 72-character columns for word-wrapping, except for quoted material that has a specific line format.

The exceptions refers mainly to “non-prose” text, that is, text that was not typed by a human for the commit — for example, compiler error messages.

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

How to center a "position: absolute" element

Just use display: flex and justify-content: center on the parent element

_x000D_
_x000D_
body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align: center;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
    display: flex;
    justify-content: center;
}

ul#slideshow li {
    position: absolute;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 100px;
}
_x000D_
<body>
   <div id="slideshowWrapper">
      <ul id="slideshow">
         <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
         <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
      </ul>
   </div>
</body>

<!-- Images from Unsplash-->
_x000D_
_x000D_
_x000D_

You can find this solution in JSFIDDLE

Syntax for creating a two-dimensional array in Java

Try this way:

int a[][] = {{1,2}, {3,4}};

int b[] = {1, 2, 3, 4};

Using OR & AND in COUNTIFS

Using array formula.

=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))

PRESS = CTRL + SHIFT + ENTER.

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

log4j:WARN No appenders could be found for logger in web.xml

Or, you could be doing what I did and define the logger before the log configuration file has been loaded. This would be as they say: "Putting the cart before the horse."

In the code:

public static Logger logger = Logger.getLogger("RbReport");

... later on

PropertyConfigurator.configure(l4j);
logger = Logger.getLogger("RbReport");

Fix was to initialize the logger after the configuration was loaded.

For the geeks it was "Putting Descarte b4 d horse".

How do you make div elements display inline?

That's something else then:

_x000D_
_x000D_
div.inline { float:left; }_x000D_
.clearBoth { clear:both; }
_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<br class="clearBoth" /><!-- you may or may not need this -->
_x000D_
_x000D_
_x000D_

Python Infinity - Any caveats?

So does C99.

The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).

All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.

setting y-axis limit in matplotlib

Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

Take a look at the documentation for xlim and for ylim

Correct way to find max in an Array in Swift

In Swift 2.0, the minElement and maxElement become methods of SequenceType protocol, you should call them like:

let a = [1, 2, 3]
print(a.maxElement()) //3
print(a.minElement()) //1

Using maxElement as a function like maxElement(a) is unavailable now.

The syntax of Swift is in flux, so I can just confirm this in Xcode version7 beta6.

It may be modified in the future, so I suggest that you'd better check the doc before you use these methods.

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

What is the effect of encoding an image in base64?

The answer is: It depends.

Although base64-images are larger, there a few conditions where base64 is the better choice.

Size of base64-images

Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.

Example:

An 48kb image needs around 64kb as base64 converted image.

Calculation: (48 / 6) * 8 = 64

Simple CLI calculator on Linux systems:

$ cat /dev/urandom|head -c 48000|base64|wc -c
64843

Or using an image:

$ cat my.png|base64|wc -c

Base64-images and websites

This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:

  • A lot of embedded images in an HTML-File or CSS-File can have similar strings. For PNGs you often find repeated "A" chars. Using gzip (sometimes called "deflate"), there might be even a win on size. But it depends on image content.
  • Request overhead of HTTP1.1: Especially with a lot of cookies you can easily have a few kilobytes overhead per request. Embedding base64 images might save bandwith.
  • Do not base64 encode SVG images, because gzip is more effective on XML than on base64.
  • Programming: On dynamically generated images it is easier to deliver them in one request as to coordinate two dependent requests.
  • Deeplinks: If you want to prevent downloading the image, it is a little bit trickier to extract an image from an HTML page.

StringUtils.isBlank() vs String.isEmpty()

I am answering this because it's the top result in Google for "String isBlank() Method".

If you are using Java 11 or above, you can use the String class isBlank() method. This method does the same thing as Apache Commons StringUtils class.

I have written a small post on this method examples, read it here.

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

I am on Mac OS so when I press Command, it enable zooming option. Here is my solution

  • Open Configuration window [...] button
  • Go toSettings tab ->General tab -> Send keyboard shortcuts to field
  • Change value to Virtual device" as shown in the picture

After that focus on the emulator and press Command + M, the dev menu appears.

Emulator Option -> Settings -> General

Codeigniter - multiple database connections

Use this.

$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);     

$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);     

$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);   

Usage

$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);

What is the best way to prevent session hijacking?

// Collect this information on every request
$aip = $_SERVER['REMOTE_ADDR'];
$bip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
session_start();

// Do this each time the user successfully logs in.
$_SESSION['ident'] = hash("sha256", $aip . $bip . $agent);

// Do this every time the client makes a request to the server, after authenticating
$ident = hash("sha256", $aip . $bip . $agent);
if ($ident != $_SESSION['ident'])
{
    end_session();
    header("Location: login.php");
    // add some fancy pants GET/POST var headers for login.php, that lets you
    // know in the login page to notify the user of why they're being challenged
    // for login again, etc.
}

What this does is capture 'contextual' information about the user's session, pieces of information which should not change during the life of a single session. A user isn't going to be at a computer in the US and in China at the same time, right? So if the IP address changes suddenly within the same session that strongly implies a session hijacking attempt, so you secure the session by ending the session and forcing the user to re-authenticate. This thwarts the hack attempt, the attacker is also forced to login instead of gaining access to the session. Notify the user of the attempt (ajax it up a bit), and vola, Slightly annoyed+informed user and their session/information is protected.

We throw in User Agent and X-FORWARDED-FOR to do our best to capture uniqueness of a session for systems behind proxies/networks. You may be able to use more information then that, feel free to be creative.

It's not 100%, but it's pretty damn effective.

There's more you can do to protect sessions, expire them, when a user leaves a website and comes back force them to login again maybe. You can detect a user leaving and coming back by capturing a blank HTTP_REFERER (domain was typed in the URL bar), or check if the value in the HTTP_REFERER equals your domain or not (the user clicked an external/crafted link to get to your site).

Expire sessions, don't let them remain valid indefinitely.

Don't rely on cookies, they can be stolen, it's one of the vectors of attack for session hijacking.

Custom fonts and XML layouts (Android)

Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the android:fontFamily attribute to add support for custom fonts in your asset folder, like so:

<TextView 
  android:text="@string/hello_world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:fontFamily="fonts/Roboto-Bold.ttf"/>

The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

You can also specify your own custom attribute to replace android:fontFamily

It also works in themes, including the AppTheme.

UTF-8, UTF-16, and UTF-32

  • UTF-8 is variable 1 to 4 bytes.

  • UTF-16 is variable 2 or 4 bytes.

  • UTF-32 is fixed 4 bytes.

Note: UTF-8 can take 1 to 6 bytes with latest convention: https://lists.gnu.org/archive/html/help-flex/2005-01/msg00030.html

How to clear all data in a listBox?

If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.

I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"

public List<ExampleItem> ClearExampleItems()
       {
           List<ExampleItem> exampleItems = new List<ExampleItem>();
           exampleItems.Clear();
           return examplelistItems;
        }

ExampleItem is also in a separate class named "ExampleItem.cs"

using System;

namespace        // The namespace is automatically added by Visual Studio
{
    public class ExampleItem
    {
        public int ItemId { get; set; }
        public string ItemType { get; set; }
        public int ItemNumber { get; set; }
        public string ItemDescription { get; set; }

        public string FullExampleItem 
        {
            get
            {
                return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
            }
        }
    }
}

In the code for your Window Form, the following code fragments reference your listbox:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;

namespace        // The namespace is automatically added by Visual Studio
{
    
    public partial class YourFormName : Form
    {
        
        List<ExampleItem> exampleItems = new List<ExampleItem>();

        public YourFormName()
        {
            InitializeComponent();

            // Connect listbox to LIST
            UpdateExampleItemsBinding();
        }

        private void UpdateUpdateItemsBinding()
        {
            ExampleItemsListBox.DataSource = exampleItems;
            ExampleItemsListBox.DisplayMember = "FullExampleItem";
        }

        private void buttonClearListBox_Click(object sender, EventArgs e)
        {
            DataAccess db = new DataAccess();
            exampleItems = db.ClearExampleItems();
            
            UpdateExampleItemsBinding();
        }
    }
}

This solution specifically addresses a Windows Form listbox with the datasource connected to a list.

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For me, it was because I ran

$ phpunit .

instead of

$ phpunit

when I already had a configured phpunit.xml file in the working directory.

How to pass object from one component to another in Angular 2?

Use the output annotation

@Directive({
  selector: 'interval-dir',
})
class IntervalDir {
  @Output() everySecond = new EventEmitter();
  @Output('everyFiveSeconds') five5Secs = new EventEmitter();
  constructor() {
    setInterval(() => this.everySecond.emit("event"), 1000);
    setInterval(() => this.five5Secs.emit("event"), 5000);
  }
}
@Component({
  selector: 'app',
  template: `
    <interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()">
    </interval-dir>
  `,
  directives: [IntervalDir]
})
class App {
  everySecond() { console.log('second'); }
  everyFiveSeconds() { console.log('five seconds'); }
}
bootstrap(App);

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

How to fix Python Numpy/Pandas installation?

If you are using a version of enthought python (EPD) you might want to go directly to your site-packages and reinstall numpy. Then try to install pandas with pip. You will have to modify your installation prefix for that.

If the problem persists (as it did with me) try downloading pandas tar ball, unpack it in your site packages and run setup.py install from your pandas directory.

If you got your dependencies right you can import pandas and check it imports smoothly.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

DIV table colspan: how?

I would imagine that this would be covered by CSS Tables, a specification which, while mentioned on the CSS homepage, appears to currently be at a state of "not yet published in any form"

In practical terms, you can't achieve this at present.

Why does an onclick property set with setAttribute fail to work in IE?

I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.

var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");

var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");

linkDeleter.appendChild(imgDeleter);

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

Solution with JavaScript debugging enabled

From the Chrome browser, go to: Settings>Advanced>System and disable "Continue running background apps when Google Chrome is closed".

IMPORTANT! The option above must be set for the correct Chrome User Profile!
Visual Studio has its own Chrome User Profile, preferences you set when using your "normal" Chrome browser wont have any affect on the Chrome browser launched from VS (with JS debugging enabled).

  1. Run your project from VS with "Enable JavaScript debugging..." enabled. The Chrome browser should open and you'll get the error in VS.
  2. Go back to the same instance of Chrome that VS started and disable "Continue running background apps when Google Chrome is closed" as explained above.
    If you don't have "Enable JavaScript debugging..." enabled/checked, the Chrome instance would use your Default User Profile and the error would persist.
  3. Stop and rerun your project, Chrome should load the project as expected without any errors and with JS debugging enabled.

Whenever you stop debugging, you must close the Chrome instance initiated by VS or the error will return the next time you run the project. If there are other Chrome instances, you can leave these open.

To make sure Chrome is using the correct User Profile, go to chrome://version/ by typing it in the url bar, then look at the value for Profile Path. On Windows, the correct value should look something like this:
"C:\Users\[UserName]\AppData\Local\Microsoft\VisualStudio\15.*\WebTools\ChromeUserData_*\Default"

If Chrome is using the browser default or if you're logged in to Chrome with an account, it will look something like this:
"C:\Users\[UserName]\AppData\Local\Google\Chrome\User Data\[ProfileName] OR Default"

Bonus note. If you use Chrome Extensions when debugging, these has to be installed when the VS Profile is active.

How to break out of the IF statement

public void Method()
{
    if(something)
    {
        //some code
        if(!something2)
        {
            return;
        }
    }
    // The code i want to go if the second if is true
}

Required attribute HTML5

Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute

Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I'd a similar problem in WebAPI (related MVC).

I fixed with:

Adding ".Global" to inherits in .asax file (not asax.cs)

Inherits="mynamespace.WebAPI.Global" 

and changing the public class (asax.cs)

public class Global : System.Web.HttpApplication

Referencing system.management.automation.dll in Visual Studio

if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**

and version could be different

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

Showing Difference between two datetime values in hours

Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.

References:

https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet

How to succinctly write a formula with many variables from a data frame?

I build this solution, reformulate does not take care if variable names have white spaces.

add_backticks = function(x) {
    paste0("`", x, "`")
}

x_lm_formula = function(x) {
    paste(add_backticks(x), collapse = " + ")
}

build_lm_formula = function(x, y){
    if (length(y)>1){
        stop("y needs to be just one variable")
    }
    as.formula(        
        paste0("`",y,"`", " ~ ", x_lm_formula(x))
    )
}

# Example
df <- data.frame(
    y = c(1,4,6), 
    x1 = c(4,-1,3), 
    x2 = c(3,9,8), 
    x3 = c(4,-4,-2)
    )

# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"

# Run Model
lm(formula = formula, data = df)
# output
Call:
    lm(formula = formula, data = df)

Coefficients:
    (Intercept)           x1           x2           x3  
        -5.6316       0.7895       1.1579           NA  

```

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

How to put wildcard entry into /etc/hosts?

Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)

hosts file (add an entry)

file: /etc/hosts (non-windows)

127.0.0.1   example.local

httpd.conf configuration (enable vhosts)

file: /XAMPP/etc/httpd.conf

# Virtual hosts
Include etc/extra/httpd-vhosts.conf

httpd-vhosts.conf configuration

file: XAMPP/etc/extra/httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/path_to_XAMPP/htdocs"
    ServerName example.local
    ServerAlias *.example.local
#    SetEnv APP_ENVIRONMENT development
#    ErrorLog "logs/example.local-error_log"
#    CustomLog "logs/example.local-access_log" common
</VirtualHost>

restart apache

create pac file:

save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)

function FindProxyForURL(url, host) {
  if (shExpMatch(host, "*example.local")) {
    return "PROXY example.local";
  }
  return "DIRECT";
}

Math functions in AngularJS bindings

This is a hairy one to answer, because you didn't give the full context of what you're doing. The accepted answer will work, but in some cases will cause poor performance. That, and it's going to be harder to test.

If you're doing this as part of a static form, fine. The accepted answer will work, even if it isn't easy to test, and it's hinky.

If you want to be "Angular" about this:

You'll want to keep any "business logic" (i.e. logic that alters data to be displayed) out of your views. This is so you can unit test your logic, and so you don't end up tightly coupling your controller and your view. Theoretically, you should be able to point your controller at another view and use the same values from the scopes. (if that makes sense).

You'll also want to consider that any function calls inside of a binding (such as {{}} or ng-bind or ng-bind-html) will have to be evaluated on every digest, because angular has no way of knowing if the value has changed or not like it would with a property on the scope.

The "angular" way to do this would be to cache the value in a property on the scope on change using an ng-change event or even a $watch.

For example with a static form:

angular.controller('MainCtrl', function($scope, $window) {
   $scope.count = 0;
   $scope.total = 1;

   $scope.updatePercentage = function () {
      $scope.percentage = $window.Math.round((100 * $scope.count) / $scope.total);
   };
});
<form name="calcForm">
   <label>Count <input name="count" ng-model="count" 
                  ng-change="updatePercentage()"
                  type="number" min="0" required/></label><br/>
   <label>Total <input name="total" ng-model="total"
                  ng-change="updatePercentage()"
                  type="number" min="1" required/></label><br/>
   <hr/>
   Percentage: {{percentage}}
</form>

And now you can test it!

describe('Testing percentage controller', function() {
  var $scope = null;
  var ctrl = null;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();

    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });
  }));

  it('should calculate percentages properly', function() {
    $scope.count = 1;
    $scope.total = 1;
    $scope.updatePercentage();
    expect($scope.percentage).toEqual(100);

    $scope.count = 1;
    $scope.total = 2;
    $scope.updatePercentage();
    expect($scope.percentage).toEqual(50);

    $scope.count = 497;
    $scope.total = 10000;
    $scope.updatePercentage();
    expect($scope.percentage).toEqual(5); //4.97% rounded up.

    $scope.count = 231;
    $scope.total = 10000;
    $scope.updatePercentage();
    expect($scope.percentage).toEqual(2); //2.31% rounded down.
  });
});

Get only records created today in laravel

for Laravel 5.6+ users, you can just do

    $posts = Post::whereDate('created_at', Carbon::today())->get();

Happy coding

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

I was having similar issue and I think if we simply ignore the ssl verification will work like charm as it worked for me. So connecting to server with https scheme but directing them not to verify the certificate.

Using requests. Just mention verify=False instead of None

    requests.post(url, data=payload, headers=headers, verify=False)

Hoping this will work for those who needs :).

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

Create a file if one doesn't exist - C

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

FILE *fp = fopen("scores.dat", "rb");
if (fp) {
    read_scores(fp);
}

// Later...

// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
    error();
write_scores(fp);

How are people unit testing with Entity Framework 6, should you bother?

There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!

Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.

https://blog.goyello.com/2016/07/14/save-time-mocking-use-your-real-entity-framework-dbcontext-in-unit-tests/

https://github.com/tamasflamich/effort

I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.

return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");

What good are SQL Server schemas?

Just like Namespace of C# codes.

Automating the InvokeRequired code pattern

I'd rather use a single instance of a method Delegate instead of creating a new instance every time. In my case i used to show progress and (info/error) messages from a Backroundworker copying and casting large data from a sql instance. Everywhile after about 70000 progress and message calls my form stopped working and showing new messages. This didn't occure when i started using a single global instance delegate.

delegate void ShowMessageCallback(string message);

private void Form1_Load(object sender, EventArgs e)
{
    ShowMessageCallback showMessageDelegate = new ShowMessageCallback(ShowMessage);
}

private void ShowMessage(string message)
{
    if (this.InvokeRequired)
        this.Invoke(showMessageDelegate, message);
    else
        labelMessage.Text = message;           
}

void Message_OnMessage(object sender, Utilities.Message.MessageEventArgs e)
{
    ShowMessage(e.Message);
}

Escape double quote character in XML

You can try using the a backslash followed by a "u" and then the unicode value for the character, for example the unicode value of the double quote is

" -> U+0022

Therefore if you were setting it as part of text in XML in android it would look something like this,

<TextView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:text=" \u0022 Showing double quotes \u0022 "/>

This would produce a text in the TextView roughly something like this

" Showing double quotes "

You can find unicode of most symbols and characters here www.unicode-table.com/en

Detecting real time window size changes in Angular 4

If you want to react on certain breakpoints (e.g. do something if width is less than 768px), you can also use BreakpointObserver:

import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';

{ ... }

const isSmallScreen = breakpointObserver.isMatched('(max-width: 599px)');

or even listen to changes to that breakpoint:

breakpointObserver.observe([
  '(max-width: 768px)'
    ]).subscribe(result => {
      if (result.matches) {
        doSomething();
      } else {
        // if necessary:
        doSomethingElse();
      }
    });

I can't install python-ldap

For alpine docker

apk add openldap-dev

if the python version is 3 and above try

pip install python3-ldap

What is the difference between String.slice and String.substring?

The only difference between slice and substring method is of arguments

Both take two arguments e.g. start/from and end/to.

You cannot pass a negative value as first argument for substring method but for slice method to traverse it from end.

Slice method argument details:

REF: http://www.thesstech.com/javascript/string_slice_method

Arguments

start_index Index from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character. end_index Index after end of slice. If not provided slice will be taken from start_index to end of string. In case of negative value index will be measured from end of string.

Substring method argument details:

REF: http://www.thesstech.com/javascript/string_substring_method

Arguments

from It should be a non negative integer to specify index from where sub-string should start. to An optional non negative integer to provide index before which sub-string should be finished.

Basic HTTP authentication with Node and Express 4

I used the code for the original basicAuth to find the answer:

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

Format string to a 3 digit number

Does it have to be String.Format?

This looks like a job for String.Padleft

myString=myString.PadLeft(3, '0');

Or, if you are converting direct from an int:

myInt.toString("D3");

Generate insert script for selected records?

In SSMS execute your sql query. From the result window select all cells and copy the values. Goto below website and there you can paste the copied data and generate sql scripts. You can also save results of query from SSMS as CSV file and import the csv file in this website.

http://www.convertcsv.com/csv-to-sql.htm

SQLite UPSERT / UPDATE OR INSERT

To have a pure UPSERT with no holes (for programmers) that don't relay on unique and other keys:

UPDATE players SET user_name="gil", age=32 WHERE user_name='george'; 
SELECT changes();

SELECT changes() will return the number of updates done in the last inquire. Then check if return value from changes() is 0, if so execute:

INSERT INTO players (user_name, age) VALUES ('gil', 32); 

How to grep (search) committed code in the Git history

To search for commit content (i.e., actual lines of source, as opposed to commit messages and the like), you need to do:

git grep <regexp> $(git rev-list --all)

git rev-list --all | xargs git grep <expression> will work if you run into an "Argument list too long" error.

If you want to limit the search to some subtree (for instance, "lib/util"), you will need to pass that to the rev-list subcommand and grep as well:

git grep <regexp> $(git rev-list --all -- lib/util) -- lib/util

This will grep through all your commit text for regexp.

The reason for passing the path in both commands is because rev-list will return the revisions list where all the changes to lib/util happened, but also you need to pass to grep so that it will only search in lib/util.

Just imagine the following scenario: grep might find the same <regexp> on other files which are contained in the same revision returned by rev-list (even if there was no change to that file on that revision).

Here are some other useful ways of searching your source:

Search working tree for text matching regular expression regexp:

git grep <regexp>

Search working tree for lines of text matching regular expression regexp1 or regexp2:

git grep -e <regexp1> [--or] -e <regexp2>

Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only:

git grep -l -e <regexp1> --and -e <regexp2>

Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2:

git grep -l --all-match -e <regexp1> -e <regexp2>

Search working tree for changed lines of text matching pattern:

git diff --unified=0 | grep <pattern>

Search all revisions for text matching regular expression regexp:

git grep <regexp> $(git rev-list --all)

Search all revisions between rev1 and rev2 for text matching regular expression regexp:

git grep <regexp> $(git rev-list <rev1>..<rev2>)

multiple packages in context:component-scan, spring config

You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");

OR

string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

I've resolved the fully qualified domain name message on different occasions by adding my server hostname to the /etc/apache2/httpd.conf file and to the /etc/apache2/apache2.conf file.

Type hostname -f in your terminal. This query will return your hostname.

Then edit the /etc/apache2/httpd.conf file (or create it if it does not exist for some reason) and add ServerName <your_hostname>.

Alternatively, I have also been able to eliminate the message by adding ServerName <your_hostname> to the /etc/apache2/apache2.conf file.

If all goes well, when you restart Apache, the message will be gone.

Should a RESTful 'PUT' operation return something

I used RESTful API in my services, and here is my opinion: First we must get to a common view: PUT is used to update an resource not create or get.

I defined resources with: Stateless resource and Stateful resource:

  • Stateless resources For these resources, just return the HttpCode with empty body, it's enough.

  • Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.

But, for a service or system, keep it simple, clearly, easy to use and maintain is the most important thing.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

NOTE: Not sure it works with the latest version of Angular.

ORIGINAL:

It's also possible to override the OPTIONS request (was only tested in Chrome):

app.config(['$httpProvider', function ($httpProvider) {
  //Reset headers to avoid OPTIONS request (aka preflight)
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
}]);

URL to load resources from the classpath in Java

Solution with registering URLStreamHandlers is most correct, of course, but sometimes the simplest solution is needed. So, I use the following method for that:

/**
 * Opens a local file or remote resource represented by given path.
 * Supports protocols:
 * <ul>
 * <li>"file": file:///path/to/file/in/filesystem</li>
 * <li>"http" or "https": http://host/path/to/resource - gzipped resources are supported also</li>
 * <li>"classpath": classpath:path/to/resource</li>
 * </ul>
 *
 * @param path An URI-formatted path that points to resource to be loaded
 * @return Appropriate implementation of {@link InputStream}
 * @throws IOException in any case is stream cannot be opened
 */
public static InputStream getInputStreamFromPath(String path) throws IOException {
    InputStream is;
    String protocol = path.replaceFirst("^(\\w+):.+$", "$1").toLowerCase();
    switch (protocol) {
        case "http":
        case "https":
            HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
            int code = connection.getResponseCode();
            if (code >= 400) throw new IOException("Server returned error code #" + code);
            is = connection.getInputStream();
            String contentEncoding = connection.getContentEncoding();
            if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"))
                is = new GZIPInputStream(is);
            break;
        case "file":
            is = new URL(path).openStream();
            break;
        case "classpath":
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path.replaceFirst("^\\w+:", ""));
            break;
        default:
            throw new IOException("Missed or unsupported protocol in path '" + path + "'");
    }
    return is;
}

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize will resize the component to the specified size.

setPreferredSize sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.

Changing the highlight color when selecting text in an HTML text input

I guess this can help :

selection styles

It's possible to define color and background for text the user selects.

Try it below. If you select something and it looks like this, your browser supports selection styles.

This is the paragraph with normal ::selection.

This is the paragraph with ::-moz-selection.

This is the paragraph with ::-webkit-selection.

Testsheet:

p.normal::selection {
  background:#cc0000;
  color:#fff;
}

p.moz::-moz-selection {
  background:#cc0000;
  color:#fff;
}

p.webkit::-webkit-selection {
  background:#cc0000;
  color:#fff;
}

Quoted from Quirksmode

Insert some string into given string at given index in Python

I had a similar problem for my DNA assignment and I used bgporter's advice to answer it. Here is my function which creates a new string...

def insert_sequence(str1, str2, int):
    """ (str1, str2, int) -> str

    Return the DNA sequence obtained by inserting the 
    second DNA sequence into the first DNA sequence 
    at the given index.

    >>> insert_sequence('CCGG', 'AT', 2)
    CCATGG
    >>> insert_sequence('CCGG', 'AT', 3)
    CCGATG
    >>> insert_sequence('CCGG', 'AT', 4)
    CCGGAT
    >>> insert_sequence('CCGG', 'AT', 0)
    ATCCGG
    >>> insert_sequence('CCGGAATTGG', 'AT', 6)
    CCGGAAATTTGG

    """

    str1_split1 = str1[:int]
    str1_split2 = str1[int:]
    new_string = str1_split1 + str2 + str1_split2
    return new_string

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

How to listen for a WebView finishing loading a URL?

You can trace the Progress Staus by the getProgress method in webview class.

Initialize the progress status

private int mProgressStatus = 0;

then the AsyncTask for loading like this:

private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
    private final ProgressDialog dialog = new ProgressDialog(
            your_class.this);

    // can use UI thread here
    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            while (mProgressStatus < 100) {
                mProgressStatus = webview.getProgress();

            }
        } catch (Exception e) {

        }
        return null;

    }

    protected void onPostExecute(Void result) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
    }
}

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

Angular2 module has no exported member

In my module i am exporting classes this way:

export { SigninComponent } from './SigninComponent';
export { RegisterComponent } from './RegisterComponent';

This allow me to import multiple classes in file from same module:

import { SigninComponent, RegisterComponent} from "../auth.module";

PS: Of course @Fjut answer is correct, but same time it doesn't support multiple imports from same file. I would suggest to use both answers for your needs. But importing from module makes folder structure refactorings more easier.

How to set 24-hours format for date on java?

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);

HH will return 0-23 for hours.

kk will return 1-24 for hours.

See more here: Customizing Formats

use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.

How to replace NaNs by preceding values in pandas DataFrame?

One thing that I noticed when trying this solution is that if you have N/A at the start or the end of the array, ffill and bfill don't quite work. You need both.

In [224]: df = pd.DataFrame([None, 1, 2, 3, None, 4, 5, 6, None])

In [225]: df.ffill()
Out[225]:
     0
0  NaN
1  1.0
...
7  6.0
8  6.0

In [226]: df.bfill()
Out[226]:
     0
0  1.0
1  1.0
...
7  6.0
8  NaN

In [227]: df.bfill().ffill()
Out[227]:
     0
0  1.0
1  1.0
...
7  6.0
8  6.0

When to use references vs. pointers

Any performance difference would be so small that it wouldn't justify using the approach that's less clear.

First, one case that wasn't mentioned where references are generally superior is const references. For non-simple types, passing a const reference avoids creating a temporary and doesn't cause the confusion you're concerned about (because the value isn't modified). Here, forcing a person to pass a pointer causes the very confusion you're worried about, as seeing the address taken and passed to a function might make you think the value changed.

In any event, I basically agree with you. I don't like functions taking references to modify their value when it's not very obvious that this is what the function is doing. I too prefer to use pointers in that case.

When you need to return a value in a complex type, I tend to prefer references. For example:

bool GetFooArray(array &foo); // my preference
bool GetFooArray(array *foo); // alternative

Here, the function name makes it clear that you're getting information back in an array. So there's no confusion.

The main advantages of references are that they always contain a valid value, are cleaner than pointers, and support polymorphism without needing any extra syntax. If none of these advantages apply, there is no reason to prefer a reference over a pointer.

Right to Left support for Twitter Bootstrap 3

If you want Bootstrap 3 support for RTL and LTR on your site, you can modify CSS rules "on the fly", attached here is a function, it modifies the major classes for Bootstrap 3 like col-(xs|sm|md|lg)-(1-12), col-(xs|sm|md|lg)-push-(1-12), col-(xs|sm|md|lg)-pull-(1-12), col-(xs|sm|md|lg)-offset-(1-12), there are many more classes to be modified but i needed only those.

All you need to do is call the function layout.setDirection('rtl') or layout.setDirection('ltr') and it will change the CSS Rules for Bootstrap 3 grid system.

Should work on all browsers (IE>=9).

        var layout = {};
        layout.setDirection = function (direction) {
            layout.rtl = (direction === 'rtl');
            document.getElementsByTagName("html")[0].style.direction = direction;
            var styleSheets = document.styleSheets;
            var modifyRule = function (rule) {
                if (rule.style.getPropertyValue(layout.rtl ? 'left' : 'right') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-push-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'right' : 'left'), rule.style.getPropertyValue((layout.rtl ? 'left' : 'right')));
                    rule.style.removeProperty((layout.rtl ? 'left' : 'right'));
                }
                if (rule.style.getPropertyValue(layout.rtl ? 'right' : 'left') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-pull-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'left' : 'right'), rule.style.getPropertyValue((layout.rtl ? 'right' : 'left')));
                    rule.style.removeProperty((layout.rtl ? 'right' : 'left'));
                }
                if (rule.style.getPropertyValue(layout.rtl ? 'margin-left' : 'margin-right') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-offset-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'margin-right' : 'margin-left'), rule.style.getPropertyValue((layout.rtl ? 'margin-left' : 'margin-right')));
                    rule.style.removeProperty((layout.rtl ? 'margin-left' : 'margin-right'));
                }
                if (rule.style.getPropertyValue('float') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-\d\d*/)) {
                    rule.style.setProperty('float', (layout.rtl ? 'right' : 'left'));
                }
            };
            try {
                for (var i = 0; i < styleSheets.length; i++) {
                    var rules = styleSheets[i].cssRules || styleSheets[i].rules;
                    if (rules) {
                        for (var j = 0; j < rules.length; j++) {
                            if (rules[j].type === 4) {
                                var mediaRules = rules[j].cssRules || rules[j].rules
                                for (var y = 0; y < mediaRules.length; y++) {
                                    modifyRule(mediaRules[y]);
                                }
                            }
                            if (rules[j].type === 1) {
                                modifyRule(rules[j]);
                            }

                        }
                    }
                }
            } catch (e) {
                // Firefox might throw a SecurityError exception but it will work
                if (e.name !== 'SecurityError') {
                    throw e;
                }
            }
        }

Process.start: how to get the output?

The standard .NET way of doing this is to read from the Process' StandardOutput stream. There is an example in the linked MSDN docs. Similar, you can read from StandardError, and write to StandardInput.

How to calculate an angle from three points?

In Objective-C you could do this by

float xpoint = (((atan2((newPoint.x - oldPoint.x) , (newPoint.y - oldPoint.y)))*180)/M_PI);

Or read more here

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

Proper way to handle multiple forms on one page in Django

You have a few options:

  1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

  2. Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?

How to remove all CSS classes using jQuery/JavaScript?

I had similar issue. In my case on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jquery to remove this class on every element/control I wont and everything works and looks great now.

This is my code for removing aspNetDisabled class:

$(document).ready(function () {

    $("span").removeClass("aspNetDisabled");
    $("select").removeClass("aspNetDisabled");
    $("input").removeClass("aspNetDisabled");

}); 

Where does forever store console.log output?

It is a old question but i ran across the same issues. If you wanna see live output you can run

forever logs

This would show the path of the logs file as well as the number of the script. You can then use

forever logs 0 -f

0 should be replaced by the number of the script you wanna see the output for.

How to drop a unique constraint from table column?

   ALTER TABLE dbo.table
DROP CONSTRAINT uq_testConstrain

constraint name uq_testConstrain can be found under database->table->keys folder

Get ID from URL with jQuery

You could just use window.location.hash to grab the id.

var id = window.location.hash;

I don't think you will need that much code to achieve this.

X-Frame-Options Allow-From multiple domains

Strictly speaking no, you cant.

You can however specify X-Frame-Options: mysite.com and therefore allow subdomain1.mysite.com and subdomain2.mysite.com. But yes, that's still one domain. There happens to be some workaround for this, but I think it's easiest to read that directly at the RFC specs: https://tools.ietf.org/html/rfc7034

It's also worth to point out that the Content-Security-Policy (CSP) header's frame-ancestor directive obsoletes X-Frame-Options. Read more here.

How do I disable text selection with CSS or JavaScript?

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>

C# Regex for Guid

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:

[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?

Example C# code:

var result = Regex.Replace(
      source, 
      @"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?", 
      @"${ __UUID}", 
      RegexOptions.IgnoreCase
);

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 

How to set an image as a background for Frame in Swing GUI of java?

Here is another quick approach without using additional panel.

JFrame f = new JFrame("stackoverflow") { 
  private Image backgroundImage = ImageIO.read(new File("background.jpg"));
  public void paint( Graphics g ) { 
    super.paint(g);
    g.drawImage(backgroundImage, 0, 0, null);
  }
};

Array String Declaration

Declare the array size will solve your problem

 String[] title = {
            "Abundance",
            "Anxiety",
            "Bruxism",
            "Discipline",
            "Drug Addiction"
        };
    String urlbase = "http://www.somewhere.com/data/";
    String imgSel = "/logo.png";
    String[] mStrings = new String[title.length];

    for(int i=0;i<title.length;i++) {
        mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;

        System.out.println(mStrings[i]);
    }

Bootstrap Carousel : Remove auto slide

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: 40000,
  });
});

By using the above script, you will be able to move the images automaticaly

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: false,
  });
});

By using the above script, auto-rotation will be blocked because interval is false

How to override the path of PHP to use the MAMP path?

you might still run into mysql binary not being found in that manner

open terminal, type
touch ~/.bash_profile; open ~/.bash_profile

edit as follows below, save, quite and restart terminal or alternately

source ~/.bash_profile

to execute new PATH without restarting terminal

and in the fashion of the DavidYell's post above, also add the following. You can stack various variables by exporting them followed by a single PATH export which I demonstrated below

export MAMP_PHP=/Applications/MAMP/bin/php/php5.6.2/bin
export MAMP_BINS=/Applications/MAMP/Library/bin
export USERBINS=~/bins
export PATH="$USERBINS:$MAMP_PHP:$MAMP_BINS:$PATH"

cheers

How can I handle the warning of file_get_contents() function in PHP?

The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones. http://www.php.net/set_error_handler

How to convert comma-separated String to List?

In groovy, you can use tokenize(Character Token) method:

list = str.tokenize(',')

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Send file using POST from a Python script

The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a len definition. A simple way is to create a subclass, which provides urlopen with the correct file. I have also modified the Content-Type header in the file below.

import os
import urllib2
class EnhancedFile(file):
    def __init__(self, *args, **keyws):
        file.__init__(self, *args, **keyws)

    def __len__(self):
        return int(os.fstat(self.fileno())[6])

theFile = EnhancedFile('a.xml', 'r')
theUrl = "http://example.com/abcde"
theHeaders= {'Content-Type': 'text/xml'}

theRequest = urllib2.Request(theUrl, theFile, theHeaders)

response = urllib2.urlopen(theRequest)

theFile.close()


for line in response:
    print line

Does SVG support embedding of bitmap images?

You can use a data: URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?

Push Notifications in Android Platform

You can use Pusher

It's a hosted service that makes it super-easy to add real-time data and functionality to web and mobile applications.
Pusher offers libraries to integrate into all the main runtimes and frameworks.

PHP, Ruby, Python, Java, .NET, Go and Node on the server
JavaScript, Objective-C (iOS) and Java (Android) on the client.

Looping from 1 to infinity in Python

def infinity():
    i=0
    while True:
        i+=1
        yield i


for i in infinity():
    if there_is_a_reason_to_break(i):
        break

Build an iOS app without owning a mac?

Update from 09/2017

It is possible to develop iOS (and Android at the same time) application using React Native + Expo without owning a mac. You will also be able to run your iOS application within iOS Expo app while developing it. (You can even publish it for other people to access, but it will only run within Expo app). Here is page from Expo on how to generate standalone app.

Steps from that page:

One: Install exp by running npm install -g exp

Two: Configure app.json (somewhere along these lines):

{
   "expo": {
    "name": "Your App Name",
    "icon": "./path/to/your/app-icon.png",
    "version": "1.0.0",
    "slug": "your-app-slug",
    "sdkVersion": "17.0.0",
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourappname"
    },
    "android": {
      "package": "com.yourcompany.yourappname"
    }
   }
 }

Three: Start exp packeger with exp start

Four: run exp build:android or exp build:ios.

You will be prompted for some input. For android you can choose 1) Let Expo handle the process! if you don't have keystore (or if you don't know what it is). For iOS you will have to enter your Apple developer credentials. Then you can provide distribution certificate or let expo handle it.

Five: Once in a while you will have to come back and run exp build:status command to check whether your build was complete. If complete you will be provided a direct link to .apk or .ipa file.

The only drawback to this approach is that it won't be as native as writing iOS app in Swift, and you will have to put up with parade of issues you may run into while developing with weakly typed js, npm, and it's dependency-on-particular-version-of-some-other-library issues, and other stuff.

Can you use Microsoft Entity Framework with Oracle?

Update:

Oracle now fully supports the Entity Framework. Oracle Data Provider for .NET Release 11.2.0.3 (ODAC 11.2) Release Notes: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/whatsnew.htm#BGGJIEIC

More documentation on Linq to Entities and ADO.NET Entity Framework: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/featLINQ.htm#CJACEDJG

Note: ODP.NET also supports Entity SQL.

Is there any method to get the URL without query string?

If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]

Find size of object instance in bytes in c#

For value types, you can use Marshal.SizeOf. Of course, it returns the number of bytes required to marshal the structure in unmanaged memory, which is not necessarily what the CLR uses.

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

Responsive font size in CSS

I had just come up with an idea with which you only have to define the font size once per element, but it is still influenced by media queries.

First, I set the variable "--text-scale-unit" to "1vh" or "1vw", depending on the viewport using the media queries.

Then I use the variable using calc() and my multiplicator number for font-size:

_x000D_
_x000D_
/* Define a variable based on the orientation. */_x000D_
/* The value can be customized to fit your needs. */_x000D_
@media (orientation: landscape) {_x000D_
  :root{_x000D_
    --text-scale-unit: 1vh;_x000D_
  }_x000D_
}_x000D_
@media (orientation: portrait) {_x000D_
  :root {_x000D_
    --text-scale-unit: 1vw;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
/* Use a variable with calc and multiplication. */_x000D_
.large {_x000D_
  font-size: calc(var(--text-scale-unit) * 20);_x000D_
}_x000D_
.middle {_x000D_
  font-size: calc(var(--text-scale-unit) * 10);_x000D_
}_x000D_
.small {_x000D_
  font-size: calc(var(--text-scale-unit) * 5);_x000D_
}_x000D_
.extra-small {_x000D_
  font-size: calc(var(--text-scale-unit) * 2);_x000D_
}
_x000D_
<span class="middle">_x000D_
  Responsive_x000D_
</span>_x000D_
<span class="large">_x000D_
  text_x000D_
</span>_x000D_
<span class="small">_x000D_
  with one_x000D_
</span>_x000D_
<span class="extra-small">_x000D_
  font-size tag._x000D_
</span>
_x000D_
_x000D_
_x000D_

In my example I only used the orientation of the viewport, but the principle should be possible with any media queries.

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

How to iterate through a list of objects in C++

if you add an #include <algorithm> then you can use the for_each function and a lambda function like so:

for_each(data.begin(), data.end(), [](Student *it) 
{
    std::cout<<it->name;
});

you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm

and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019

How to get text with Selenium WebDriver in Python

The answer is:

driver.find_element_by_class_name("ctsymbol").text

How to easily initialize a list of Tuples?

C# 6 adds a new feature just for this: extension Add methods. This has always been possible for VB.net but is now available in C#.

Now you don't have to add Add() methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add() method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.

public static class TupleListExtensions
{
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
            T1 item1, T2 item2)
    {
        list.Add(Tuple.Create(item1, item2));
    }

    public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
            T1 item1, T2 item2, T3 item3)
    {
        list.Add(Tuple.Create(item1, item2, item3));
    }

    // and so on...
}

This will allow you to do this on any class that implements IList<>:

var numbers = new List<Tuple<int, string>>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" },
    { 4, "four" },
    { 5, "five" },
};
var points = new ObservableCollection<Tuple<double, double, double>>
{
    { 0, 0, 0 },
    { 1, 2, 3 },
    { -4, -2, 42 },
};

Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.

public static class BigIntegerListExtensions
{
    public static void Add(this IList<BigInteger> list,
        params byte[] value)
    {
        list.Add(new BigInteger(value));
    }

    public static void Add(this IList<BigInteger> list,
        string value)
    {
        list.Add(BigInteger.Parse(value));
    }
}

var bigNumbers = new List<BigInteger>
{
    new BigInteger(1), // constructor BigInteger(int)
    2222222222L,       // implicit operator BigInteger(long)
    3333333333UL,      // implicit operator BigInteger(ulong)
    { 4, 4, 4, 4, 4, 4, 4, 4 },               // extension Add(byte[])
    "55555555555555555555555555555555555555", // extension Add(string)
};

C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.

public static class ValueTupleListExtensions
{
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
        ValueTuple<T1, T2> item) => list.Add(item.ToTuple());
}

This way the list initialization will look even nicer.

var points = new List<Tuple<int, int, int>>
{
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),
};

But instead of going through all this trouble, it might just be better to switch to using ValueTuple exclusively.

var points = new List<(int, int, int)>
{
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),
};

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

How can I trim beginning and ending double quotes from a string?

I am using something as simple as this :

if(str.startsWith("\"") && str.endsWith("\""))
        {
            str = str.substring(1, str.length()-1);
        }

Array Size (Length) in C#

What has been missed so far is what I suddenly was irritated about:

How do I know the amount of items inside the array? Is .Length equal .Count of a List?

The answer is: the amount of items of type X which have been put into an array of type X created with new X[number] you have to carry yourself!

Eg. using a counter: int countItemsInArray = 0 and countItemsInArray++ for every assignment to your array.

(The array just created with new X[number] has all space for number items (references) of type X already allocated, you can assign to any place inside as your first assignment, for example (if number = 100 and the variable name = a) a[50] = new X();.

I don't know whether C# specifies the initial value of each place inside an array upon creation, if it doesn't or the initial value you cannot compare to (because it might be a value you yourself have put into the array), you would have to track which places inside the array you already assigned to too if you don't assign sequentially starting from 0 (in which case all places smaller than countItemsInArray would be assigned to).)

In your question size of an array (length / number of items) depending on whether / is meant to stand for "alternative" or "divide by" the latter still has to be covered (the "number of items" I just gave as "amount of items" and others gave .Length which corresponds to the value of number in my code above):

C# has a sizeof operator (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof). It's safe to use for built-in types (such as int) (and only operates on types (not variables)). Thus the size of an array b of type int in bytes would be b.Length * sizeof(int).

(Due to all space of an array already being allocated on creation, like mentioned above, and sizeof only working on types, no code like sizeof(variable)/sizeof(type) would work or yield the amount of items without tracking.)

Casting a variable using a Type variable

After not finding anything to get around "Object must implement IConvertible" exception when using Zyphrax's answer (except for implementing the interface).. I tried something a little bit unconventional and worked for my situation.

Using the Newtonsoft.Json nuget package...

var castedObject = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(myObject), myType);

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

PostgreSQL: Which version of PostgreSQL am I running?

If you're using CLI and you're a postgres user, then you can do this:

psql -c "SELECT version();"


Possible output:

                                                         version                                                         
-------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 11.1 (Debian 11.1-3.pgdg80+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10+deb8u2) 4.9.2, 64-bit
(1 row)

How to set JAVA_HOME environment variable on Mac OS X 10.9?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

At times the error code 409 occurs when you name you folder or files a reserved or blocked name. These could be names like register, contact

In my case I named a folder contact, turns out the name was blocked from being used as folder names.

When testing my script on postman, I was getting this error:

<script>
    document.cookie = "humans_21909=1"; document.location.reload(true)
</script>

I changed the folder name from contact to contacts and it worked. The error was gone.

What is the problem with shadowing names defined in outer scopes?

It depends how long the function is. The longer the function, the greater the chance that someone modifying it in future will write data thinking that it means the global. In fact, it means the local, but because the function is so long, it's not obvious to them that there exists a local with that name.

For your example function, I think that shadowing the global is not bad at all.

How to create a windows service from java app

I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

How do you cast a List of supertypes to a List of subtypes?

You really can't*:

Example is taken from this Java tutorial

Assume there are two types A and B such that B extends A. Then the following code is correct:

    B b = new B();
    A a = b;

The previous code is valid because B is a subclass of A. Now, what happens with List<A> and List<B>?

It turns out that List<B> is not a subclass of List<A> therefore we cannot write

    List<B> b = new ArrayList<>();
    List<A> a = b; // error, List<B> is not of type List<A>

Furthermore, we can't even write

    List<B> b = new ArrayList<>();
    List<A> a = (List<A>)b; // error, List<B> is not of type List<A>

*: To make the casting possible we need a common parent for both List<A> and List<B>: List<?> for example. The following is valid:

    List<B> b = new ArrayList<>();
    List<?> t = (List<B>)b;
    List<A> a = (List<A>)t;

You will, however, get a warning. You can suppress it by adding @SuppressWarnings("unchecked") to your method.

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

My Custom Toolbar XML

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

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

Max size of an iOS application

50 Meg is the max for Cell data download.

But you might be able to keep it under that in the app store and then have the app download other content after the user install and runs the app, so the app can be bigger. But not sure what the apple rules are for this.

I know that all in-app purchases need to be approved, but not sure if this kind of content needs to be approved.

In android how to set navigation drawer header image and name programmatically in class file?

  nav = ( NavigationView ) findViewById( R.id.navigation );

    if( nav != null ){
        LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );

        if( mParent != null ){
            // Set your values to the image and text view by declaring and setting as you need to here.

            SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
            String photoUrl = prefs.getString("photo_url", null);
            String user_name = prefs.getString("name", "User");

            if(photoUrl!=null) {
                Log.e("Photo Url: ", photoUrl);

                TextView userName = mParent.findViewById(R.id.user_name);
                userName.setText(user_name);

                ImageView user_imageView = mParent.findViewById(R.id.avatar);

                RequestOptions requestOptions = new RequestOptions();
                requestOptions.placeholder(R.drawable.ic_user_24dp);
                requestOptions.error(R.drawable.ic_user_24dp);

                Glide.with(this).load(photoUrl)
                        .apply(requestOptions).thumbnail(0.5f).into(user_imageView);

            }

        }
    }

Hope this helps.

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

PHP - print all properties of an object

To get more information use this custom TO($someObject) function:

I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.

function TO($object){ //Test Object
                if(!is_object($object)){
                    throw new Exception("This is not a Object"); 
                    return;
                }
                if(class_exists(get_class($object), true)) echo "<pre>CLASS NAME = ".get_class($object);
                $reflection = new ReflectionClass(get_class($object));
                echo "<br />";
                echo $reflection->getDocComment();

                echo "<br />";

                $metody = $reflection->getMethods();
                foreach($metody as $key => $value){
                    echo "<br />". $value;
                }

                echo "<br />";

                $vars = $reflection->getProperties();
                foreach($vars as $key => $value){
                    echo "<br />". $value;
                }
                echo "</pre>";
            }

To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:

        /**
         * DocNotes -  This is description of this class if given else it will display false
         */
        class Person{
            private $name;
            private $dob;
            private $height;
            private $weight;
            private static $num;

            function __construct($dbo, $height, $weight, $name) {
                $this->dob = $dbo;
                $this->height = (integer)$height;
                $this->weight = (integer)$weight;
                $this->name = $name;
                self::$num++;

            }
            public function eat($var="", $sar=""){
                echo $var;
            }
            public function potrzeba($var =""){
                return $var;
            }
        }

Now lets create a instance of a Person and wrap it with our function.

    $Wictor = new Person("27.04.1987", 170, 70, "Wictor");
    TO($Wictor);

This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:

CLASS NAME = Person
/**
             * DocNotes -  This is description of this class if given else it will display false
             */

Method [  public method __construct ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 75 - 82

  - Parameters [4] {
    Parameter #0 [  $dbo ]
    Parameter #1 [  $height ]
    Parameter #2 [  $weight ]
    Parameter #3 [  $name ]
  }
}

Method [  public method eat ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 83 - 85

  - Parameters [2] {
    Parameter #0 [  $var = '' ]
    Parameter #1 [  $sar = '' ]
  }
}

Method [  public method potrzeba ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 86 - 88

  - Parameters [1] {
    Parameter #0 [  $var = '' ]
  }
}


Property [  private $name ]

Property [  private $dob ]

Property [  private $height ]

Property [  private $weight ]

Property [ private static $num ]

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

How to use the TextWatcher class in Android?

    public class Test extends AppCompatActivity {

    EditText firstEditText;
    EditText secondEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        firstEditText = (EditText)findViewById(R.id.firstEditText);
        secondEditText = (EditText)findViewById(R.id.secondEditText);

        firstEditText.addTextChangedListener(new EditTextListener());

    }

    private class EditTextListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            secondEditText.setText(firstEditText.getText());
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

If you get an icon error when submitting an application from Xcode9, or if you cannot see app icon on your simulator as well as a device, just update your cocoapods to the latest version in your project. That issue is a bug in Xcode9 with cocoapods.


There's a new guideline for iPhoneX that can be seen here.


Here's a helpful website that creates an icon for iOS, Mac App and Android app.

You just need to drag and drop your 1024 x 1024 icon and the site will create all the icon sizes and send it to your email. Then follow the following method to set icons for iOS app.

After Apple launched iOS 8, iPhone 6 and 6 Plus, the app icon sizes and launch image sizes changed. Please visit my post for new sizes:

Image resolution for new iPhone 6 and 6+, @3x support added?


Yes, you need to add a 120x120 high resolution icon. Now, if you want to target only iOS 7, you just need 76 x 76, 120 x 120 and 152 x 152 icon sizes. If you also want to target iOS 6, you’ll need 57 x 57, 72 x 72, 76 x 76, 114 x 114, 120 x 120, 144 x 144 and 152 x 152 icon sizes. Without counting Spotlight and Settings icon if you don’t want the OS to interpolate them!

Enter image description here

Enter image description here

As per the blog post New Metrics for iOS 7 App Icons.

UPDATE:

As per Apple Guideline App-icon OR Icon and Image Sizes:

Icon dimensions (iOS 7 and later)

Enter image description here

Icon dimensions (iOS 6.1 and earlier)

Enter image description here

Create different sizes of the app icon for different devices. If you’re creating a universal app, you need to supply app icons in all four sizes.

For iPhone and iPod touch, both of these sizes are required:

  • 120 x 120 pixels

  • 60 x 60 pixels (standard resolution)

For iPad, both of these sizes are required:

  • 152 x 152

  • 76 x 76 pixels (standard resolution)


Now set this into Project:

  • Create a new icon with 120 pixels with high-resolution and 60 pixels as regular as above that the Apple documentation mentions and set the name. For example, icon-120.png and icon-152.png.

  • Put this icons into your project Resource folder and add this icon into the project:

Enter image description here

  • After this, click on ProjectName-Info.plist and find the icon files row. If you can't find it, then add it by clicking the (+) sign and select icon files and then set all icon images like below.

Enter image description here

Enter image description here

Now archive and distribute your project as we did for submission of the app binary into the App Store. I hope now you can submit your app without any icon issue.


NOTE:

Be careful to provide all the icons you need. Otherwise your app will not pass Apple validation. If you’ve received this kind of email:

Invalid Image - For iOS applications, icons included in the binary submission must be in the PNG format.

- If your application supports the iPhone device family, you must include square icons of the following dimensions: 57x57 pixels and 120x120 pixels.

- If your application supports the iPad device family, you must include square icons of the following dimensions: 72x72 pixels, 76x76 pixels and 152x152 pixels

Apple is now accepting applications that work on iOS 7 as well, so whatever the Deployment target 6.1 or earlier, but you also need to provide the iOS 7 icon sizes as I mention above (that the store is expecting).

Xcode 5 app icon Manage

If you are using xCode5 The first thing to update is the icons. Xcode 5 introduces Asset Catalogs to simply managing multiple copies of an image (such as for multiple resolutions). We’ll create one to manage both the Game’s icons, along with the Launch Images.

enter image description here

Now, click the Use Asset Catalog button. When confirming the migration, you’re also asked if you wish to migrate the Launch Images (which is iOS talk for the splash screen that appears when starting your app) - you’ll want to ensure this is checked as well.

enter image description here

Please take a Look for more Info Apple doc of Asset Catalogs

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

How to POST a FORM from HTML to ASPX page

You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post.

You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.

How to modify existing, unpushed commit messages?

For anyone looking for a Windows/Mac GUI to help with editing older messages (i.e. not just the latest message), I'd recommend Sourcetree. The steps to follow are below the image.

Sourcetree interactive rebase

For commits that haven't been pushed to a remote yet:

  1. Make sure you've committed or stashed all current changes (i.e., so there are no files listed in the "File Status" tab) - it won't work otherwise.
  2. In the "Log / History" tab, right click on the entry with an adjoining line in the graph one below the commit(s) you wish to edit and select "Rebase children of <commit ref> interactively..."
  3. Select the whole row for a commit message you wish to change (click on the "Message" column).
  4. Click the "Edit Message" button.
  5. Edit the message as desired in the dialog that comes up and then click OK.
  6. Repeat steps 3-4 if there are other commit messages to change.
  7. Click OK: Rebasing will commence. If all is well, the output will end "Completed successfully". NOTE: I've sometimes seen this fail with Unable to create 'project_path/.git/index.lock': File exists. when trying to modify multiple commit messages at the same time. Not sure exactly what the issue is, or whether it will be fixed in a future version of Sourcetree, but if this happens would recommend rebasing them one at a time (slower but seems more reliable).

...Or... for commits that have already been pushed:

Follow the steps in this answer, which are similar to above, but require a further command to be run from the command line (git push origin <branch> -f) to force-push the branch. I'd recommend reading it all and applying the necessary caution!

What is stdClass in PHP?

php.net manual has a few solid explanation and examples contributed by users of what stdClass is, I especially like this one http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773.

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

SQL Server: Examples of PIVOTing String data

I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below

PIVOT(
  min(value)
  FOR ColTitle in([F4], [UR], [UQ])
 )

How to run a command in the background and get no output?

Run in a subshell to remove notifications and close STDOUT and STDERR:

(&>/dev/null script.sh &)

How to get the input from the Tkinter Text Widget?

To get Tkinter input from the text box in python 3 the complete student level program used by me is as under:

#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace

from tkinter import *

#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.

root = Tk()
root.title('how to get text from textbox')


#**********************************
mystring = StringVar()

####define the function that the signup button will do
def getvalue():
##    print(mystring.get())
#*************************************

Label(root, text="Text to get").grid(row=0, sticky=W)  #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox

WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button


############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()

mysql update column with value from another table

you need to join the two tables:

for instance you want to copy the value of name from tableA into tableB where they have the same ID

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.id = t2.id
SET t1.name = t2.name 
WHERE t2.name = 'Joe'

UPDATE 1

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.id = t2.id
SET t1.name = t2.name 

UPDATE 2

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.name = t2.name
SET t1.value = t2.value

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

Non-alphanumeric list order from os.listdir()

aaa = ['row_163.pkl', 'row_394.pkl', 'row_679.pkl', 'row_202.pkl', 'row_1449.pkl', 'row_247.pkl', 'row_1353.pkl', 'row_749.pkl', 'row_1293.pkl', 'row_1304.pkl', 'row_78.pkl', 'row_532.pkl', 'row_9.pkl', 'row_1435.pkl']                                                                                                                                                                                                                                                                                                 
sorted(aaa, key=lambda x: int(os.path.splitext(x.split('_')[1])[0]))

As In case of mine requirement I have the case like row_163.pkl here os.path.splitext('row_163.pkl') will break it into ('row_163', '.pkl') so need to split it based on '_' also.

but in case of your requirement you can do something like

sorted(aa, key = lambda x: (int(re.sub('\D','',x)),x))

where

aa = ['run01', 'run08', 'run11', 'run12', 'run13', 'run14', 'run18']

and also for directory retrieving you can do sorted(os.listdir(path))

and for the case of like 'run01.txt' or 'run01.csv' you can do like this

sorted(files, key=lambda x : int(os.path.splitext(x)[0]))

bash "if [ false ];" returns true instead of false -- why?

as noted by @tripleee, this is tangential, at best.

still, in case you arrived here searching for something like that (as i did), here is my solution

having to deal with user acessible configuration files, i use this function :

function isTrue() {
    if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
    return 1
    }

wich can be used like that

if isTrue "$whatever"; then..

You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".

note that the '^^' provides case insensivity

Check if the file exists using VBA

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

Works very well, almost, at my site. If I call it with "" the empty string, Dir returns "connection.odc"!! Would be great if you guys could share your result.

Anyway, I do like this:

Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function

VSCode: How to Split Editor Vertically

If you're looking for a way to change this through the GUI, at least in the current version 1.10.1 if you hover over the OPEN EDITORS group in the EXPLORER pane a button appears that toggles the editor group layout between horizontal and vertical.

Visual Studio Code - toggle editor group layout button

More Pythonic Way to Run a Process X Times

Personally:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.

Why is null an object and what's the difference between null and undefined?

null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).

undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.

null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.

How to resize image (Bitmap) to a given size?

The other answers are correct as to "how" to resize them, but I would also thrown in the recommendation to just grab the resolution you are interested in, to begin with. Most Android devices offer a range of resolutions and you should pick one that gives you a file size that you're comfortable with. The biggest reason for this is that the native Android scaling algorithm (as detailed by Jin35 and Padma Kumar) produces pretty crappy results. It's not going to give you Photoshop quality resizing, even downscaling (to say nothing of upscaling, which I know you're not asking about, but that's just a non-starter).

So, you should try their solution and if you're happy with the outcome, great. But if not, I'd write a function that offers a range of width that you're happy with, and looks for that dimension (or whatever's closest) in the device's available picture size array and just set it and use it.

How to link an image and target a new window

To open in a new tab use:

target = "_blank"

To open in the same tab use:

target = "_self"