Programs & Examples On #Xmlstore

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

I/O error(socket error): [Errno 111] Connection refused

Its seems that server is not running properly so ensure that with terminal by

telnet ip port

example

telnet localhost 8069

It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection

Execute PowerShell Script from C# with Commandline Arguments

Here is a way to add Parameters to the script if you used

pipeline.Commands.AddScript(Script);

This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
  // Add additional variables to PowerShell
  if (scriptParameters != null)
  {
    foreach (DictionaryEntry entry in scriptParameters)
    {
      CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
      pipeline.Commands[0].Parameters.Add(Param);
    }
  }
}

this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");

//results being the name of the v

you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.

Add custom icons to font awesome

I suggest keeping your icons separate from FontAwesome and create and maintain your own custom library. Personally, I think it is much easier to maintain keeping FontAwesome separate if you are going to be creating your own icon library. You can then have FontAwesome loaded into your site from a CDN and never have to worry about keeping it up-to-date.

When creating your own custom icons, create each icon via Adobe Illustrator or similar software. Once your icons are created, save each individually in SVG format on your computer.

Next, head on over to IcoMoon: http://icomoon.io , which has the best font generating software (in my opinion), and it's free. IcoMoon will allow you to import your individual svg-saved fonts into a font library, then generate your custom icon glyph library in eot, ttf, woff, and svg. One format IcoMoon does not generate is woff2.

After generating your icon pack at IcoMoon, head over to FontSquirrel: http://fontsquirrel.com and use their font generator. Use your ttf file generated at IcoMoon. In the newly generated icon pack created, you'll now have your icon pack in woff2 format.

Make sure the files for eot, ttf, svg, woff, and woff2 are all the same name. You are generating an icon pack from two different websites/software, and they do name their generated output differently.

You'll have CSS generated for your icon pack at both locations. But the CSS generated at IcoMoon will not include the woff2 format in your @font-face {} declaration. Make sure to add that when you're adding your CSS to your project:

@font-face {
    font-family: 'customiconpackname';
    src: url('../fonts/customiconpack.eot?lchn8y');
    src: url('../fonts/customiconpack.eot?lchn8y#iefix') format('embedded-opentype'),
         url('../fonts/customiconpack.ttf?lchn8y') format('truetype'),
         url('../fonts/customiconpack.woff2?lchn8y') format('woff'),
         url('../fonts/customiconpack.woff?lchn8y') format('woff'),
         url('../fonts/customiconpack.svg?lchn8y#customiconpack') format('svg');
    font-weight: normal;
    font-style: normal;
}

Keep in mind that you can get the glyph unicode values of each icon in your icon pack using the IcoMoon software. These values can be helpful in assigning your icons via CSS, as in (assuming we're using the font-family declared in the example @font-face {...} above):

selector:after {
    font-family: 'customiconpackname';
    content: '\e953';
    }

You can also get the glyph unicode value e953 if you open the font-pack-generated svg file in a text editor. E.g.:

<glyph unicode="&#xe953;" glyph-name="eye" ... />

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

OSX Yosemite, ZSH, and Java SE Runtime Environment 8, I had to:

$ sudo ln -s /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands /System/Library/Frameworks/JavaVM.framework/Versions/Current/bin

and in ~/.zshrc change JAVA_HOME to export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/Current"

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

Iteration is synonymous with sprint, sprint is just the Scrum terminology.

On the question about sprint length, the only caution I would note is that in Scrum you are using the past sprints to gain a level of predictability on your teams ability to deliver on their commitments for the sprint. They do this by developing a velocity over a number of sprints. A change in the team members or the length of the sprint are factors that will affect the velocity for a sprint, over past sprints.

Just as background, velocity is the sum of estimation points assigned to the backlog items, or stories, that were completely finished during that sprint. Most Agile proponents (Mike Cohn, Ken Schwaber and Jeff Sutherland for instance), recommend that teams use "the recent weather" to base their future estimations on how much they think they can commit to in a sprint. This means using the average from the last few sprints as the basis for an estimate in the upcoming sprint planning session.

Once again, varying the sprint length reduces your teams ability to provide that velocity statistic which the team uses for sprint planning, and the product owner uses for release planning (i.e. predicting when the project will end or what will be in the project at the end).

I recommend Mike Cohn's book on Agile Estimating and Planning to provide an overview of the way sprints, estimation and planning all can fit together.

What is the purpose of nameof?

The ASP.NET Core MVC project uses nameof in the AccountController.cs and ManageController.cs with the RedirectToAction method to reference an action in the controller.

Example:

return RedirectToAction(nameof(HomeController.Index), "Home");

This translates to:

return RedirectToAction("Index", "Home");

and takes takes the user to the 'Index' action in the 'Home' controller, i.e. /Home/Index.

Read a HTML file into a string variable in memory

What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument(); followed by doc.Load(filename). Then the XML document can be parsed in memory.

Read here for more information on XmlDocument:

Run .php file in Windows Command Prompt (cmd)

If running Windows 10:

  1. Open the start menu
  2. Type path
  3. Click Edit the system environment variables (usually, it's the top search result) and continue on step 6 below.

If on older Windows:

  1. Show Desktop.

  2. Right Click My Computer shortcut in the desktop.

  3. Click Properties.

  4. You should see a section of control Panel - Control Panel\System and Security\System.

  5. Click Advanced System Settings on the Left menu.

  6. Click Enviornment Variables towards the bottom of the System Properties window.

  7. Select PATH in the user variables list.

  8. Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.

  9. Click OK

  10. Open your "cmd"

  11. Type PATH, press enter

  12. Make sure that you see your PHP folder among the list.

That should work.

Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.

React Native fetch() Network Request Failed

This worked for me, android uses a special type of IP address 10.0.2.2 then port number

import { Platform } from 'react-native';

export const baseUrl = Platform.OS === 'android' ?
    'http://10.0.2.2:3000/'
: 
'http://localhost:3000/';

Bootstrap carousel width and height

I know this is an older post but Bootstrap is still alive and kicking!

Slightly different to @Eduardo's post, I had to modify:

#myCarousel.carousel.slide {
    width: 100%; 
    max-width: 400px; !important
}

When I only modified .carousel-inner {}, the actual image was fixed size but the left/right controls were displaying incorrectly off to the side of the div.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

How to overload functions in javascript?

There are multiple aspects to argument overloading in Javascript:

  1. Variable arguments - You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.

  2. Default arguments - You can define a default value for an argument if it is not passed.

  3. Named arguments - Argument order becomes irrelevant and you just name which arguments you want to pass to the function.

Below is a section on each of these categories of argument handling.

Variable Arguments

Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of myFunc() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.

jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.

In implementing these types of overloads, you have several different techniques you can use:

  1. You can check for the presence of any given argument by checking to see if the declared argument name value is undefined.
  2. You can check the total quantity or arguments with arguments.length.
  3. You can check the type of any given argument.
  4. For variable numbers of arguments, you can use the arguments pseudo-array to access any given argument with arguments[i].

Here are some examples:

Let's look at jQuery's obj.data() method. It supports four different forms of usage:

obj.data("key");
obj.data("key", value);
obj.data();
obj.data(object);

Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.

Here's how one can discern between all these options in English and then I'll combine them all in code:

// get the data element associated with a particular key value
obj.data("key");

If the first argument passed to .data() is a string and the second argument is undefined, then the caller must be using this form.


// set the value associated with a particular key
obj.data("key", value);

If the second argument is not undefined, then set the value of a particular key.


// get all keys/values
obj.data();

If no arguments are passed, then return all keys/values in a returned object.


// set all keys/values from the passed in object
obj.data(object);

If the type of the first argument is a plain object, then set all keys/values from that object.


Here's how you could combine all of those in one set of javascript logic:

 // method declaration for .data()
 data: function(key, value) {
     if (arguments.length === 0) {
         // .data()
         // no args passed, return all keys/values in an object
     } else if (typeof key === "string") {
         // first arg is a string, look at type of second arg
         if (typeof value !== "undefined") {
             // .data("key", value)
             // set the value for a particular key
         } else {
             // .data("key")
             // retrieve a value for a key
         }
     } else if (typeof key === "object") {
         // .data(object)
         // set all key/value pairs from this object
     } else {
         // unsupported arguments passed
     }
 },

The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.

For example, if you have a function that takes three string arguments:

obj.query("firstArg", "secondArg", "thirdArg");

You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can't tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what's in the second argument's spot is actually the third argument:

obj.query("firstArg", "secondArg");
obj.query("firstArg", "thirdArg");

Since all three arguments are the same type, you can't tell the difference between different arguments so you don't know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as null (or some other detectable value) instead and your code would detect that:

obj.query("firstArg", null, "thirdArg");

Here's a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:

clone: function( dataAndEvents, deepDataAndEvents ) {
    dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
    deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

    return this.map( function () {
        return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
    });
},

Here's a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:

html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},

Named Arguments

Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.

Here's a simple ES5 example:

jQuery's $.ajax() accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.

Here's an example:

$.ajax({url: "http://www.example.com/somepath", data: myArgs, dataType: "json"}).then(function(result) {
    // process result here
});

Inside of the $.ajax() implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either with for (prop in obj) or by getting all the properties into an array with Object.keys(obj) and then iterating that array.

This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).

In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.

Here's one example from that article:

function selectEntries({ start=0, end=-1, step=1 } = {}) {
    ···
};

This creates default properties and values for the start, end and step properties on an object passed to the selectEntries() function.

Default values for function arguments

In ES6, Javascript adds built-in language support for default values for arguments.

For example:

function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5

Further description of the ways this can be used here on MDN.

How to check if a specified key exists in a given S3 bucket using Java

Use ListObjectsRequest setting Prefix as your key.

.NET code:

 public bool Exists(string key)
    {

        using (Amazon.S3.AmazonS3Client client = (Amazon.S3.AmazonS3Client)Amazon.AWSClientFactory.CreateAmazonS3Client(m_accessKey, m_accessSecret))
        {
            ListObjectsRequest request = new ListObjectsRequest();
            request.BucketName = m_bucketName;
            request.Prefix = key;
            using (ListObjectsResponse response = client.ListObjects(request))
            {

                foreach (S3Object o in response.S3Objects)
                {
                    if( o.Key == key )
                        return true;
                }
                return false;
            }
        }
    }.

Iif equivalent in C#

C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not the way it is.

If you really want IIf() in C#, you can have it:

object IIf(bool expression, object truePart, object falsePart) 
{return expression?truePart:falsePart;}

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart) 
{return expression?truePart:falsePart;}

On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If() operator that works like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

error while loading shared libraries: libncurses.so.5:

For Redhat Linux 8 try this:

sudo yum install libncurses*

How do I convert array of Objects into one Object in JavaScript?

Based on answers suggested by many authors, I created a JsPref test scenario. https://jsperf.com/array2object82364

Below are the screenshots of performance. It is a little shocking to me to see, chrome result is in contrast to firefox and edge, even after running it several times.

Edge

Firefox

Chrome

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to find all the subclasses of a class given its name?

New-style classes (i.e. subclassed from object, which is the default in Python 3) have a __subclasses__ method which returns the subclasses:

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

Here are the names of the subclasses:

print([cls.__name__ for cls in Foo.__subclasses__()])
# ['Bar', 'Baz']

Here are the subclasses themselves:

print(Foo.__subclasses__())
# [<class '__main__.Bar'>, <class '__main__.Baz'>]

Confirmation that the subclasses do indeed list Foo as their base:

for cls in Foo.__subclasses__():
    print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>

Note if you want subsubclasses, you'll have to recurse:

def all_subclasses(cls):
    return set(cls.__subclasses__()).union(
        [s for c in cls.__subclasses__() for s in all_subclasses(c)])

print(all_subclasses(Foo))
# {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}

Note that if the class definition of a subclass hasn't been executed yet - for example, if the subclass's module hasn't been imported yet - then that subclass doesn't exist yet, and __subclasses__ won't find it.


You mentioned "given its name". Since Python classes are first-class objects, you don't need to use a string with the class's name in place of the class or anything like that. You can just use the class directly, and you probably should.

If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above.

How to find the class from the name depends on where you're expecting to find it. If you're expecting to find it in the same module as the code that's trying to locate the class, then

cls = globals()[name]

would do the job, or in the unlikely case that you're expecting to find it in locals,

cls = locals()[name]

If the class could be in any module, then your name string should contain the fully-qualified name - something like 'pkg.module.Foo' instead of just 'Foo'. Use importlib to load the class's module, then retrieve the corresponding attribute:

import importlib
modname, _, clsname = name.rpartition('.')
mod = importlib.import_module(modname)
cls = getattr(mod, clsname)

However you find the class, cls.__subclasses__() would then return a list of its subclasses.

Subscript out of range error in this Excel VBA script

Private Sub CommandButton1_Click()

    Dim Data As Object, Employee As Object

    Application.ScreenUpdating = False

    Set Data = ThisWorkbook.Sheets("Data")

    Set Employee = ThisWorkbook.Sheets("Employee Names")

    Data.Range("AK1").Value = "Lookup"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"

    Application.DisplayAlerts = False

    Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)

    Data.Range("AK:AK").Delete

    Data.AutoFilterMode = False

    'Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"

    Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")

    Dr.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    'DrfeeRequested.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
    Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")

    Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
    Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")

    Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"

    Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")

    Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    TodayDT = Format(Now())

    Weekdy = Weekday(Now())

    If Weekdy = 2 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 3 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 4 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 5 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 6 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    Else
       MsgBox "Today Satuarday OR Sunday Data is not Available"
    End If

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"

    Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")

    Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"

    Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")

    Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.Range("A1").AutoFilter

   End Sub

 Private Sub CommandButton2_Click()


    Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear

    MsgBox "Please paste new data in data sheet"


End Sub

SQL Server 2000: How to exit a stored procedure?

This works over here.

ALTER PROCEDURE dbo.Archive_Session
    @SessionGUID int
AS 
    BEGIN
        SET NOCOUNT ON
        PRINT 'before raiserror'
        RAISERROR('this is a raised error', 18, 1)
        IF @@Error != 0 
            RETURN
        PRINT 'before return'
        RETURN -1
        PRINT 'after return'
    END
go

EXECUTE dbo.Archive_Session @SessionGUID = 1

Returns

before raiserror
Msg 50000, Level 18, State 1, Procedure Archive_Session, Line 7
this is a raised error

Strtotime() doesn't work with dd/mm/YYYY format

I haven't found a better solution. You can use explode(), preg_match_all(), etc.

I have a static helper function like this

class Date {

    public static function ausStrToTime($str) {
        $dateTokens = explode('/', $str);
        return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]); 

    }

}

There is probably a better name for that, but I use ausStrToTime() because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.

Developing for Android in Eclipse: R.java not regenerating

I've found that any file that has capital letters in the res folder will create this error. This happened to me with a PNG file I added and forgot about.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

Whoever still having the same issue. Please add the following line in application.properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
## I am using Mysql8 so I have declared MySQL8Dialect if you have other versions just add ## that version number
spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL8Dialect

What is the purpose of "&&" in a shell command?

See the example:

mkdir test && echo "Something" > test/file

Shell will try to create directory test and then, only if it was successfull will try create file inside it.

So you may interrupt a sequence of steps if one of them failed.

Enable binary mode while restoring a Database from an SQL dump

If you don't have enough space or don't want to waste time in decompressing it, Try this command.

gunzip < compressed-sqlfile.gz | mysql -u root -p

Don't forget to replace compressed-sqlfile.gz with your compressed file name.

.gz restore will not work without command I provided above.

When to use margin vs padding in CSS

Margin is outside the box and padding is inside the box

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you are working on Joomla! and getting this annoying error when trying to include a (.js) JavaScript file, then the following solution is for you.

The most probable problem is that you are trying to include a .js file that isn't there, or you just misplaced that .js file, and when Joomla! doesn't find a resource, then instead of the generic 404 message, it returns a full fledged 404 message with a complete webpage and html etc.

The web browser is interpreting it as .js whereas its just a webpage saying that the required file wasn't found.

This can work for

Chrome, Javascript, window.open in new tab

It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.

For example:

$("#theButton").button().click( function(event) {
   $.post( url, data )
   .always( function( response ) {
      window.open( newurl + response, '_blank' );
   } );
} );

will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:

$("#theButton").button().click( function(event) {
   var newtab = window.open( '', '_blank' );
   $.post( url, data )
   .always( function( response ) {
      newtab.location = newurl + response;
   } );
} );

we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.

How to use jQuery Plugin with Angular 4?

Install jquery with npm

npm install jquery --save

Add typings

npm install --save-dev @types/jquery

Add scripts to angular-cli.json

"apps": [{
  ...
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ],
  ...
}]

Build project and serve

ng build

Hope this helps! Enjoy coding

How can I check if a jQuery plugin is loaded?

To detect jQuery plugins I found more accurate to use the brackets:

if(jQuery().pluginName) {
    //run plugin dependent code
}

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

Which characters make a URL invalid?

Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:

First, a digression into terminology. What are these addresses? Are they valid URLs?

Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.

Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.

What characters are allowed under the WHATWG Living Standard?

Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are

URL code points and percent-encoded bytes.

What are "URL code points"?

The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.

(Note that the list of "URL code points" doesn't include %, but that %s are allowed in "URL code units" if they're part of a percent-encoding sequence.)

The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [ and ] characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.

What characters were allowed under the old RFCs?

For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.

First of all, we have two types of RFC 3986 reserved characters:

  • :/?#[]@, which are part of the generic syntax for a URI defined in RFC 3986
  • !$&'()*+,;=, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and & and = are used as part of the ubiquitous ?foo=bar&qux=baz format in query strings (which isn't specified by RFC 3986).

Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although / has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)

RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:

  • abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~

Finally, the % character itself is allowed for percent-encodings.

That leaves only the following ASCII characters that are forbidden from appearing in a URL:

  • The control characters (chars 0-1F and 7F), including new line, tab, and carriage return.
  • "<>\^`{|}

Every other character from ASCII can legally feature in a URL.

Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:

  %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD

These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.


Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [ and ] are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html is illegal.

If/else else if in Jquery for a condition

Iam confused a lot from morning whether it should be less than or greater than`

this can accept value less than "99999"

I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:

}elseif($("#seats").val() < 99999){
  alert("Not a valid Number");
}else{

You are saying if it's less than 99999, then it's not valid. You want to do the opposite:

}elseif($("#seats").val() >= 99999){
  alert("Not a valid Number");
}else{

Also, since you have $("#seats") twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:

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

var error = null;

if (seats == "") {
    error = "Number is required";
} else {
    var seatsNum = parseInt(seats);
    
    if (isNaN(seatsNum)) {
        error = "Not a valid number";
    } else if (seatsNum >= 99999) {
        error = "Number must be less than 99999";
    }
}

if (error != null) {
    alert(error);
} else {
    alert("Valid number");
}

// If you really need setflag:
var setflag = error != null;

Here's a working sample: http://jsfiddle.net/LUY8q/

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

Java Command line arguments

Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This worked for me:

git branch

Copy the current branch name to clipboard

git pull origin <paste-branch-name>
git push

Replacing a fragment with another fragment inside activity group

you can use simple code its work for transaction

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

Is there a good Valgrind substitute for Windows?

I used Insure++ which does excellent job in finding c++ memory leaks/corruptions and many other bugs like uninitialized variables, pointer errors, strings etc., It also does visual "Code coverage" and run time memory usage etc.. which give more confident on your code.. You can try it for trail version..

UITableView example for Swift

//    UITableViewCell set Identify "Cell"
//    UITableView Name is  tableReport

UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet weak var tableReport: UITableView!  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = "Report Name"
            return cell;
        }
}

angularjs: allows only numbers to be typed into a text box

This answer serves as a simplification and optimisation over Leopoldo's answer.

Trigger a function from your input on every keydown like this:

<input type="text" ng-keydown="onlyNumbers($event);"/>

You can describe the function in this manner in your controller

$scope.onlyNumbers = function(event){    
    // 'up': 38,'right':39,'down':40,'left':37,
    // 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
    // '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
                 46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
                 54:true,55:true,56:true,57:true };

    // if the pressed key is not listed, do not perform any action
    if(!keys[event.keyCode]) { event.preventDefault(); }
}

In case you're using Angular 2+, you can call this same function in this manner:

<input type="text" (keydown)="onlyNumbers($event);"/>

Your Angular 2+ function should look something like this:

onlyNumbers(event) { // the logic here }

Python element-wise tuple operations like sum

from numpy import array

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

gives array([4,4,4]).

See http://www.scipy.org/Tentative_NumPy_Tutorial

Build Error - missing required architecture i386 in file

Check your library search paths in your target settings. Sometimes goofy libraries get entered in there and this will give you a similar error.

You can remove all entries in this section.

Set selected item in Android BottomNavigationView

From API 25.3.0 it was introduced the method setSelectedItemId(int id) which lets you mark an item as selected as if it was tapped.

From docs:

Set the selected menu item ID. This behaves the same as tapping on an item.

Code example:

BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);

IMPORTANT

You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.

C# Convert a Base64 -> byte[]

This may be helpful

byte[] bytes = System.Convert.FromBase64String(stringInBase64);

java.io.IOException: Invalid Keystore format

for me that issue happened because i generated .jks file on my laptop with 1.8.0_251 and i copied it on server witch had java 1.8.0_45 and when I used that .jks file in my code i got java.io.IOException: Invalid Keystore format.

to solve this issue i generated .jks file directly on the server instead of copy there from my laptop which had different java version.

Find all stored procedures that reference a specific column in some table

You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.

SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
    ,objects.type_desc
FROM syscomments comments
    ,sys.objects objects
WHERE comments.id = objects.object_id
    AND TEXT LIKE '%CreatedDate%'
ORDER BY 1

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Getting the thread ID from a thread

The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):

public static int GetNativeThreadId(Thread thread)
{
    var f = typeof(Thread).GetField("DONT_USE_InternalThread",
        BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

    var pInternalThread = (IntPtr)f.GetValue(thread);
    var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
    return nativeId;
}

Programmatically getting the MAC of an Android device

You can get mac address:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();

Set Permission in Menifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

Get all directories within directory nodejs

functional programming

const fs = require('fs')
const path = require('path')
const R = require('ramda')

const getDirectories = pathName => {
    const isDirectory = pathName => fs.lstatSync(pathName).isDirectory()
    const mapDirectories = pathName => R.map(name => path.join(pathName, name), fs.readdirSync(pathName))
    const filterDirectories = listPaths => R.filter(isDirectory, listPaths)

    return {
        paths:R.pipe(mapDirectories)(pathName),
        pathsFiltered: R.pipe(mapDirectories, filterDirectories)(pathName)
    }
}

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

C++11, < 20ms for me - Run it here

I understand that you want tips to help improve your language specific knowledge, but since that has been well covered here, I thought I would add some context for people who may have looked at the mathematica comment on your question, etc, and wondered why this code was so much slower.

This answer is mainly to provide context to hopefully help people evaluate the code in your question / other answers more easily.

This code uses only a couple of (uglyish) optimisations, unrelated to the language used, based on:

  1. every traingle number is of the form n(n+1)/2
  2. n and n+1 are coprime
  3. the number of divisors is a multiplicative function

#include <iostream>
#include <cmath>
#include <tuple>
#include <chrono>

using namespace std;

// Calculates the divisors of an integer by determining its prime factorisation.

int get_divisors(long long n)
{
    int divisors_count = 1;

    for(long long i = 2;
        i <= sqrt(n);
        /* empty */)
    {
        int divisions = 0;
        while(n % i == 0)
        {
            n /= i;
            divisions++;
        }

        divisors_count *= (divisions + 1);

        //here, we try to iterate more efficiently by skipping
        //obvious non-primes like 4, 6, etc
        if(i == 2)
            i++;
        else
            i += 2;
    }

    if(n != 1) //n is a prime
        return divisors_count * 2;
    else
        return divisors_count;
}

long long euler12()
{
    //n and n + 1
    long long n, n_p_1;

    n = 1; n_p_1 = 2;

    // divisors_x will store either the divisors of x or x/2
    // (the later iff x is divisible by two)
    long long divisors_n = 1;
    long long divisors_n_p_1 = 2;

    for(;;)
    {
        /* This loop has been unwound, so two iterations are completed at a time
         * n and n + 1 have no prime factors in common and therefore we can
         * calculate their divisors separately
         */

        long long total_divisors;                 //the divisors of the triangle number
                                                  // n(n+1)/2

        //the first (unwound) iteration

        divisors_n_p_1 = get_divisors(n_p_1 / 2); //here n+1 is even and we

        total_divisors =
                  divisors_n
                * divisors_n_p_1;

        if(total_divisors > 1000)
            break;

        //move n and n+1 forward
        n = n_p_1;
        n_p_1 = n + 1;

        //fix the divisors
        divisors_n = divisors_n_p_1;
        divisors_n_p_1 = get_divisors(n_p_1);   //n_p_1 is now odd!

        //now the second (unwound) iteration

        total_divisors =
                  divisors_n
                * divisors_n_p_1;

        if(total_divisors > 1000)
            break;

        //move n and n+1 forward
        n = n_p_1;
        n_p_1 = n + 1;

        //fix the divisors
        divisors_n = divisors_n_p_1;
        divisors_n_p_1 = get_divisors(n_p_1 / 2);   //n_p_1 is now even!
    }

    return (n * n_p_1) / 2;
}

int main()
{
    for(int i = 0; i < 1000; i++)
    {
        using namespace std::chrono;
        auto start = high_resolution_clock::now();
        auto result = euler12();
        auto end = high_resolution_clock::now();

        double time_elapsed = duration_cast<milliseconds>(end - start).count();

        cout << result << " " << time_elapsed << '\n';
    }
    return 0;
}

That takes around 19ms on average for my desktop and 80ms for my laptop, a far cry from most of the other code I've seen here. And there are, no doubt, many optimisations still available.

Get current folder path

Use this,

var currentDirectory = System.IO.Directory.GetCurrentDirectory(); 

You can use this as well.

var currentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

Find the number of downloads for a particular app in apple appstore

Updated answer now that xyo.net has been bought and shut down.

appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

Outdated answer:

Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

xyo.net

Your project contains error(s), please fix it before running it

it can also happen if you move required files. Simply check Problems View (menu window -> show view -> Problems) as told here

Sending mass email using PHP

Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.

The developers of this app have not set up this app properly for Facebook Login?

Set LoginBehavior if you have installed facebook app in your phone

loginButton.setLoginBehavior(LoginBehavior.WEB_ONLY);

Invert match with regexp

Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').

^((?!foo).)*$

This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

Calculating distance between two points, using latitude longitude?

Here is a page with javascript examples for various spherical calculations. The very first one on the page should give you what you need.

http://www.movable-type.co.uk/scripts/latlong.html

Here is the Javascript code

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad(); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
        Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

Where 'd' will hold the distance.

How to open, read, and write from serial port in C?

I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.

You must call cfmakeraw on a tty obtained from tcgetattr. You cannot zero-out a struct termios, configure it, and then set the tty with tcsetattr. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3).

#include <errno.h>
#include <fcntl.h> 
#include <string.h>
#include <termios.h>
#include <unistd.h>

int
set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                error_message ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

void
set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                error_message ("error %d setting term attributes", errno);
}


...
char *portname = "/dev/ttyUSB1"
 ...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
        error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
        return;
}

set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);                // set no blocking

write (fd, "hello!\n", 7);           // send 7 character greeting

usleep ((7 + 25) * 100);             // sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

The values for speed are B115200, B230400, B9600, B19200, B38400, B57600, B1200, B2400, B4800, etc. The values for parity are 0 (meaning no parity), PARENB|PARODD (enable parity and use odd), PARENB (enable parity and use even), PARENB|PARODD|CMSPAR (mark parity), and PARENB|CMSPAR (space parity).

"Blocking" sets whether a read() on the port waits for the specified number of characters to arrive. Setting no blocking means that a read() returns however many characters are available without waiting for more, up to the buffer limit.


Addendum:

CMSPAR is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h enables definition of CMSPAR only if the preprocessor symbol __USE_MISC is defined. That definition occurs (in features.h) with

#if defined _BSD_SOURCE || defined _SVID_SOURCE
 #define __USE_MISC     1
#endif

The introductory comments of <features.h> says:

/* These are defined by the user (or the compiler)
   to specify the desired environment:

...
   _BSD_SOURCE          ISO C, POSIX, and 4.3BSD things.
   _SVID_SOURCE         ISO C, POSIX, and SVID things.
...
 */

SQLite: How do I save the result of a query as a CSV file?

From here and d5e5's comment:

You'll have to switch the output to csv-mode and switch to file output.

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

ComboBox SelectedItem vs SelectedValue

I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.

Here is a reference to the focus events that occur on controls:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx

jQuery How do you get an image to fade in on load?

This thread seems unnecessarily controversial.

If you really want to solve this question correctly, using jQuery, please see the solution below.

The question is "jQuery How do you get an image to fade in on load?"

First, a quick note.

This is not a good candidate for $(document).ready...

Why? Because the document is ready when the HTML DOM is loaded. The logo image will not be ready at this point - it may still be downloading in fact!

So to answer first the general question "jQuery How do you get an image to fade in on load?" - the image in this example has an id="logo" attribute:

$("#logo").bind("load", function () { $(this).fadeIn(); });

This does exactly what the question asks. When the image has loaded, it will fade in. If you change the source of the image, when the new source has loaded, it will fade in.

There is a comment about using window.onload alongside jQuery. This is perfectly possible. It works. It can be done. However, the window.onload event needs a particular bit of care. This is because if you use it more than once, you overwrite your previous events. Example (feel free to try it...).

function SaySomething(words) {
    alert(words);
}
window.onload = function () { SaySomething("Hello"); };
window.onload = function () { SaySomething("Everyone"); };
window.onload = function () { SaySomething("Oh!"); };

Of course, you wouldn't have three onload events so close together in your code. You would most likely have a script that does something onload, and then add your window.onload handler to fade in your image - "why has my slide show stopped working!!?" - because of the window.onload problem.

One great feature of jQuery is that when you bind events using jQuery, they ALL get added.

So there you have it - the question has already been marked as answered, but the answer seems to be insufficient based on all the comments. I hope this helps anyone arriving from the world's search engines!

How to write to a file in Scala?

No dependencies, with error handling

  • Uses methods from the standard library exclusively
  • Creates directories for the file, if necessary
  • Uses Either for error handling

Code

def write(destinationFile: Path, fileContent: String): Either[Exception, Path] =
  write(destinationFile, fileContent.getBytes(StandardCharsets.UTF_8))

def write(destinationFile: Path, fileContent: Array[Byte]): Either[Exception, Path] =
  try {
    Files.createDirectories(destinationFile.getParent)
    // Return the path to the destinationFile if the write is successful
    Right(Files.write(destinationFile, fileContent))
  } catch {
    case exception: Exception => Left(exception)
  }

Usage

val filePath = Paths.get("./testDir/file.txt")

write(filePath , "A test") match {
  case Right(pathToWrittenFile) => println(s"Successfully wrote to $pathToWrittenFile")
  case Left(exception) => println(s"Could not write to $filePath. Exception: $exception")
}

Named parameters in JDBC

Vanilla JDBC only supports named parameters in a CallableStatement (e.g. setString("name", name)), and even then, I suspect the underlying stored procedure implementation has to support it.

An example of how to use named parameters:

//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
        + "if @id is not null "
        + "select * from sysobjects where id = @id "
        + "else if @name is not null "
        + "select * from sysobjects where name = @name "
        + " end");
stmt.execute();

//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}


//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

Android - save/restore fragment state

Android fragment has some advantages and some disadvantages. The most disadvantage of the fragment is that when you want to use a fragment you create it ones. When you use it, onCreateView of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown. This make fragment view a bit slow and weird.

I have found a solution and I have used this solution: "Everything is great. Every body can try".

When first time onCreateView is being run, create view as a global variable. When second time you call this fragment onCreateView is called again you can return this global view. The fragment component state will be kept.

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

How to remove empty cells in UITableView?

in the below method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (([array count]*65) > [UIScreen mainScreen].bounds.size.height - 66)
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [array count]*65)); 
    }
    else
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 66);
    }
    return [array count];
}

here 65 is the height of the cell and 66 is the height of the navigation bar in UIViewController.

Displaying the Indian currency symbol on a website

Image approach is not bad either. It hardly takes 400Bytes.
Download from here http://i.stack.imgur.com/vJZ9m.png

<span class="rupee"></span>

Well i found it better than webrupee.

For colors edit the image as below

    .rupee{
    background-position:left;
    width: 10px; 
    height: 14px;
    background-image: url('rupee.png');
    display:block; 
    background-repeat: no-repeat;
}

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Upgrading from Kepler to Luna worked for me.

I had just added some components for Java 1.8 support. It seems that they where not as compatible as I would like or that I mixed the wrong ones. It really caused a lot of problems. Trying to update the system reported errors as they couldn't fulfill some dependencies. Maven upgrades didn't work. Tried a lot of things.

So, if there is no reason to avoid the upgrade just add the luna repository to avalilable software sites (Luna http://download.eclipse.org/releases/luna/ ) and "check for updates". It is better to have all the components with the same version and there are some nice new features.

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

Extracting specific selected columns to new DataFrame as a copy

If you want to have a new data frame then:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

check your pom.xml is exists

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>

I've had a problem like this;For lack this dependency

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

WebDriver: check if an element exists?

This works for me every time:

    if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
        //THEN CLICK ON THE SUBMIT BUTTON
    }else{
        //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
    }

How can I change UIButton title color?

If you are using Swift, this will do the same:

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Hope that helps!

How to resize image automatically on browser width resize but keep same height?

Make it a background image and larger than 100% to get the desired effect: http://jsfiddle.net/derekstory/hVM9v/

HTML

<div id="image"></div>

CSS

body, html {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}
#image {
    width: 100%;
    height: 500px;
    background: #000 url('http://static.ddmcdn.com/gif/dog-9.jpg') center no-repeat;
    background-size: auto 200%;
}

Difference between Activity Context and Application Context

The reason I think is that ProgressDialog is attached to the activity that props up the ProgressDialog as the dialog cannot remain after the activity gets destroyed so it needs to be passed this(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.

Expand a div to fill the remaining width

Use calc:

_x000D_
_x000D_
.leftSide {_x000D_
  float: left;_x000D_
  width: 50px;_x000D_
  background-color: green;_x000D_
}_x000D_
.rightSide {_x000D_
  float: left;_x000D_
  width: calc(100% - 50px);_x000D_
  background-color: red;_x000D_
}
_x000D_
<div style="width:200px">_x000D_
  <div class="leftSide">a</div>_x000D_
  <div class="rightSide">b</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The problem with this is that all widths must be explicitly defined, either as a value(px and em work fine), or as a percent of something explicitly defined itself.

CONVERT Image url to Base64

This is your html-

    <img id="imageid" src="">
    <canvas id="imgCanvas" />

Javascript should be-

   var can = document.getElementById("imgCanvas");
   var img = document.getElementById("imageid");
   var ctx = can.getContext("2d");
   ctx.drawImage(img, 10, 10);
   var encodedBase = can.toDataURL();

'encodedBase' Contains Base64 Encoding of Image.

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

Angular 2 - Setting selected value on dropdown list

Angular 2 simple dropdown selected value

It may help someone as I need to only show selected value, don't need to declare something in component and etc.

If your status is coming from the database then you can show selected value this way.

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

How to do SVN Update on my project using the command line

I think I got it. It's:

"SVN Client Path"  /command:update / path:"My folder path"

How to sort an associative array by its values in Javascript?

i use $.each of jquery but you can make it with a for loop, an improvement is this:

        //.ArraySort(array)
        /* Sort an array
         */
        ArraySort = function(array, sortFunc){
              var tmp = [];
              var aSorted=[];
              var oSorted={};

              for (var k in array) {
                if (array.hasOwnProperty(k)) 
                    tmp.push({key: k, value:  array[k]});
              }

              tmp.sort(function(o1, o2) {
                    return sortFunc(o1.value, o2.value);
              });                     

              if(Object.prototype.toString.call(array) === '[object Array]'){
                  $.each(tmp, function(index, value){
                      aSorted.push(value.value);
                  });
                  return aSorted;                     
              }

              if(Object.prototype.toString.call(array) === '[object Object]'){
                  $.each(tmp, function(index, value){
                      oSorted[value.key]=value.value;
                  });                     
                  return oSorted;
              }               
     };

So now you can do

    console.log("ArraySort");
    var arr1 = [4,3,6,1,2,8,5,9,9];
    var arr2 = {'a':4, 'b':3, 'c':6, 'd':1, 'e':2, 'f':8, 'g':5, 'h':9};
    var arr3 = {a: 'green', b: 'brown', c: 'blue', d: 'red'};
    var result1 = ArraySort(arr1, function(a,b){return a-b});
    var result2 = ArraySort(arr2, function(a,b){return a-b});
    var result3 = ArraySort(arr3, function(a,b){return a>b});
    console.log(result1);
    console.log(result2);       
    console.log(result3);

How do I create a round cornered UILabel on the iPhone?

You can make rounded border with width of border of any control in this way:-

CALayer * l1 = [lblName layer];
[l1 setMasksToBounds:YES];
[l1 setCornerRadius:5.0];

// You can even add a border
[l1 setBorderWidth:5.0];
[l1 setBorderColor:[[UIColor darkGrayColor] CGColor]];


Just replace lblName with your UILabel.

Note:- Don't forget to import <QuartzCore/QuartzCore.h>

Size of Matrix OpenCV

Note that apart from rows and columns there is a number of channels and type. When it is clear what type is, the channels can act as an extra dimension as in CV_8UC3 so you would address a matrix as

uchar a = M.at<Vec3b>(y, x)[i];

So the size in terms of elements of elementary type is M.rows * M.cols * M.cn

To find the max element one can use

Mat src;
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal);

Swift programmatically navigate to another view controller/scene

According to @jaiswal Rajan in his answer. You can do a pushViewController like this:

let storyBoard: UIStoryboard = UIStoryboard(name: "NewBotStoryboard", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
self.navigationController?.pushViewController(newViewController, animated: true)

Making authenticated POST requests with Spring RestTemplate for Android

Ok found the answer. exchange() is the best way. Oddly the HttpEntity class doesn't have a setBody() method (it has getBody()), but it is still possible to set the request body, via the constructor.

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("field", "value");

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);

Select last row in MySQL

Keep in mind that tables in relational databases are just sets of rows. And sets in mathematics are unordered collections. There is no first or last row; no previous row or next row.

You'll have to sort your set of unordered rows by some field first, and then you are free the iterate through the resultset in the order you defined.

Since you have an auto incrementing field, I assume you want that to be the sorting field. In that case, you may want to do the following:

SELECT    *
FROM      your_table
ORDER BY  your_auto_increment_field DESC
LIMIT     1;

See how we're first sorting the set of unordered rows by the your_auto_increment_field (or whatever you have it called) in descending order. Then we limit the resultset to just the first row with LIMIT 1.

Convert InputStream to byte array in Java

In new version,

IOUtils.readAllBytes(inputStream)

How to set Sqlite3 to be case insensitive when string comparing?

Another option is to create your own custom collation. You can then set that collation on the column or add it to your select clauses. It will be used for ordering and comparisons.

This can be used to make 'VOILA' LIKE 'voilà'.

http://www.sqlite.org/capi3ref.html#sqlite3_create_collation

The collating function must return an integer that is negative, zero, or positive if the first string is less than, equal to, or greater than the second, respectively.

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

Hiding an Excel worksheet with VBA

Just wanted to add a little more detail to the answers given. You can also use

sheet.Visible = False

to hide and

sheet.Visible = True

to unhide.

Source

What is size_t in C?

size_t is an unsigned integer data type which can assign only 0 and greater than 0 integer values. It measure bytes of any object's size and returned by sizeof operator. const is the syntax representation of size_t, but without const you can run the programm.

const size_t number;

size_t regularly used for array indexing and loop counting. If the compiler is 32-bit it would work on unsigned int. If the compiler is 64-bit it would work on unsigned long long int also. There for maximum size of size_t depending on compiler type.

size_t already define on <stdio.h> header file, but It can also define by <stddef.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> headers.

  • Example (with const)
#include <stdio.h>

int main()
{
    const size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800


  • Example (without const)
#include <stdio.h>

int main()
{
    size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800

PHP replacing special characters like à->a, è->e

Simple function. Transform strings like 'Ábç Éfg' to 'abc_efg'

/**
 * @param $str
 * @return mixed
 */
function sanitizeString($str) {
    $str = preg_replace('/[áàãâä]/ui', 'a', $str);
    $str = preg_replace('/[éèêë]/ui', 'e', $str);
    $str = preg_replace('/[íìîï]/ui', 'i', $str);
    $str = preg_replace('/[óòõôö]/ui', 'o', $str);
    $str = preg_replace('/[úùûü]/ui', 'u', $str);
    $str = preg_replace('/[ç]/ui', 'c', $str);
    $str = preg_replace('/[^a-z0-9]/i', '_', $str);
    $str = preg_replace('/_+/', '_', $str);

    return $str;
}

Check if a specific tab page is selected (active)

This can work as well.

if (tabControl.SelectedTab.Text == "tabText" )
{
    .. do stuff
}

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How to check if any value is NaN in a Pandas DataFrame

df.apply(axis=0, func=lambda x : any(pd.isnull(x)))

Will check for each column if it contains Nan or not.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

How to target only IE (any version) within a stylesheet?

Another working solution for IE specific styling is

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

And then your selector

html[data-useragent*='MSIE 10.0'] body .my-class{
        margin-left: -0.4em;
    }

Confirm deletion in modal / dialog using Twitter Bootstrap?

I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:

    bootbox.confirm("Are you sure to want to delete , function(result) {

    //here result will be true
    // delete process code goes here

    });

Offical bootboxjs site

HttpClient not supporting PostAsJsonAsync method C#

Ok, it is apocalyptical 2020 now, and you can find these methods in NuGet package System.Net.Http.Json. But beware that it uses System.Text.Json internally.

And if you really need to find out which API resides where, just use https://apisof.net/

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

unsigned int vs. size_t

size_t is the size of a pointer.

So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).

There are other models but these are the ones that g++ use (at least by default)

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Have a look at Select2 for Bootstrap. It should be able to do everything you need.

Another good option is Selectize.js. It feels a bit more native to Bootstrap.

Changing SVG image color with javascript

Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.

There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.

A simple example using SVGInject looks like this:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Java 1.7 makes our lives much easier thanks to the try-with-resources statement.

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.

send Content-Type: application/json post with node.js

For some reason only this worked for me today. All other variants ended up in bad json error from API.

Besides, yet another variant for creating required POST request with JSON payload.

_x000D_
_x000D_
request.post({_x000D_
    uri: 'https://www.googleapis.com/urlshortener/v1/url',_x000D_
    headers: {'Content-Type': 'application/json'},_x000D_
    body: JSON.stringify({"longUrl": "http://www.google.com/"})_x000D_
});
_x000D_
_x000D_
_x000D_

Access to file download dialog in Firefox

I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.

Of course this was Java, I've translated it to Python:

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf

When does System.gc() do something?

There is a LOT to be said in taking the time to test out the various garbage collection settings, but as was mentioned above it usually not useful to do so.

I am currently working on a project involving a memory-limited environment and a relatively large amounts of data--there are a few large pieces of data that push my environment to its limit, and even though I was able to bring memory usage down so that in theory it should work just fine, I would still get heap space errors---the verbose GC options showed me that it was trying to garbage collect, but to no avail. In the debugger, I could perform System.gc() and sure enough there would be "plenty" of memory available...not a lot of extra, but enough.

Consequently, The only time my application calls System.gc() is when it is about to enter the segment of code where large buffers necessary for processing the data will be allocated, and a test on the free memory available indicates that I'm not guaranteed to have it. In particular, I'm looking at a 1gb environment where at least 300mb is occupied by static data, with the bulk of the non-static data being execution-related except when the data being processed happens to be at least 100-200 MB at the source. It's all part of an automatic data conversion process, so the data all exists for relatively short periods of time in the long run.

Unfortunately, while information about the various options for tuning the garbage collector is available, it seems largely an experimental process and the lower level specifics needed to understand how to handle these specific situations are not easily obtained.

All of that being said, even though I am using System.gc(), I still continued to tune using command line parameters and managed to improve the overall processing time of my application by a relatively significant amount, despite being unable to get over the stumbling block posed by working with the larger blocks of data. That being said, System.gc() is a tool....a very unreliable tool, and if you are not careful with how you use it, you will wish that it didn't work more often than not.

Import cycle not allowed

This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)

Lets say your project go-circular-dependency have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows

+--go-circular-dependency    
      +--one    
         +-one.go
      +--two        
         +-two.go

This issue occurs when you try to do something like following.

Step 1 - In one.go you import package two (Following is one.go)

package one

import (
    "go-circular-dependency/two"
)

//AddOne is
func AddOne() int {
    a := two.Multiplier()
    return a + 1
}

Step 2 - In two.go you import package one (Following is two.go)

package two

import (
    "fmt"
    "go-circular-dependency/one"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    //import AddOne from "package one"
    x := one.AddOne()
    fmt.Println(x)
}

In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)

Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)

Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.

Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)

So in Step 2 that is in two.go you should not import package one. Instead in two.go you should actually replicate the functionality of AddOne() written in one.go as follows.

package two

import (
    "fmt"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    // x := one.AddOne()
    x := Multiplier() + 1
    fmt.Println(x)
}

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

enter image description here

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

Auto-fitting columns

Further study

How to keep a Python script output window open?

you can combine the answers before: (for Notepad++ User)

press F5 to run current script and type in command:

cmd /k python -i "$(FULL_CURRENT_PATH)"

in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)

How to do a SUM() inside a case statement in SQL server

You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.

WITH PercentageOfTotal (Id, Percentage) 
AS 
(
    SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT 
    CASE
        WHEN o.TotalType = 'Average' THEN r.avgscore
        WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
        ELSE o.cnt
    END AS [displayscore]
FROM PercentageOfTotal pt
    JOIN dbo.MyTable t ON pt.Id = t.Id

Setting a JPA timestamp column to be generated by the database?

@Column(name = "LastTouched", insertable = false, updatable = false, columnDefinition = "TIMESTAMP default getdate()")
@Temporal(TemporalType.TIMESTAMP)
private Date LastTouched;`enter code here`

CLEAR SCREEN - Oracle SQL Developer shortcut?

Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.

Run script.

Alt+PgDn     -  puts you in Script Output panel.
Ctrl+Shift+D -  clears panel.
Alt+PgUp     -  puts you back in editor panel. 

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

Read all contacts' phone numbers in android

     package com.example.readcontacts;

        import java.util.ArrayList;

        import android.app.Activity; import android.app.ProgressDialog;
        import android.content.ContentResolver; import
        android.database.Cursor; import android.net.Uri; import
        android.os.Bundle; import android.os.Handler; import
        android.provider.ContactsContract; import android.view.View; import
        android.widget.AdapterView; import
        android.widget.AdapterView.OnItemClickListener; import
        android.widget.ArrayAdapter; import android.widget.ListView; import
        android.widget.Toast;

        public class MainActivity extends Activity {    private ListView
        mListView;  private ProgressDialog pDialog;     private Handler
        updateBarHandler;

            ArrayList<String> contactList;  Cursor cursor;  int counter;    
            @Override   public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                pDialog = new ProgressDialog(this);         pDialog.setMessage("Reading
        contacts...");      pDialog.setCancelable(false);       pDialog.show();

                mListView = (ListView) findViewById(R.id.list);         updateBarHandler
        =new Handler();
                        // Since reading contacts takes more time, let's run it on a separate thread.       new Thread(new Runnable() {

                    @Override           public void run() {
                        getContacts();          }       }).start();

                // Set onclicklistener to the list item.
                mListView.setOnItemClickListener(new OnItemClickListener() {

                    @Override           public void onItemClick(AdapterView<?> parent, View
        view,
                            int position, long id) {
                        //TODO Do whatever you want with the list data
                        Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show();          }
                });     }

            public void getContacts() {


                contactList = new ArrayList<String>();

                String phoneNumber = null;      String email = null;

                Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;        String
        _ID = ContactsContract.Contacts._ID;        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;       String HAS_PHONE_NUMBER =
        ContactsContract.Contacts.HAS_PHONE_NUMBER;

                Uri PhoneCONTENT_URI =
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI;         String
        Phone_CONTACT_ID =
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID;      String NUMBER =
        ContactsContract.CommonDataKinds.Phone.NUMBER;

                Uri EmailCONTENT_URI = 
        ContactsContract.CommonDataKinds.Email.CONTENT_URI;         String
        EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
                String DATA = ContactsContract.CommonDataKinds.Email.DATA;

                StringBuffer output;

                ContentResolver contentResolver = getContentResolver();

                cursor = contentResolver.query(CONTENT_URI, null,null, null,
        null);  

                // Iterate every contact in the phone       if (cursor.getCount() > 0)
        {

                    counter = 0;            while (cursor.moveToNext()) {
                        output = new StringBuffer();

                        // Update the progress message
                        updateBarHandler.post(new Runnable() {
                            public void run() {
                                pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
                            }
                        });

                        String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
                        String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

                        int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
        HAS_PHONE_NUMBER )));

                        if (hasPhoneNumber > 0) {

                            output.append("\n First Name:" + name);

                            //This is to read multiple phone numbers associated with the same contact
                            Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                            while (phoneCursor.moveToNext()) {
                                phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                                output.append("\n Phone number:" + phoneNumber);

                            }

                            phoneCursor.close();

                            // Read every email id associated with the contact
                            Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,    null, EmailCONTACT_ID+ " =
        ?", new String[] { contact_id }, null);

                            while (emailCursor.moveToNext()) {

                                email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

                                output.append("\n Email:" + email);

                            }

                            emailCursor.close();
                        }

                        // Add the contact to the ArrayList
                        contactList.add(output.toString());             }

                    // ListView has to be updated using a ui thread
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
        R.id.text1, contactList);
                            mListView.setAdapter(adapter);          
                        }           });

                    // Dismiss the progressbar after 500 millisecondds
                    updateBarHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pDialog.cancel();               
                        }           }, 500);        }

            }

        }

List item

Angular 5 Button Submit On Enter Key Press

try use keyup.enter or keydown.enter

  <button type="submit" (keyup.enter)="search(...)">Search</button>

The name does not exist in the namespace error in XAML

When you are writing your wpf code and VS tell that "The name ABCDE does not exist in the namespace clr-namespace:ABC". But you can totally build your project successfully, there is only a small inconvenience because you can not see the UI designing (or just want to clean the code).

Try to do these:

  • In VS, right click on your Solution -> Properties -> Configuration Properties

  • A new dialog is opened, try to change the project configurations from Debug to Release or vice versa.

After that, re-build your solution. It can solve your problem.

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Bootstrap 3: Using img-circle, how to get circle from non-square image?

I see that this post is a little out of date but still... I can show you and everyone else (who is in the same situation as I was this day) how i did it.

First of all, you need html like this:

<div class="circle-avatar" style="background-image:url(http://placekitten.com/g/200/400)"></div>

Than your css class will look like this:

div.circle-avatar{
/* make it responsive */
max-width: 100%;
width:100%;
height:auto;
display:block;
/* div height to be the same as width*/
padding-top:100%;

/* make it a circle */
border-radius:50%;

/* Centering on image`s center*/
background-position-y: center;
background-position-x: center;
background-repeat: no-repeat;

/* it makes the clue thing, takes smaller dimension to fill div */
background-size: cover;

/* it is optional, for making this div centered in parent*/
margin: 0 auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

It is responsive circle, centered on original image. You can change width and height not to autofill its parent if you want. But keep them equal if you want to have a circle in result.

Link with solution on fiddle

I hope this answer will help struggling people. Bye.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: Each "child" Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: A Skill has a Set of Person(s) which relate to it.

In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).

Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.

What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!

All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

how to get the attribute value of an xml node using java

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}

Submit Button Image

<input type="image" src="path to image" name="submit" />

UPDATE:

For button states, you can use type="submit" and then add a class to it

<input type="submit" name="submit" class="states" />

Then in css, use background images for:

.states{
background-image:url(path to url);
height:...;
width:...;
}

.states:hover{
background-position:...;
}

.states:active{
background-position:...;
}

Cancel a vanilla ECMAScript 6 Promise chain

Here's our implementation https://github.com/permettez-moi-de-construire/cancellable-promise

Used like

const {
  cancellablePromise,
  CancelToken,
  CancelError
} = require('@permettezmoideconstruire/cancellable-promise')

const cancelToken = new CancelToken()

const initialPromise = SOMETHING_ASYNC()
const wrappedPromise = cancellablePromise(initialPromise, cancelToken)


// Somewhere, cancel the promise...
cancelToken.cancel()


//Then catch it
wrappedPromise
.then((res) => {
  //Actual, usual fulfill
})
.catch((err) => {
  if(err instanceOf CancelError) {
    //Handle cancel error
  }

  //Handle actual, usual error
})

which :

  • Doesn't touch Promise API
  • Let us make further cancellation inside catch call
  • Rely on cancellation being rejected instead of resolved unlike any other proposal or implementation

Pulls and comments welcome

Why I can't access remote Jupyter Notebook server?

Have you configured the jupyter_notebook_config.py file to allow external connections?

By default, Jupyter Notebook only accepts connections from localhost (eg, from the same computer that its running on). By modifying the NotebookApp.allow_origin option from the default ' ' to '*', you allow Jupyter to be accessed externally.

c.NotebookApp.allow_origin = '*' #allow all origins

You'll also need to change the IPs that the notebook will listen on:

c.NotebookApp.ip = '0.0.0.0' # listen on all IPs


Also see the details in a subsequent answer in this thread.

Documentation on the Jupyter Notebook config file.

Simple search MySQL database using php

Just with the above answer I hope it was the problem.

$_POST['search'] instead of $_post['search']

And again use LIKE '%$name%' instead of LIKE '%{$name}%'

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

How do I replace whitespaces with underscore?

You can try this instead:

mystring.replace(r' ','-')

H2 in-memory database. Table not found

I have tried adding ;DATABASE_TO_UPPER=false parameter, which it did work a single test, but what did the trick for me was ;CASE_INSENSITIVE_IDENTIFIERS=TRUE.

At the I had: jdbc:h2:mem:testdb;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Moreover, the problem for me was when I upgraded to Spring Boot 2.4.1.

How do I iterate through table rows and cells in JavaScript?

This solution worked perfectly for me

var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{    for(j = 0; j < # of columns; j++)
     {
         y = table[i].cells;
         //do something with cells in a row
         y[j].innerHTML = "";
     }
}

How can I convert uppercase letters to lowercase in Notepad++

You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

What exactly is RESTful programming?

A great book on REST is REST in Practice.

Must reads are Representational State Transfer (REST) and REST APIs must be hypertext-driven

See Martin Fowlers article the Richardson Maturity Model (RMM) for an explanation on what an RESTful service is.

Richardson Maturity Model

To be RESTful a Service needs to fulfill the Hypermedia as the Engine of Application State. (HATEOAS), that is, it needs to reach level 3 in the RMM, read the article for details or the slides from the qcon talk.

The HATEOAS constraint is an acronym for Hypermedia as the Engine of Application State. This principle is the key differentiator between a REST and most other forms of client server system.

...

A client of a RESTful application need only know a single fixed URL to access it. All future actions should be discoverable dynamically from hypermedia links included in the representations of the resources that are returned from that URL. Standardized media types are also expected to be understood by any client that might use a RESTful API. (From Wikipedia, the free encyclopedia)

REST Litmus Test for Web Frameworks is a similar maturity test for web frameworks.

Approaching pure REST: Learning to love HATEOAS is a good collection of links.

REST versus SOAP for the Public Cloud discusses the current levels of REST usage.

REST and versioning discusses Extensibility, Versioning, Evolvability, etc. through Modifiability

What is the difference between Serialization and Marshaling?

Both do one thing in common - that is serializing an Object. Serialization is used to transfer objects or to store them. But:

  • Serialization: When you serialize an object, only the member data within that object is written to the byte stream; not the code that actually implements the object.
  • Marshalling: Term Marshalling is used when we talk about passing Object to remote objects(RMI). In Marshalling Object is serialized(member data is serialized) + Codebase is attached.

So Serialization is part of Marshalling.

CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.

Angular routerLink does not navigate to the corresponding component

In my case I had line-wrapper in my VS code and, apparently, there was no space between end of closing quote belonging to [routerLink] and next attribute. Line-wrapper split this in two lines so missing space went unnoticed.

Git Bash won't run my python files?

Add following line in you .bashrc file

############################
# Environment path setting #
############################
export PATH=/c/Python27:/c/Python27/Scripts:$PATH

z-index issue with twitter bootstrap dropdown menu

I had the same problem, in my case because i forgot this in my NavBar style: overflow: hidden;

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Determine .NET Framework version for dll

"Detect It Easy" also known as DiE is a program for determining types of files. Works with .dll files or other (.exe) files. Absolute free for commercial and non-commercial use.

enter image description here

Git for beginners: The definitive practical guide

I got started with the official Git tutorial. I think it's practical enough for beginners (I was, and still am, a beginner, by your definition! I barely grasp makefiles, I've only played a bit with Apache Subversion, etc.).

jQuery table sort

If you want to avoid all the bells and whistles then may I suggest this simple sortElements plugin. Usage:

var table = $('table');

$('.sortable th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){

        var th = $(this),
            thIndex = th.index(),
            inverse = false;

        th.click(function(){

            table.find('td').filter(function(){

                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode; 

            });

            inverse = !inverse;

        });

    });

And a demo. (click the "city" and "facility" column-headers to sort)

OnItemCLickListener not working in listview

Two awesome solutions were this, if your extending ListFragment from a fragment, know that mListView.setOnItemClickListener wont be called before your activity is created, this ensured it is set when activity has been created

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long rowId) {
            // Do the onItemClick action

            Log.d("ROWSELECT", "" + rowId);
        }
    });
}

While looking at the source code for ListFragment, I came across this

public class ListFragment extends Fragment {
    ...........................................
    ................................................

    final private AdapterView.OnItemClickListener mOnClickListener
                = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            onListItemClick((ListView)parent, v, position, id);
        }
    };

    ................................................................
    ................................................................

    public void onListItemClick(ListView l, View v, int position, long id) {
    }
}

An onItemClickListener object is attached and it calls onListItemClick() As such the other similar solution, which works in the exact same way is to override onListItemClick()

@Override
public void onListItemClick(ListView l, View v, int position, long rowId) {
    super.onListItemClick(l, v, position, id);
   // Do the onItemClick action

   Log.d("ROWSELECT", "" + rowId);
} 

Get event listeners attached to node using addEventListener

You can obtain all jQuery events using $._data($('[selector]')[0],'events'); change [selector] to what you need.

There is a plugin that gather all events attached by jQuery called eventsReport.

Also i write my own plugin that do this with better formatting.

But anyway it seems we can't gather events added by addEventListener method. May be we can wrap addEventListener call to store events added after our wrap call.

It seems the best way to see events added to an element with dev tools.

But you will not see delegated events there. So there we need jQuery eventsReport.

UPDATE: NOW We CAN see events added by addEventListener method SEE RIGHT ANSWER TO THIS QUESTION.

How to split elements of a list?

Do not use list as variable name. You can take a look at the following code too:

clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]

Or in-place editing:

for i,x in enumerate(clist):
    if '\t' in x:
        clist[i] = x[:x.index('\t')]

How to dockerize maven project? and how many ways to accomplish it?

As a rule of thumb, you should build a fat JAR using Maven (a JAR that contains both your code and all dependencies).

Then you can write a Dockerfile that matches your requirements (if you can build a fat JAR you would only need a base os, like CentOS, and the JVM).

This is what I use for a Scala app (which is Java-based).

FROM centos:centos7

# Prerequisites.

RUN yum -y update
RUN yum -y install wget tar

# Oracle Java 7

WORKDIR /opt

RUN wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/7u71-b14/server-jre-7u71-linux-x64.tar.gz
RUN tar xzf server-jre-7u71-linux-x64.tar.gz
RUN rm -rf server-jre-7u71-linux-x64.tar.gz
RUN alternatives --install /usr/bin/java java /opt/jdk1.7.0_71/bin/java 1

# App

USER daemon

# This copies to local fat jar inside the image
ADD /local/path/to/packaged/app/appname.jar /app/appname.jar

# What to run when the container starts
ENTRYPOINT [ "java", "-jar", "/app/appname.jar" ]

# Ports used by the app
EXPOSE 5000

This creates a CentOS-based image with Java7. When started, it will execute your app jar.

The best way to deploy it is via the Docker Registry, it's like a Github for Docker images.

You can build an image like this:

# current dir must contain the Dockerfile
docker build -t username/projectname:tagname .

You can then push an image in this way:

docker push username/projectname # this pushes all tags

Once the image is on the Docker Registry, you can pull it from anywhere in the world and run it.

See Docker User Guide for more informations.

Something to keep in mind:

You could also pull your repository inside an image and build the jar as part of the container execution, but it's not a good approach, as the code could change and you might end up using a different version of the app without notice.

Building a fat jar removes this issue.

UnicodeDecodeError when reading CSV file in Pandas with Python

I am posting an update to this old thread. I found one solution that worked, but requires opening each file. I opened my csv file in LibreOffice, chose Save As > edit filter settings. In the drop-down menu I chose UTF8 encoding. Then I added encoding="utf-8-sig" to the data = pd.read_csv(r'C:\fullpathtofile\filename.csv', sep = ',', encoding="utf-8-sig").

Hope this helps someone.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

Visual Studio Code how to resolve merge conflicts with git?

For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.

How to hide soft keyboard on android after clicking outside EditText?

Well, You can use this code, Use your Main Layout Id instead of "mainRelativeLayout"

//hide Soft keyboard on click outside  the input text
    findViewById(R.id.mainRelativeLayout).setOnClickListener(new 
View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager im = (InputMethodManager) 
getSystemService(INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 
0);
        }

    });

What is the difference between a .cpp file and a .h file?

The C++ build system (compiler) knows no difference, so it's all one of conventions.

The convention is that .h files are declarations, and .cpp files are definitions.

That's why .h files are #included -- we include the declarations.

Reverse Singly Linked List Java

I think your problem is that your initially last element next attribute isn't being changed becuase of your condition

if(next == null)
     return;

Is at the beginning of your loop.

I would move it right after tmp.next has been assigned:

while(tmp != null){

  tmp.next = before;
  if(next == null)
     return;
  before = tmp;
  tmp = next;
  next = next.next;
}

Remove HTML tags from string including &nbsp in C#

I took @Ravi Thapliyal's code and made a method: It is simple and might not clean everything, but so far it is doing what I need it to do.

public static string ScrubHtml(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
    var step2 = Regex.Replace(step1, @"\s{2,}", " ");
    return step2;
}

How to compare strings in C conditional preprocessor-directives

If your strings are compile time constants (as in your case) you can use the following trick:

#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif

The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.

EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

How do shift operators work in Java?

System.out.println(Integer.toBinaryString(2 << 11)); 

Shifts binary 2(10) by 11 times to the left. Hence: 1000000000000

System.out.println(Integer.toBinaryString(2 << 22)); 

Shifts binary 2(10) by 22 times to the left. Hence : 100000000000000000000000

System.out.println(Integer.toBinaryString(2 << 33)); 

Now, int is of 4 bytes,hence 32 bits. So when you do shift by 33, it's equivalent to shift by 1. Hence : 100

How do I pass a string into subprocess.Popen (using the stdin argument)?

I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)

MSIE and addEventListener Problem in Javascript?

Internet Explorer (IE8 and lower) doesn't support addEventListener(...). It has its own event model using the attachEvent method. You could use some code like this:

var element = document.getElementById('container');
if (document.addEventListener){
    element .addEventListener('copy', beforeCopy, false); 
} else if (el.attachEvent){
    element .attachEvent('oncopy', beforeCopy);
}

Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.

By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.

Javascript - Append HTML to container element without innerHTML

This is what DocumentFragment was meant for.

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

What is the difference between a data flow diagram and a flow chart?

A Data Flow Diagram is functional relationship which includes input values and output values and internal data stored.

A Flow Chart is a process relationship which includes input and output values.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

Creating a generic method in C#

Convert.ChangeType() doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:

public static class Converter
{
  public static T ConvertTo<T>(object value)
  {
    return ConvertTo(value, default(T));
  }

  public static T ConvertTo<T>(object value, T defaultValue)
  {
    if (value == DBNull.Value)
    {
      return defaultValue;
    }
    return (T) ChangeType(value, typeof(T));
  }

  public static object ChangeType(object value, Type conversionType)
  {
    if (conversionType == null)
    {
      throw new ArgumentNullException("conversionType");
    }

    // if it's not a nullable type, just pass through the parameters to Convert.ChangeType
    if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
      // null input returns null output regardless of base type
      if (value == null)
      {
        return null;
      }

      // it's a nullable type, and not null, which means it can be converted to its underlying type,
      // so overwrite the passed-in conversion type with this underlying type
      conversionType = Nullable.GetUnderlyingType(conversionType);
    }
    else if (conversionType.IsEnum)
    {
      // strings require Parse method
      if (value is string)
      {
        return Enum.Parse(conversionType, (string) value);          
      }
      // primitive types can be instantiated using ToObject
      else if (value is int || value is uint || value is short || value is ushort || 
           value is byte || value is sbyte || value is long || value is ulong)
      {
        return Enum.ToObject(conversionType, value);
      }
      else
      {
        throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
                              "not supported for enum conversions.", conversionType.FullName));
      }
    }

    return Convert.ChangeType(value, conversionType);
  }
}

Then your implementation of GetQueryString<T> can be:

public static T GetQueryString<T>(string key)
{
    T result = default(T);
    string value = HttpContext.Current.Request.QueryString[key];

    if (!String.IsNullOrEmpty(value))
    {
        try
        {
            result = Converter.ConvertTo<T>(value);  
        }
        catch
        {
            //Could not convert.  Pass back default value...
            result = default(T);
        }
    }

    return result;
}

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Why do we need the "finally" clause in Python?

The code blocks are not equivalent. The finally clause will also be run if run_code1() throws an exception other than TypeError, or if run_code2() throws an exception, while other_code() in the first version wouldn't be run in these cases.

Send a SMS via intent

Uri uri = Uri.parse("smsto:YOUR_SMS_NUMBER");   
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);   
intent.putExtra("sms_body", "The SMS text");   
startActivity(intent);  

Remove duplicated rows using dplyr

Note: dplyr now contains the distinct function for this purpose.

Original answer below:


library(dplyr)
set.seed(123)
df <- data.frame(
  x = sample(0:1, 10, replace = T),
  y = sample(0:1, 10, replace = T),
  z = 1:10
)

One approach would be to group, and then only keep the first row:

df %>% group_by(x, y) %>% filter(row_number(z) == 1)

## Source: local data frame [3 x 3]
## Groups: x, y
## 
##   x y z
## 1 0 1 1
## 2 1 0 2
## 3 1 1 4

(In dplyr 0.2 you won't need the dummy z variable and will just be able to write row_number() == 1)

I've also been thinking about adding a slice() function that would work like:

df %>% group_by(x, y) %>% slice(from = 1, to = 1)

Or maybe a variation of unique() that would let you select which variables to use:

df %>% unique(x, y)

TypeScript enum to object array

_x000D_
_x000D_
enum GoalProgressMeasurements {_x000D_
    Percentage = 1,_x000D_
    Numeric_Target = 2,_x000D_
    Completed_Tasks = 3,_x000D_
    Average_Milestone_Progress = 4,_x000D_
    Not_Measured = 5_x000D_
}_x000D_
    _x000D_
const array = []_x000D_
    _x000D_
for (const [key, value] of Object.entries(GoalProgressMeasurements)) {_x000D_
    if (!Number.isNaN(Number(key))) {_x000D_
        continue;_x000D_
    }_x000D_
_x000D_
    array.push({ id: value, name: key.replace('_', '') });_x000D_
}_x000D_
_x000D_
console.log(array);
_x000D_
_x000D_
_x000D_

Get current controller in view

I have put this in my partial view:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()

in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.

So use this alert instead:

alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');

Using true and false in C

I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:

if (variable == TRUE)
{
   ...
}

instead of:

if (variable)
{
   ...
}

Confused about Service vs Factory

This is how I understood the difference between them in terms of design patterns:

Service: Return a type, that will be newed to create an object of that type. If Java analogy is used, Service returns a Java Class definition.

Factory: Returns a concrete object that can be immediately used. In Java Analogy a Factory returns a Java Object.

The part that often confuses people (including myself) is that when you inject a Service or a Factory in your code they can be used the same way, what you get in your code in both cases is a concrete object that you can immediately invoke. Which means in case of the Service, angular calls "new" on the service declaration on behalf of you. I think this is a convoluted concept.

How do I calculate square root in Python?

sqrt=x**(1/2) is doing integer division. 1/2 == 0.

So you're computing x(1/2) in the first instance, x(0) in the second.

So it's not wrong, it's the right answer to a different question.

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Tooltips with Twitter Bootstrap

The easiest way to use this is

put this in the header:

<script>
    $(function ($) {
        $("a").tooltip()
    });
</script>

and then

<a href="#" rel="tooltip" data-placement="bottom" title="My Tooltip Text">
    My link text
</a>

so with that js code if you have tag any where in your page with rel="tooltip" get the bootstrap tooltip.

good luck.

How do I declare a two dimensional array?

As far as I'm aware there is no built in php function to do this, you need to do it via a loop or via a custom method that recursively calls to something like array_fill inidcated in the answer by @Amber;

I'm assuming you mean created an empty but intialized array of arrays. For example, you want a final results like the below of a array of 3 arrays:

   $final_array = array(array(), array(), array());

This is simple to just hand code, but for an arbitrary sized array like a an array of 3 arrays of 3 arrays it starts getting complex to initialize prior to use:

     $final_array = array(array(array(), array(), array()), array(array(), array(), array()), array(array(), array(), array()));

...etc...

I get the frustration. It would be nice to have an easy way to declare an initialized array of arrays any depth to use without checking or throwing errors.

Pretty-print an entire Pandas Series / DataFrame

Using pd.options.display

This answer is a variation of the prior answer by lucidyan. It makes the code more readable by avoiding the use of set_option.

After importing pandas, as an alternative to using the context manager, set such options for displaying large dataframes:

def set_pandas_display_options() -> None:
    """Set pandas display options."""
    # Ref: https://stackoverflow.com/a/52432757/
    display = pd.options.display

    display.max_columns = 1000
    display.max_rows = 1000
    display.max_colwidth = 199
    display.width = None
    # display.precision = 2  # set as needed

set_pandas_display_options()

After this, you can use either display(df) or just df if using a notebook, otherwise print(df).

Using to_string

Pandas 0.25.3 does have DataFrame.to_string and Series.to_string methods which accept formatting options.

Using to_markdown

If what you need is markdown output, Pandas 1.0.0 has DataFrame.to_markdown and Series.to_markdown methods.

Using to_html

If what you need is HTML output, Pandas 0.25.3 does have a DataFrame.to_html method but not a Series.to_html. Note that a Series can be converted to a DataFrame.

Center image in div horizontally

text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :

div
{
    position: relative;
}
div img
{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: [-50% of your image's width];
    margin-top: [-50% of your image's height];
}

Proper way to restrict text input values (e.g. only numbers)

You can use the HTML5 input of type number

It does not accept any characters in its declaration

<input type="number" [(model)]='myvar' min=0 max=100 step=5 />

Here is an example of its usage with angular 2 [(model)]

http://www.webpackbin.com/VJNUNF0M-