Programs & Examples On #Iswitchb mode

Split string using a newline delimiter with Python

If you want to split only by newlines, you can use str.splitlines():

Example:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

With str.split() your case also works:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

However if you have spaces (or tabs) it will fail:

>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

Text File Parsing in Java

Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.

How to detect if multiple keys are pressed at once using JavaScript?

I'd try adding a keypress Event handler upon keydown. E.g:

window.onkeydown = function() {
    // evaluate key and call respective handler
    window.onkeypress = function() {
       // evaluate key and call respective handler
    }
}

window.onkeyup = function() {
    window.onkeypress = void(0) ;
}

This is just meant to illustrate a pattern; I won't go into detail here (especially not into browser specific level2+ Event registration).

Post back please whether this helps or not.

Possible to extend types in Typescript?

The keyword extends can be used for interfaces and classes only.

If you just want to declare a type that has additional properties, you can use intersection type:

type UserEvent = Event & {UserId: string}

UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.

And it's still impossible to use extend with arbitrary types - for example, it does not work if Event is a type parameter without any constraints.

A fast way to delete all rows of a datatable at once

If you are running your code against a sqlserver database then
use this command

string sqlTrunc = "TRUNCATE TABLE " + yourTableName
SqlCommand cmd = new SqlCommand(sqlTrunc, conn);
cmd.ExecuteNonQuery();

this will be the fastest method and will delete everything from your table and reset the identity counter to zero.

The TRUNCATE keyword is supported also by other RDBMS.

5 years later:
Looking back at this answer I need to add something. The answer above is good only if you are absolutely sure about the source of the value in the yourTableName variable. This means that you shouldn't get this value from your user because he can type anything and this leads to Sql Injection problems well described in this famous comic strip. Always present your user a choice between hard coded names (tables or other symbolic values) using a non editable UI.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

SELECT 
CASE WHEN LastName IS NULL THEN FirstName         
     WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName     
END AS 'FullName' 
FROM  customers GROUP BY 1`

How to set layout_gravity programmatically?

I use someting like that: (Xamarin and C# code)

  LinearLayout linLayout= new LinearLayout(this); 
    linLayout.SetGravity(GravityFlags.Center);

    TextView txtView= new TextView(this);  
     linLayout.AddView(txtView); 

the SetGravity puts my textView in the center of the layout. So SetGravity layout property refer to layout content

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

How can I delete derived data in Xcode 8?

In the Latest Xcode version 12+ Follow the below steps, I found here https://handyopinion.com/solution-failed-to-load-info-plist-from-bundle-at-path-in-xcode/

1.

enter image description here

2.

enter image description here

It will navigate to the Derived Data folder then you can remove the content of the folder.

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

How to create a data file for gnuplot?

plot "data.txt" using 1:2 with lines 

works for me. Do you actually have blank lines in your data file? That will cause an empty plot. Can you see a plot without data? Like plot x*x. If not, then your terminal might not be set up correctly.

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

How do you get the string length in a batch file?

@echo off
::   warning doesn't like * ( in mystring

setlocal enabledelayedexpansion 

set mystring=this is my string to be counted forty one

call :getsize %mystring%
echo count=%count% of "%mystring%" 

set mystring=this is my string to be counted

call :getsize %mystring%

echo count=%count% of "%mystring%" 

set mystring=this is my string
call :getsize %mystring%

echo count=%count% of "%mystring%" 
echo.
pause
goto :eof

:: Get length of mystring line ######### subroutine getsize ########

:getsize

set count=0

for /l %%n in (0,1,2000) do (

    set chars=

    set chars=!mystring:~%%n!

    if defined chars set /a count+=1
)
goto :eof

:: ############## end of subroutine getsize ########################

Get docker container id from container name

Docker image inspect ImageName\ImageId --format={{'.ConatinerConfig.Hostname'}}

How to import Swagger APIs into Postman?

With .Net Core it is now very easy:

  1. You go and find JSON URL on your swagger page:

enter image description here

  1. Click that link and copy the URL
  2. Now go to Postman and click Import:

enter image description here

  1. Select what you need and you end up with a nice collection of endpoints:

enter image description here

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

Select from table by knowing only date without time (ORACLE)

You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

Page unload event in asp.net

With AutoEventWireup which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.

In the case of Unload the method signature is:

protected void Page_Unload(object sender, EventArgs e)

For details see the MSDN article.

Android LinearLayout Gradient Background

I would check your alpha channel on your gradient colors. For me, when I was testing my code out I had the alpha channel set wrong on the colors and it did not work for me. Once I got the alpha channel set it all worked!

explicit casting from super class to subclass

As explained, it is not possible. If you want to use a method of the subclass, evaluate the possibility to add the method to the superclass (may be empty) and call from the subclasses getting the behaviour you want (subclass) thanks to polymorphism. So when you call d.method() the call will succeed withoug casting, but in case the object will be not a dog, there will not be a problem

C++: what regex library should I use?

Noone here said anything about the one that comes with C++0x. If you are using a compiler and the STL that supports C++0x you could just use that instead of having another lib in your project.

Eclipse IDE for Java - Full Dark Theme

UPDATE 2: A fork of this plugin has been merged with the main Eclipse Platform. You should find it pre-installed in the future Eclipse releases ;)


UPDATE: I released a new version, it's a little bit darker, now pretty everything that can be currently modified has been aligned to the theme colors. Have fun!

Here is a screenshot: enter image description here


if you may like, I uploaded on github a dark theme I made some months ago to avoid blinding my eyes when spending many hours on the editor.. I made it because with all the others themes some Eclipse parts remains ugly and unstyled.

You can find it here: http://guari.github.io/eclipse-ui-theme/

With my Eclipse configurations works quite ok, if you'll find some elements that remains unstyled you can submit an issue or suggest a change and I'll try to correct it if it's possible ;) (remind that currently, CSS styling support in Eclipse it's uncomplete and sometimes buggy..)

When and where to use GetType() or typeof()?

typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.

ASP.NET DateTime Picker

There is an easy, out of the box implementation: the HTML 5 input type="date" and the other date-related input types.

Okay, you can't style the controls that much and it doesn't work on every browser, but still it can be a very good option in the long term if all modern browsers support it and don't want to include heavy libraries that don't always work that good on mobile devices.

Getting individual colors from a color map in matplotlib

For completeness these are the cmap choices I encountered so far:

Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r

Why is vertical-align:text-top; not working in CSS

You can use margin-top: -50% to move the text all the way to the top of the div.

margin-top: -50%;

How to create a dynamic array of integers

Since C++11, there's a safe alternative to new[] and delete[] which is zero-overhead unlike std::vector:

std::unique_ptr<int[]> array(new int[size]);

In C++14:

auto array = std::make_unique<int[]>(size);

Both of the above rely on the same header file, #include <memory>

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

With Validation

In this example I used two controls,ddl and txtbox, have a happy coding

 asp:ScriptManager ID="script1" runat="server" /asp:ScriptManager

    asp:UpdatePanel ID="Panel1" runat="server"
       ContentTemplate

// ASP BUTTON
asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-success" OnClientClick="return Valid()" OnClick="btnSave_Click"


   /ContentTemplate    
    /asp:UpdatePanel    

  <script type="text/javascript">
        function Valid() {

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val() == 0) {
                alert("Please select YOUR TEXT");
                $("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val().length == 0) {
                alert("Please Type YOUR TEXT");
                $("ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }
            return true;
        }
</script>

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

How do I use Linq to obtain a unique list of properties from a list of objects?

When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this

 IEnumerable<T> ids = list.Select(x => x).Distinct();

How do I import a specific version of a package using go get?

From Go 1.5 there's the "vendor experiment" that helps you manage dependencies. As of Go 1.6 this is no longer an experiment. Theres also some other options on the Go wiki..

Edit: as mentioned in this answer gopkg.in is a good option for pinning github-depdencies pre-1.5.

How to make audio autoplay on chrome

Google changed their policies last month regarding auto-play inside Chrome. Please see this announcement.

They do, however, allow auto-play if you are embedding a video and it is muted. You can add the muted property and it should allow the video to start playing.

<video autoplay controls muted>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

Add a UIView above all, even the navigation bar

Dalef great solution in swift:

self.navigationController?.view.addSubview(view)

Python threading.timer - repeat function every 'n' seconds

In the interest of providing a correct answer using Timer as the OP requested, I'll improve upon swapnil jariwala's answer:

from threading import Timer


class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue: # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            self._should_continue = False # Just in case thread is running and cancel fails.
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")


def tick():
    print('ipsem lorem')

# Example Usage
t = InfiniteTimer(0.5, tick)
t.start()

In Java, how to append a string more efficiently?

Use StringBuilder class. It is more efficient at what you are trying to do.

Exception.Message vs Exception.ToString()

Converting the WHOLE Exception To a String

Calling Exception.ToString() gives you more information than just using the Exception.Message property. However, even this still leaves out lots of information, including:

  1. The Data collection property found on all exceptions.
  2. Any other custom properties added to the exception.

There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.

public static class ExceptionExtensions
{
    public static string ToDetailedString(this Exception exception) =>
        ToDetailedString(exception, ExceptionOptions.Default);

    public static string ToDetailedString(this Exception exception, ExceptionOptions options)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        } 

        var stringBuilder = new StringBuilder();

        AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);

        foreach (PropertyInfo property in exception
            .GetType()
            .GetProperties()
            .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
            .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
        {
            var value = property.GetValue(exception, null);
            if (value == null && options.OmitNullProperties)
            {
                if (options.OmitNullProperties)
                {
                    continue;
                }
                else
                {
                    value = string.Empty;
                }
            }

            AppendValue(stringBuilder, property.Name, value, options);
        }

        return stringBuilder.ToString().TrimEnd('\r', '\n');
    }

    private static void AppendCollection(
        StringBuilder stringBuilder,
        string propertyName,
        IEnumerable collection,
        ExceptionOptions options)
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} =");

            var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);

            var i = 0;
            foreach (var item in collection)
            {
                var innerPropertyName = $"[{i}]";

                if (item is Exception)
                {
                    var innerException = (Exception)item;
                    AppendException(
                        stringBuilder,
                        innerPropertyName,
                        innerException,
                        innerOptions);
                }
                else
                {
                    AppendValue(
                        stringBuilder,
                        innerPropertyName,
                        item,
                        innerOptions);
                }

                ++i;
            }
        }

    private static void AppendException(
        StringBuilder stringBuilder,
        string propertyName,
        Exception exception,
        ExceptionOptions options)
    {
        var innerExceptionString = ToDetailedString(
            exception, 
            new ExceptionOptions(options, options.CurrentIndentLevel + 1));

        stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
        stringBuilder.AppendLine(innerExceptionString);
    }

    private static string IndentString(string value, ExceptionOptions options)
    {
        return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
    }

    private static void AppendValue(
        StringBuilder stringBuilder,
        string propertyName,
        object value,
        ExceptionOptions options)
    {
        if (value is DictionaryEntry)
        {
            DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
        }
        else if (value is Exception)
        {
            var innerException = (Exception)value;
            AppendException(
                stringBuilder,
                propertyName,
                innerException,
                options);
        }
        else if (value is IEnumerable && !(value is string))
        {
            var collection = (IEnumerable)value;
            if (collection.GetEnumerator().MoveNext())
            {
                AppendCollection(
                    stringBuilder,
                    propertyName,
                    collection,
                    options);
            }
        }
        else
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
        }
    }
}

public struct ExceptionOptions
{
    public static readonly ExceptionOptions Default = new ExceptionOptions()
    {
        CurrentIndentLevel = 0,
        IndentSpaces = 4,
        OmitNullProperties = true
    };

    internal ExceptionOptions(ExceptionOptions options, int currentIndent)
    {
        this.CurrentIndentLevel = currentIndent;
        this.IndentSpaces = options.IndentSpaces;
        this.OmitNullProperties = options.OmitNullProperties;
    }

    internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }

    internal int CurrentIndentLevel { get; set; }

    public int IndentSpaces { get; set; }

    public bool OmitNullProperties { get; set; }
}

Top Tip - Logging Exceptions

Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.

Top Tip - Human Readable Stack Traces

You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.

How do I set an absolute include path in PHP?

What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;

define( 'ROOT_DIR', dirname(__FILE__) );

Then in all files, I know what the root of my project is and can do stuff like this

require_once( ROOT_DIR.'/include/functions.php' );

Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.

How can I get a value from a map?

How can I get the value from the map, which is passed as a reference to a function?

Well, you can pass it as a reference. The standard reference wrapper that is.

typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;

// use it 
void function(map_ref_t map_r)
{
    // get to the map from inside the
    // std::reference_wrapper
    // see the alternatives behind that link
    MAP & the_map = map_r;
    // take the value from the map
    // by reference
    auto & value_r = the_map["key"];
    // change it, "in place"
    value_r = "new!";
}

And the test.

    void test_ref_to_map() {

    MAP valueMap;
    valueMap["key"] = "value";
    // pass it by reference
    function(valueMap);
    // check that the value has changed
    assert( "new!" == valueMap["key"] );
}

I think this is nice and simple. Enjoy ...

What does `ValueError: cannot reindex from a duplicate axis` mean?

Simple Fix that Worked for Me

Run df.reset_index(inplace=True) before grouping.

Thank you to this github comment for the solution.

Remove inplace if you want it to return the dataframe.

Eclipse Bug: Unhandled event loop exception No more handles

I had the same problem, turned out that TeamViewer was causing this.

In your TeamViewer go to:

Extras → Options → Advanced → QuickConnect button, configure it and disable the show QuickConnect button.

java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.

Demo: jsfiddle.net/KcdpW

HTML:

<ul>
    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>
</ul>?

CSS:

ul {
    width: 10em
}
.right {
    float: right
}?

How do I remove the horizontal scrollbar in a div?

Hide Scrollbars

step 1:

go to any browser for example Google Chrome
click on keyboard ctrl+Shift+i inspect use open tools Developer

step 2:

Focused mouse on the div and change style div use try this:
 overflow: hidden; /* Hide scrollbars */

now go to add file .css in project and include file

How To Execute SSH Commands Via PHP

For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:

composer require phpseclib/phpseclib

Next, simply use it as follows:

use phpseclib\Net\SSH2;

// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
    // Login failed, do something
}

$return_value = $ssh->exec('command');

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

@Media min-width & max-width

for some iPhone you have to put your viewport like this

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, shrink-to-fit=no, user-scalable=0" />

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

Spring Boot application as a Service

Here is a script that deploys an executable jar as a systemd service.

It creates a user for the service and the .service file, and place the jar file under /var, and makes some basic lock down of privileges.

#!/bin/bash

# Argument: The jar file to deploy
APPSRCPATH=$1

# Argument: application name, no spaces please, used as folder name under /var
APPNAME=$2

# Argument: the user to use when running the application, may exist, created if not exists
APPUSER=$3

# Help text
USAGE="
Usage: sudo $0 <jar-file> <app-name> <runtime-user>
If an app with the name <app-name> already exist, it is stopped and deleted.
If the <runtime-user> does not already exist, it is created.
"

# Check that we are root
if [ ! "root" = "$(whoami)" ]; then
    echo "Must be root. Please use e.g. sudo"
    echo "$USAGE"
    exit
fi

# Check arguments
if [ "$#" -ne 3 -o ${#APPSRCPATH} = 0 -o ${#APPNAME} = 0 -o ${#APPUSER} = 0 ]; then
    echo "Incorrect number of parameters."
    echo "$USAGE"
    exit
fi

if [ ! -f $APPSRCPATH ]; then
    echo "Can't find jar file $APPSRCPATH"
    echo "$USAGE"
    exit
fi

# Infered values
APPFILENAME=$(basename $APPSRCPATH)
APPFOLDER=/var/javaapps/$APPNAME
APPDESTPATH=$APPFOLDER/$APPFILENAME

# Stop the service if it already exist and is running
systemctl stop $APPNAME >/dev/null 2>&1

# Create the app folder, deleting any previous content
rm -fr $APPFOLDER
mkdir -p $APPFOLDER

# Create the user if it does not exist
if id "$APPUSER" >/dev/null 2>&1; then
    echo "Using existing user $APPUSER"
else
    adduser --disabled-password --gecos "" $APPUSER
    echo "Created user $APPUSER"
fi

# Place app in app folder, setting owner and rights
cp $APPSRCPATH $APPDESTPATH
chown $APPUSER $APPDESTPATH
chmod 500 $APPDESTPATH
echo "Added or updated the $APPDESTPATH file"

# Create the .service file used by systemd
echo "
[Unit]
Description=$APPNAME
After=syslog.target
[Service]
User=$APPUSER
ExecStart=/usr/bin/java -jar $APPDESTPATH
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/$APPNAME.service
echo "Created the /etc/systemd/system/$APPNAME.service file"

# Reload the daemon
systemctl daemon-reload

# Start the deployed app
systemctl start $APPNAME
systemctl status $APPNAME

Example: enter image description here

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

How can I replace text with CSS?

This isn't really possible without tricks. Here is a way that works by replacing the text with an image of text.

.pvw-title{
    text-indent: -9999px;
    background-image: url(text_image.png)
}

This type of thing is typically done with JavaScript. Here is how it can be done with jQuery:

$('.pvw-title').text('new text');

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

How to set app icon for Electron / Atom Shell App

Updated package.json:

"build": {
  "appId": "com.my-website.my-app",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "icon": "./public/icons/mac/icon.icns",     <---------- set Mac Icons
    "category": "public.app-category.utilities"
  },
  "win": {
    "icon": "./public/icons/png/256x256.png" <---------- set Win Icon
  },
  "files": [
    "./build/**/*",
    "./dist/**/*",
    "./node_modules/**/*",
    "./public/**/*",       <---------- need for get access to icons
    "*.js"
  ],
  "directories": {
    "buildResources": "public" <---------- folder where placed icons
  }
},

After build application you can see icons. This solution don't show icons in developer mode. I don't setup icons in new BrowserWindow().

How to add comments into a Xaml file in WPF?

Just a tip:

In Visual Studio to comment a text, you can highlight the text you want to comment, and then use Ctrl + K followed by Ctrl + C. To uncomment, you can use Ctrl + K followed by Ctrl + U.

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

How to check if std::map contains a key without doing insert?

Potatoswatter's answer is all right, but I prefer to use find or lower_bound instead. lower_bound is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.

map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) {    // not found
    // ...
    my_map.insert(iter, make_pair(key, value));     // hinted insertion
} else {
    // ... use iter->second here
}

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

You cannot use properties that are not mapped to a database column in a Where expression. You must build the expression based on mapped properties, like:

var date = DateTime.Now.AddYears(-from);
result = result.Where(p => date >= p.DOB);
// you don't need `AsQueryable()` here because result is an `IQueryable` anyway

As a replacement for your not mapped Age property you can extract this expression into a static method like so:

public class clsProfileDate
{
    // ...
    public DateTime DOB { get; set; } // property mapped to DB table column

    public static Expression<Func<clsProfileDate, bool>> IsOlderThan(int age)
    {
        var date = DateTime.Now.AddYears(-age);
        return p => date >= p.DOB;
    }
}

And then use it this way:

result = result.Where(clsProfileDate.IsOlderThan(from));

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

Java Initialize an int array in a constructor

why not simply

public Date(){
    data = new int[]{0,0,0};
}

the reason you got the error is because int[] data = ... declares a new variable and hides the field data

however it should be noted that the contents of the array are already initialized to 0 (the default value of int)

Print PHP Call Stack

See debug_print_backtrace. I guess you can call flush afterwards if you want.

How to tag docker image with docker-compose

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This results in an image named webapp and tagged tag, built from ./dir.

https://docs.docker.com/compose/compose-file/#build

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

Using GroupBy, Count and Sum in LINQ Lambda Expressions

        var q = from b in listOfBoxes
                group b by b.Owner into g
                select new
                           {
                               Owner = g.Key,
                               Boxes = g.Count(),
                               TotalWeight = g.Sum(item => item.Weight),
                               TotalVolume = g.Sum(item => item.Volume)
                           };

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

How to test an SQL Update statement before running it?

Autocommit OFF ...

MySQL

set autocommit=0;

It sets the autommit off for the current session.

You execute your statement, see what it has changed, and then rollback if it's wrong or commit if it's what you expected !

EDIT: The benefit of using transactions instead of running select query is that you can check the resulting set easierly.

Function ereg_replace() is deprecated - How to clear this bug?

http://php.net/ereg_replace says:

Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.

Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.

AppFabric installation failed because installer MSI returned with error code : 1603

I also hit this error…

The installation msi will try to create a new task in the Windows Task scheduler to remind you to give customer feedback. This install step executes regardless of whether you do or do not click the check box to participate in customer feedback. In many corporate environments (including mine) creating new windows tasks is denied to all but domain administrators. As a result, running as a local admin is not sufficient and the entire installation fails when adding the task returns “access denied”. This shows up in the install log as a 1603.

The only workaround we could find was to manually pull all the files out of the msi, remove the “add schedule task” from the install script, and then create a new msi. After that one line change, it worked fine.

pandas get column average/mean

You can simply go for: df.describe() that will provide you with all the relevant details you need, but to find the min, max or average value of a particular column (say 'weights' in your case), use:

    df['weights'].mean(): For average value
    df['weights'].max(): For maximum value
    df['weights'].min(): For minimum value

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Check if application is installed - Android

Faster solution:

private boolean isPackageInstalled(String packagename, PackageManager packageManager) {
    try {
        packageManager.getPackageGids(packagename);
        return true;
    } catch (NameNotFoundException e) {
        return false;
    }
}

getPackageGids is less expensive from getPackageInfo, so it work faster.

Run 10000 on API 15
Exists pkg:
getPackageInfo: nanoTime = 930000000
getPackageGids: nanoTime = 350000000
Not exists pkg:
getPackageInfo: nanoTime = 420000000
getPackageGids: nanoTime = 380000000

Run 10000 on API 17
Exists pkg:
getPackageInfo: nanoTime = 2942745517
getPackageGids: nanoTime = 2443716170
Not exists pkg:
getPackageInfo: nanoTime = 2467565849
getPackageGids: nanoTime = 2479833890

Run 10000 on API 22
Exists pkg:
getPackageInfo: nanoTime = 4596551615
getPackageGids: nanoTime = 1864970154
Not exists pkg:
getPackageInfo: nanoTime = 3830033616
getPackageGids: nanoTime = 3789230769

Run 10000 on API 25
Exists pkg:
getPackageInfo: nanoTime = 3436647394
getPackageGids: nanoTime = 2876970397
Not exists pkg:
getPackageInfo: nanoTime = 3252946114
getPackageGids: nanoTime = 3117544269

Note: This will not work in some virtual spaces. They can violate the Android API and always return an array, even if there is no application with that package name.
In this case, use getPackageInfo.

Tablix: Repeat header rows on each page not working - Report Builder 3.0

I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:

  1. Under column groups select the advanced and the statics will show up
  2. Click on the static which shows up in the row groups
  3. Set KeepWithGroup to After and RepeatOnNewPage to true

Now your column headers should repeat on each page.

Mocking HttpClient in unit tests

This is an old question, but I feel the urge to extend the answers with a solution I didn't see here.
You can fake the Microsoft assemly (System.Net.Http) and then use ShinsContext during the test.

  1. In VS 2017, right click on the System.Net.Http assembly and choose "Add Fakes Assembly"
  2. Put your code in the unit test method under a ShimsContext.Create() using. This way, you can isolate the code where you are planning to fake the HttpClient.
  3. Depends on your implementation and test, I would suggest to implement all the desired acting where you call a method on the HttpClient and want to fake the returned value. Using ShimHttpClient.AllInstances will fake your implementation in all the instances created during your test. For example, if you want to fake the GetAsync() method, do the following:

    [TestMethod]
    public void FakeHttpClient()
    {
        using (ShimsContext.Create())
        {
            System.Net.Http.Fakes.ShimHttpClient.AllInstances.GetAsyncString = (c, requestUri) =>
            {
              //Return a service unavailable response
              var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
              var task = Task.FromResult(httpResponseMessage);
              return task;
            };
    
            //your implementation will use the fake method(s) automatically
            var client = new Connection(_httpClient);
            client.doSomething(); 
        }
    }
    

comparing strings in vb

I would suggest using the String.Compare method. Using that method you can also control whether to to have it perform case-sensitive comparisons or not.

Sample:

Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3

If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
    MessageBox.Show("str1 = str2 And str3 = str4")
Else
    MessageBox.Show("Else")
End If

Edit: if you want to perform a case-insensitive search you can use the StringComparison parameter:

If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

We were having the same issues on our jenkins slaves (linux machine) and tried all the options above.

The only thing helped is setting the argument

chrome_options.add_argument('--headless')

But when we investigated further, noticed that XVFB screen doesn't started property and thats causing this error. After we fix XVFB screen, it resolved the issue.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

Background blur with CSS

There is a simple and very common technique by using 2 background images: a crisp and a blurry one. You set the crisp image as a background for the body and the blurry one as a background image for your container. The blurry image must be set to fixed positioning and the alignment is 100% perfect. I used it before and it works.

body {
    background: url(yourCrispImage.jpg) no-repeat;
}

#container {
    background: url(yourBlurryImage.jpg) no-repeat fixed;
}

You can see a working example at the following fiddle: http://jsfiddle.net/jTUjT/5/. Try to resize the browser and see that the alignment never fails.


If only CSS element() was supported by other browsers other than Mozilla's -moz-element() you could create great effects. See this demo with Mozilla.

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

CSS Background image not loading

for me following line is working for me , I put it in the css of my body ( where image is in same folder in which my css and .html files ) :

background: url('test.jpg');

Other thing that you must care about is , be careful about image extension , be sure that your image has .jpeg or .jpg extension. Thanks

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If none of the answers worked for you. You might be in the wrong "Window". I was in "Package explorer" and switching to "Project Explorer" showed me the folders.

How do I properly clean up Excel interop objects?

You can actually release your Excel Application object cleanly, but you do have to take care.

The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via Marshal.FinalReleaseComObject() is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a for each loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.

The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call GC.Collect() and then GC.WaitForPendingFinalizers() to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference.

You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.

For example, assuming that you had a Range object variable named xlRng, a Worksheet variable named xlSheet, a Workbook variable named xlBook and an Excel Application variable named xlApp, then your cleanup code could look something like the following:

// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);

xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);

In most code examples you'll see for cleaning up COM objects from .NET, the GC.Collect() and GC.WaitForPendingFinalizers() calls are made TWICE as in:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the next garbage collection. However, if you are not using VSTO, you should be able to call GC.Collect() and GC.WaitForPendingFinalizers() just once.

I know that explicitly calling GC.Collect() is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling GC.Collect().

This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)

I have a tutorial on this here:

Automating Office Programs with VB.Net / COM Interop

It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.

Form/JavaScript not working on IE 11 with error DOM7011

This error occurred for me when using window.location.reload(). Replacing with window.location = window.location.href solved the problem.

How to "pretty" format JSON output in Ruby on Rails

The <pre> tag in HTML, used with JSON.pretty_generate, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this:

<% if @data.present? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

sscanf in Python

There is an ActiveState recipe which implements a basic scanf http://code.activestate.com/recipes/502213-simple-scanf-implementation/

Getting command-line password input in Python

Updating on the answer of @Ahmed ALaa

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.

PreparedStatement setNull(..)

preparedStatement.setNull(index, java.sql.Types.NULL);

that should work for any type. Though in some cases failure happens on the server-side, like: for SQL:

COALESCE(?, CURRENT_TIMESTAMP)

Oracle 18XE fails with the wrong type: expected DATE, got STRING -- that is a perfectly valid failure;

Bottom line: it is good to know the type if you call .setNull()

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

How to set image to UIImage

Try this code to 100% work....

UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view  addSubview:imageview];

How to check if a variable is an integer in JavaScript?

you can also try it this way

var data = 22;
if (Number.isInteger(data)) {
    console.log("integer");
 }else{
     console.log("not an integer");
 }

or

if (data === parseInt(data, 10)){
    console.log("integer");
}else{
    console.log("not an integer");
}

What is Scala's yield?

val aList = List( 1,2,3,4,5 )

val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.filter(_ > 3).map(_ + 1)

println( res3 )
println( res4 )

These two pieces of code are equivalent.

val res3 = for (al <- aList) yield al + 1 > 3
val res4 = aList.map( _+ 1 > 3 )

println( res3 ) 
println( res4 )

These two pieces of code are also equivalent.

Map is as flexible as yield and vice-versa.

UIButton: set image for selected-highlighted state

You can do this in Interface Builder.

Select the UIButton you wish to set in IB then go to the attributes inspector.

In the screen shots,I am using a custom button type , but that does not matter.

Custom Default

enter image description here

enter image description here

Eclipse does not start when I run the exe?

did not have to uninstall Java JDK - just ran installer over my existing install. Not sure what was wrong but this fixed my issue with Eclipse not starting.

Custom CSS Scrollbar for Firefox

May I offer an alternative?

No scripting whatsoever, only standardized css styles and a little bit of creativity. Short answer - masking parts of the existing browser scrollbar, which means you retain all of it's functionality.

.scroll_content {
    position: relative;
    width: 400px;
    height: 414px;
    top: -17px;
    padding: 20px 10px 20px 10px;
    overflow-y: auto;
}

For demo and a little bit more in-depth explanation, check here...

jsfiddle.net/aj7bxtjz/1/

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

C++ Best way to get integer division and remainder

You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

Google Android USB Driver and ADB

Answer 1 worked perfectly for me. I tested it on a new MID 10' tablet. Here are the lines I added in the .inf file and it installed without a problem:

;Google MID
%SingleAdbInterface%        = USB_INSTALL, USB\Vid_18d1&Pid_0003&MI_01
%CompositeAdbInterface%     = USB_INSTALL, USB\Vid_18d1&Pid_0003&Rev_0230&MI_01 

Change SVN repository URL

Grepping the URL before and after might give you some peace of mind:

svn info | grep URL

  URL: svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
  Relative URL: (...doesn't matter...)

And checking on your version (to be >1.7) to ensure, svn relocate is the right thing to use:

svn --version

Lastly, adding to the above, if your repository url change also involves a change of protocol you might need to state the before and after url (also see here)

svn relocate svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
    https://svngate.mycompany.org/svn/repos/trunk/DataPortal

All in one single line of course.Thereafter, get the good feeling, that all went smoothly:

svn info | grep URL:

If you feel like it, a bit more of self-assurance, the new svn repo URL is connected and working:

svn status --show-updates
svn diff

Where does Anaconda Python install on Windows?

C:\Users\<Username>\AppData\Local\Continuum\anaconda2

For me this was the default installation directory on Windows 7. Found it via Rusy's answer

How do I set the visibility of a text box in SSRS using an expression?

I tried the example that you have provided and the only difference is that you have True and False values switched as @bdparrish had pointed out. Here is a working example of making an SSRS Texbox visible or hidden based on the number of rows present in a dataset. This example uses SSRS 2008 R2.

Step-by-step process: SSRS 2008 R2

  1. In this example, the report has a dataset named Items and has textbox to show row counts. It also has another textbox which will be visible only if the dataset Items has rows.

  2. Right-click on the textbox that should be visible/hidden based on an expression and select Text Box Properties.... Refer screenshot #1.

  3. On the Text Box Properties dialog, click on Visibility from the left section. Refer screenshot #2.

  4. Select Show or hide based on an epxression.

  5. Click on the expression button fx.

  6. Enter the expression =IIf(CountRows("Items") = 0 , True, False). Note that this expression is to hide the Textbox (Hidden).

  7. Click OK twice to close the dialogs.

  8. Screenshot #3 shows data in the SQL Server table dbo.Items, which is the source for the report data set Items. The table contains 3 rows. Screenshot #4 shows the sample report execution against the data.

  9. Screenshot #5 shows data in the SQL Server table dbo.Items, which is the source for the report data set Items. The table contains no data. Screenshot #6 shows the sample report execution against the data.

Hope that helps.

Screenshot #1:

1

Screenshot #2:

2

Screenshot #3:

3

Screenshot #4:

4

Screenshot #5:

5

Screenshot #6:

6

SQLite3 database or disk is full / the database disk image is malformed

I use the following script for repairing malformed sqlite files:

#!/bin/bash

cat <( sqlite3 "$1" .dump | grep "^ROLLBACK" -v ) <( echo "COMMIT;" ) | sqlite3 "fix_$1"

Most of the time when a sqlite database is malformed it is still possible to make a dump. This dump is basically a lot of SQL statements that rebuild the database.

Some rows might be missing from the dump (probably becasue they are corrupted). If this is the case the INSERT statements of the missing rows will be replaced with some comments and the script will end with a ROLLBACK TRANSACTION.

So what we do here is we make the dump (malformed rows are excluded) and we replace the ROLLBACK with a COMMIT so that the entire dump script will be committed in stead of rolled back.

This method saved my life a couple of 100 times already \o/

How can I insert a line break into a <Text> component in React Native?

You can try using like this

<text>{`${val}\n`}</text>

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

  • The @@identity function returns the last identity created in the same session.
  • The scope_identity() function returns the last identity created in the same session and the same scope.
  • The ident_current(name) returns the last identity created for a specific table or view in any session.
  • The identity() function is not used to get an identity, it's used to create an identity in a select...into query.

The session is the database connection. The scope is the current query or the current stored procedure.

A situation where the scope_identity() and the @@identity functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity() function will return the identity created by the query, while the @@identity function will return the identity created by the trigger.

So, normally you would use the scope_identity() function.

Permanently hide Navigation Bar in an activity

After watching the DevBytes video (by Roman Nurik) and reading the very last line in the docs, which says:

Note: If you like the auto-hiding behavior of IMMERSIVE_STICKY but need to show your own UI controls as well, just use IMMERSIVE combined with Handler.postDelayed() or something similar to re-enter immersive mode after a few seconds.

the answer, radu122 gave, worked for me. Just setup a handler and your will be good to go.

Here is the code which works for me:

@Override
protected void onResume() {
    super.onResume();
    executeDelayed();
}


private void executeDelayed() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // execute after 500ms
            hideNavBar();
        }
    }, 500);
}


private void hideNavBar() {
    if (Build.VERSION.SDK_INT >= 19) {
        View v = getWindow().getDecorView();
        v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

Google says "after a few seconds" - but I want to provide this functionality as soon as possible. Maybe I will change the value later, if I have to, I will update this answer.

How to upload files to server using JSP/Servlet?

you can upload file using jsp /servlet.

<form action="UploadFileServlet" method="post">
  <input type="text" name="description" />
  <input type="file" name="file" />
  <input type="submit" />
</form>

on the other hand server side. use following code.

     package com.abc..servlet;

import java.io.File;
---------
--------


/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.sendRedirect("../jsp/ErrorPage.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

            PrintWriter out = response.getWriter();
            HttpSession httpSession = request.getSession();
            String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

            String path1 =  filePathUpload;
            String filename = null;
            File path = null;
            FileItem item=null;


            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String FieldName = "";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                         item = (FileItem) iterator.next();

                            if (fieldname.equals("description")) {
                                description = item.getString();
                            }
                        }
                        if (!item.isFormField()) {
                            filename = item.getName();
                            path = new File(path1 + File.separator);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            /* START OF CODE FRO PRIVILEDGE*/

                            File uploadedFile = new File(path + Filename);  // for copy file
                            item.write(uploadedFile);
                            }
                        } else {
                            f1 = item.getName();
                        }

                    } // END OF WHILE 
                    response.sendRedirect("welcome.jsp");
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }   
    }

}

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Adding an external directory to Tomcat classpath

You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there

export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR

Merging two images with PHP

Question is about merging two images, however in this specified case you shouldn't do that. You should put Content Image (ie. cover) into <img /> tag, and Style Image into CSS, why?

  1. As I said the cover belongs to the content of the document, while that vinyl record and shadow are just a part of the page styles.
  2. Such separation is much more convenient to use. User can easily copy that image. It's easier to index by web-spiders.
  3. Finally, it's much easier to maintain.

So use a very simple code:

<div class="cover">
   <img src="/content/images/covers/movin-mountains.png" alt="Moving mountains by Pneuma" width="100" height="100" />
</div>

.cover {
    padding: 10px;
    padding-right: 100px;

    background: url(/style/images/cover-background.png) no-repeat;
}

How to add an image to the emulator gallery in android studio?

I went through the Android Device Monitor

  1. Click on device
  2. Select Android Device Monitor's File Explorer tab
  3. Select Pictures folder (path: data -> media -> 0 -> Pictures)
  4. Click "Push folders on to device" icon
  5. Select pic from computer and ok.

On linux SUSE or RedHat, how do I load Python 2.7

You have to leave Python 2.4 installed on RHEL/Centos; otherwise, tools start breaking. You can do a dual-install, though; I talk about this here:

http://thebuild.com/blog/2009/10/17/wordpress-to-djangopostgresql-part-3-installing-apache-python-2-6-psycopg2-and-mod_wsgi/

The post is about 2.6, but applies equally to 2.7.

MySQL vs MySQLi when using PHP

MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.

Android TextView Text not getting wrapped

The only correct answer to this question is that you need to set the parents to a proper width (in this case FILL_PARENT, WRAP_CONTENT) and use android:layout_weight=1 for the textview that needs to be wrapped.

SingleLine is on by default so that won't make any changes.

A width set to 0px will work but is not a good solution.

Some example (in a tableview this time), using xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">
    <TableLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:stretchColumns="*"
        android:id="@+id/tableLayout1">
        <TableRow android:id="@+id/tableRow1" android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <TextView android:text="test1" android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:layout_weight="0" />
            <TextView android:layout_weight="1"
                android:text="test2 very long text that needs to be wrapped properly using layout_weight property and ignoring singleline since that is set by default..."
                android:layout_width="fill_parent" android:layout_height="wrap_content" />
        </TableRow>     
    </TableLayout>
</LinearLayout>

If you want to set this in code you're looking for the layout_weight as a third parameter as in this example where it is set to 1:

row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
TextView label = new TextView(getApplicationContext());
label.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, 1f));

Swift how to sort array of custom objects by property value

Nearly everyone gives how directly, let me show the evolvement:

you can use the instance methods of Array:

// general form of closure
images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })

// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })

// Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })

// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
images.sortInPlace({ $0.fileID > $1.fileID })

// the simplification of the closure is the same
images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
images = images.sort({ $0.fileID > $1.fileID })

For elaborate explanation about the working principle of sort, see The Sorted Function.

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

Read file from resources folder in Spring Boot

Very short answer: you are looking for your property in the scope of a particular class loader instead of you target class. This should work:

File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

Also, see this:

P.S. there can be an issue if the project has been compiled on one machine and after that has been launched on another or you run your app in Docker. In this case, paths to your resource folder can be invalid. In this case it would be better to determine paths to your resources at runtime:

ClassPathResource res = new ClassPathResource("jsonschema.json");    
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);

Update from 2020

On top of that if you want to read resource file as a String in your tests, for example, you can use these static utils methods:

public static String getResourceFileAsString(String fileName) {
    InputStream is = getResourceFileAsInputStream(fileName);
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        return (String)reader.lines().collect(Collectors.joining(System.lineSeparator()));
    } else {
        throw new RuntimeException("resource not found");
    }
}

public static InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classLoader = {CurrentClass}.class.getClassLoader();
    return classLoader.getResourceAsStream(fileName);
}

Example of usage:

String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");

Html.RenderPartial() syntax with Razor

If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.

How to Validate Google reCaptcha on Form Submit

var googleResponse = $('#g-recaptcha-response').val();

if(googleResponse=='')
{   
    $("#texterr").html("<span>Please check reCaptcha to continue.</span>");

    return false;
}

Escape quotes in JavaScript

This is how I do it, basically str.replace(/[\""]/g, '\\"').

_x000D_
_x000D_
var display = document.getElementById('output');_x000D_
var str = 'class="whatever-foo__input" id="node-key"';_x000D_
display.innerHTML = str.replace(/[\""]/g, '\\"');_x000D_
_x000D_
//will return class=\"whatever-foo__input\" id=\"node-key\"
_x000D_
<span id="output"></span>
_x000D_
_x000D_
_x000D_

Error: "Could Not Find Installable ISAM"

Have you checked this http://support.microsoft.com/kb/209805? In particular, whether you have Msrd3x40.dll.

You may also like to check that you have the latest version of Jet: http://support.microsoft.com/kb/239114

How do I disable form resizing for users?

I always use this:

// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;

This way you can always resize the form from Designer without changing code.

Convert SVG to image (JPEG, PNG, etc.) in the browser

jbeard4 solution worked beautifully.

I'm using Raphael SketchPad to create an SVG. Link to the files in step 1.

For a Save button (id of svg is "editor", id of canvas is "canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});

How to return a dictionary | Python

I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.

**Note have used Python 2.7 so some minor modification might be required for Python 3+

class a:
    global d
    d={}
    def get_config(self,x):
        if x=='GENESYS':
            d['host'] = 'host name'
            d['port'] = '15222'
        return d

Calling get_config method using class instance in a separate python file:

from constant import a
class b:
    a().get_config('GENESYS')
    print a().get_config('GENESYS').get('host')
    print a().get_config('GENESYS').get('port')

SSIS how to set connection string dynamically from a config file

Some options:

  1. You can use the Execute Package Utility to change your datasource, before running the package.

  2. You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.

  3. You can use the SSIS XML package configuration file. Here is a walk through.

  4. You can save your configrations in a database table.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

For anyone using MySQL:

If you head into your PHPMYADMIN webpage and navigate to the table that has the foreign key you want to update, all you have to do is click the Relational view located in the Structure tab and change the On delete select menu option to Cascade.

Image shown below:

enter image description here

Return content with IHttpActionResult for non-OK response

Simple:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Your message"));

Remember to reference System.Net.Http and System.Net.

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

Best HTML5 markup for sidebar

The ASIDE has since been modified to include secondary content as well.

HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/

Excerpt:

With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).

How to AUTO_INCREMENT in db2?

You're looking for is called an IDENTITY column:

create table student (
   sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
  ,sname varchar(30)
  ,PRIMARY KEY (sid)
);

A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.

Encoding URL query parameters in Java

java.net.URLEncoder.encode(String s, String encoding) can help too. It follows the HTML form encoding application/x-www-form-urlencoded.

URLEncoder.encode(query, "UTF-8");

On the other hand, Percent-encoding (also known as URL encoding) encodes space with %20. Colon is a reserved character, so : will still remain a colon, after encoding.

Django - makemigrations - No changes detected

I solved that problem by doing this:

  1. Erase the "db.sqlite3" file. The issue here is that your current data base will be erased, so you will have to remake it again.
  2. Inside the migrations folder of your edited app, erase the last updated file. Remember that the first created file is: "0001_initial.py". For example: I made a new class and register it by the "makemigrations" and "migrate" procedure, now a new file called "0002_auto_etc.py" was created; erase it.
  3. Go to the "pycache" folder (inside the migrations folder) and erase the file "0002_auto_etc.pyc".
  4. Finally, go to the console and use "python manage.py makemigrations" and "python manage.py migrate".

How to truncate string using SQL server

You can use

LEFT(column, length)

or

SUBSTRING(column, start index, length)

Dynamically access object property using variable

ES5 // Check Deeply Nested Variables

This simple piece of code can check for deeply nested variable / value existence without having to check each variable along the way...

var getValue = function( s, context ){
    return Function.call( context || null, 'return ' + s )();
}

Ex. - a deeply nested array of objects:

a = [ 
    {
      b : [
          {
             a : 1,
             b : [
                 {
                    c : 1,
                    d : 2   // we want to check for this
                 }
             ]
           }
      ]
    } 
]

Instead of :

if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 )  // true

We can now :

if( getValue('a[0].b[0].b[0].d') == 2 ) // true

Cheers!

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

How do I "Add Existing Item" an entire directory structure in Visual Studio?

What worked for me was to drag the folder into Visual Studio, then right click the folder and select "Open Folder in File Explorer". Then select all and drag them into the folder in Visual Studio.

How to pass a list from Python, by Jinja2 to JavaScript

Make some invisible HTML tags like <label>, <p>, <input> etc. and name its id, and the class name is a pattern so that you can retrieve it later.

Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.

_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_

Now you can retrieve the data in javascript using some javascript operation like below -

_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
 _x000D_
for (var i = 0; i < total_len; i++) {_x000D_
    var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
    var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
    _x000D_
    //Do what you need to do with tm1 and tm2._x000D_
    _x000D_
    console.log(tm1);_x000D_
    console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

Classes vs. Modules in VB.NET

Modules are by no means deprecated and are used heavily in the VB language. It's the only way for instance to implement an extension method in VB.Net.

There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.

Here's a quick example that I use a lot when writing VB code that interops with raw COM interfaces.

Module Interop
  Public Function Succeeded(ByVal hr as Integer) As Boolean
    ...
  End Function

  Public Function Failed(ByVal hr As Integer) As Boolean
    ...
  End Function
End Module

Class SomeClass
  Sub Foo()
    Dim hr = CallSomeHrMethod()
    if Succeeded(hr) then
      ..
    End If
  End Sub
End Class

htaccess "order" Deny, Allow, Deny

As Gerben suggested, just change:

order deny,allow
deny from all

to

order allow,deny

And the restrictions will work as you want them to.

Details can be found in Apache's docs.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

Of course, if you create a queue don't forget to dispatch_release if you're targeting an iOS version before 6.0.

How do you set the title color for the new Toolbar?

Here is my solution if you need to change only color of title and not color of text in search widget.

layout/toolbar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:background="@color/toolbar_bg"
    app:theme="@style/AppTheme.Toolbar"
    app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"/>

values/themes.xml

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item>
    </style>

    <style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
        <!-- Customize color of navigation drawer icon and back arrow --> 
        <item name="colorControlNormal">@color/toolbar_icon</item>
    </style>

    <style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <!-- Set proper title size -->
        <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
        <!-- Set title color -->
        <item name="android:textColor">@color/toolbar_title</item>
    </style>
</resources>

In the similar way, you can set also subtitleTextAppearance.

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

Equivalent of LIMIT for DB2

You should also consider the OPTIMIZE FOR n ROWS clause. More details on all of this in the DB2 LUW documentation in the Guidelines for restricting SELECT statements topic:

  • The OPTIMIZE FOR clause declares the intent to retrieve only a subset of the result or to give priority to retrieving only the first few rows. The optimizer can then choose access plans that minimize the response time for retrieving the first few rows.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

How to convert a string to a date in sybase

102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'

Clear dropdownlist with JQuery

How about storing the new options in a variable, and then using .html(variable) to replace the data in the container?

How to get current working directory using vba?

Use these codes and enjoy it.

Public Function GetDirectoryName(ByVal source As String) As String()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection

Dim source_file() As String
Dim i As Integer        

queue.Add fso.GetFolder(source) 'obviously replace

Do While queue.Count > 0
    Set oFolder = queue(1)
    queue.Remove 1 'dequeue
    '...insert any folder processing code here...
    For Each oSubfolder In oFolder.SubFolders
        queue.Add oSubfolder 'enqueue
    Next oSubfolder
    For Each oFile In oFolder.Files
        '...insert any file processing code here...
        'Debug.Print oFile
        i = i + 1
        ReDim Preserve source_file(i)
        source_file(i) = oFile
    Next oFile
Loop
GetDirectoryName = source_file
End Function

And here you can call function:

Sub test()
Dim s
For Each s In GetDirectoryName("C:\New folder")
Debug.Print s
Next
End Sub

How can I get the current page name in WordPress?

You can get the current page, post, or custom post type with the global variable $post:

echo $post->post_title

Note: In a function or class you'll need to specify global $post; prior to trying to use $post.

If you have loops on your page, make sure you end each loop with wp_reset_postdata(); to set $post back to the default item being displayed (the page).

Note, the 'post_title' variable is also available for any custom loop / query... including menu items and media attachments... everything in WordPress is a 'post'.

Count unique values in a column in Excel

Here's an elegant array formula (which I found here http://www.excel-easy.com/examples/count-unique-values.html) that does the trick nicely:

Type

=SUM(1/COUNTIF(List,List))

and confirm with CTRL-SHIFT-ENTER

How to calculate Date difference in Hive

datediff(to_date(String timestamp), to_date(String timestamp))

For example:

SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;

How do I URl encode something in Node.js?

You can use JavaScript's encodeURIComponent:

encodeURIComponent('select * from table where i()')

giving

'select%20*%20from%20table%20where%20i()'

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

Short rot13 function - Python

from string import maketrans, lowercase, uppercase

def rot13(message):
   lower = maketrans(lowercase, lowercase[13:] + lowercase[:13])
   upper = maketrans(uppercase, uppercase[13:] + uppercase[:13])
   return message.translate(lower).translate(upper)

Use Toast inside Fragment

Making a Toast inside Fragment

 Toast.makeText(getActivity(), "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

    Activity activityObj = this.getActivity();

    Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();

Project has no default.properties file! Edit the project properties to set one

When importing to Eclipse project, I accidentally did:

BAD: Import... >> General >> Existing Proejcts into Workspace

when I should have done instead:

GOOD: Import... >> Android >> Existing Android Code Into Workspace

Removing the project imported with first method, and then re-importing it with the second method solved the problem for me.

(Others have written similar answers but I didn't get it until the explicit comparison.)

How to check a radio button with jQuery?

Use prop() mehtod

enter image description here

Source Link

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

how to change onclick event with jquery?

$('#id').attr('onclick', 'function()');

Right now (11 Jul 2015) this solution is still working (jquery 2.1.4); in my opinion, it is the best one to pick up.

Aligning a float:left div to center?

CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.

This works fine in all newer browsers:

_x000D_
_x000D_
#container {_x000D_
  display:         flex;_x000D_
  flex-wrap:       wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
  width:              150px;_x000D_
  height:             150px;_x000D_
  background-color:   #cccccc;_x000D_
  margin:             10px;        _x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="block">1</div>    _x000D_
  <div class="block">2</div>    _x000D_
  <div class="block">3</div>    _x000D_
  <div class="block">4</div>    _x000D_
  <div class="block">5</div>        _x000D_
</div>
_x000D_
_x000D_
_x000D_

Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.

"Uncaught TypeError: Illegal invocation" in Chrome

When you execute a method (i.e. function assigned to an object), inside it you can use this variable to refer to this object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
_x000D_
_x000D_

If you assign a method from one object to another, its this variable refers to the new object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
  someProperty: false,_x000D_
  someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
_x000D_
_x000D_

The same thing happens when you assign requestAnimationFrame method of window to another object. Native functions, such as this, has build-in protection from executing it in other context.

There is a Function.prototype.call() function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({}) gives TypeError: Illegal invocation. However, alert.call(window) works fine, because now alert is executed in its original scope.

If you use .call() with your object like that:

support.animationFrame.call(window, function() {});

it works fine, because requestAnimationFrame is executed in scope of window instead of your object.

However, using .call() every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind(). It has similar effect to .call(), but instead of calling the function, it creates a new function which will always be called in specified context. For example:

_x000D_
_x000D_
window.someProperty = true;_x000D_
var obj = {_x000D_
  someProperty: false,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
_x000D_
_x000D_

The only downside of Function.prototype.bind() is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.

As you probably already figured out, you can use .bind() to always execute requestAnimationFrame in context of window. Your code could look like this:

var support = {
    animationFrame: (window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame).bind(window)
};

Then you can simply use support.animationFrame(function() {});.

Ant error when trying to build file, can't find tools.jar?

Using suggestions from answers on this page and this other one (ANT_HOME is set incorrectly or ant could not be located), the ultimate fix was the following:

  1. Adding a ANT_HOME environment variable that points to the ROOT directory of your Apache ant directory location. (Not the bin sub-dir!)

  2. Adding a JAVA_HOME environment variable that points to the ROOT directory of your Java JDK (or SDK) directory location. (NOT your JRE and not the bin sub-dir!)

  3. Appended %ANT_HOME%\bin;%JAVA_HOME%\bin to the PATH environment variable.

  4. Make sure you close any command window(s) that were open prior to the changes above. Only command windows opened after the changes will have the updated environment variables.

Validating URL in Java

You need to create both a URL object and a URLConnection object. The following code will test both the format of the URL and whether a connection can be established:

try {
    URL url = new URL("http://www.yoursite.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Chrome since ~Sep/Oct 2014 makes fonts subject to the same CORS checks as Firefox has done https://code.google.com/p/chromium/issues/detail?id=286681. There is a discussion on this in https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/blink-dev/TT9D5-Zfnzw

Given that for fonts the browser may do a preflight check, then your S3 policy needs the cors request header as well. You can check your page in say Safari (which at present doesn't do CORS checking for fonts) and Firefox (that does) to double check this is the problem described.

See Stack overflow answer on Amazon S3 CORS (Cross-Origin Resource Sharing) and Firefox cross-domain font loading for the Amazon S3 CORS details.

NB in general because this used to apply to Firefox only, so it may help to search for Firefox rather than Chrome.

Java Try Catch Finally blocks without Catch

Java versions before version 7 allow for these three combinations of try-catch-finally...

try - catch
try - catch - finally
try - finally

finally block will be always executed no matter of what's going on in the try or/and catch block. so if there is no catch block, the exception won't be handled here.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

  • Java try block must be followed by either catch or finally block.
  • For each try block there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

If you compile with optimizations enabled, then many variables will be removed; for example:

SomeType value = GetValue();
DoSomething(value);

here the local variable value would typically get removed, keeping the value on the stack instead - a bit like as if you had written:

DoSomething(GetValue());

Also, if a return value isn't used at all, then it will be dropped via "pop" (rather than stored in a local via "stloc", and again; the local will not exist).

Because of this, in such a build the debugger can't get the current value of value because it doesn't exist - it only exists for the brief instant between GetValue() and DoSomething(...).

So; if you want to debug... don't use a release build! or at least, disable optimizations while you debug.

PHP parse/syntax errors; and how to solve them

unexpected ':', expecting ',' or ')'

If attempting to use PHP 8's new named parameter functionality in a version of PHP < 8 this error will occur:

$table->string(column:'Name');

Solutions:

  1. Upgrade your version of PHP tp PHP 8.8.0 or higher
  2. Do not use named parameters (pass the parameters in in the order they are expected)

How can I disable a button on a jQuery UI dialog?

You could do this to disable the first button for example:

$('.ui-dialog-buttonpane button:first').attr('disabled', 'disabled');

Find all paths between two graph nodes

The following functions (modified BFS with a recursive path-finding function between two nodes) will do the job for an acyclic graph:

from collections import defaultdict

# modified BFS
def find_all_parents(G, s):
    Q = [s]
    parents = defaultdict(set)
    while len(Q) != 0:
        v = Q[0]
        Q.pop(0)
        for w in G.get(v, []):
            parents[w].add(v)
            Q.append(w) 
    return parents

# recursive path-finding function (assumes that there exists a path in G from a to b)   
def find_all_paths(parents, a, b): 
    return [a] if a == b else [y + b for x in list(parents[b]) for y in find_all_paths(parents, a, x)]

For example, with the following graph (DAG) G given by

G = {'A':['B','C'], 'B':['D'], 'C':['D', 'F'], 'D':['E', 'F'], 'E':['F']}

if we want to find all paths between the nodes 'A' and 'F' (using the above-defined functions as find_all_paths(find_all_parents(G, 'A'), 'A', 'F')), it will return the following paths:

enter image description here

Expanding tuples into arguments

Take a look at the Python tutorial section 4.7.3 and 4.7.4. It talks about passing tuples as arguments.

I would also consider using named parameters (and passing a dictionary) instead of using a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters.

PDO closing connection

According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

Fastest way to convert Image to Byte array

public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

JavaScript override methods

the method modify() that you called in the last is called in global context if you want to override modify() you first have to inherit A or B.

Maybe you're trying to do this:

In this case C inherits A

function A() {
    this.modify = function() {
        alert("in A");
    }
}

function B() {
    this.modify = function() {
        alert("in B");
    }
}

C = function() {
    this.modify = function() {
        alert("in C");
    };

    C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}

C.prototype = new A();

How do I set up a simple delegate to communicate between two view controllers?

This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.

First you need to declare a protocol:

Let's call it MyFirstControllerDelegate.h

@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end

Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate

#import "MyFirstControllerDelegate.h"

@interface FirstController : UIViewController<MyFirstControllerDelegate>
{

}

@end

In the implementation file, you need to implement both functions of protocol:

@implementation FirstController 


    - (void) FunctionOne: (MyDataOne*) dataOne
      {
          //Put your finction code here
      }
    - (void) FunctionTwo: (MyDatatwo*) dataTwo
      {
          //Put your finction code here
      }

     //Call below function from your code
    -(void) CreateSecondController
     {
             SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
           //..... push second controller into navigation stack 
            mySecondController.delegate = self ;
            [mySecondController release];
     }

@end

in your SecondController:

@interface SecondController:<UIViewController>
{
   id <MyFirstControllerDelegate> delegate;
}

@property (nonatomic,assign)  id <MyFirstControllerDelegate> delegate;

@end

In the implementation file of SecondController.

@implementation SecondController

@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
   [delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
   [delegate FunctionTwo:myDataSecond];
}

@end

Here is the wiki article on delegate.

Tomcat Servlet: Error 404 - The requested resource is not available

My problem was in web.xml file. In one <servlet-mapping> there was an error inside <url-pattern>: I forgot to add / before url.

jQuery UI DatePicker to show month year only

Marked answer work!! but Not in my case there's more then one datepicker and only want to implement on particular datepicker

So I use instance of dp and find datepicker Div and add hide class

Here's Code

<style>
    .hide-day-calender .ui-datepicker-calendar{
        display:none;
    }
</style>

<script>
        $('#dpMonthYear').datepicker({ 
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function (dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            },
            beforeShow: function (elem,dp) {
                $(dp.dpDiv).addClass('hide-day-calender'); //here a change
            }
        });
</script>

Note: You can not target .ui-datepicker-calendar and set css, because it will constantly rendering while selection/changes

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In the case where the problem is that System.loadLibrary cannot find the DLL in question, one common misconception (reinforced by Java's error message) is that the system property java.library.path is the answer. If you set the system property java.library.path to the directory where your DLL is located, then System.loadLibrary will indeed find your DLL. However, if your DLL in turn depends on other DLLs, as is often the case, then java.library.path cannot help, because the loading of the dependent DLLs is managed entirely by the operating system, which knows nothing of java.library.path. Thus, it is almost always better to bypass java.library.path and simply add your DLL's directory to LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (MacOS), or Path (Windows) prior to starting the JVM.

(Note: I am using the term "DLL" in the generic sense of DLL or shared library.)

SQL: set existing column as Primary Key in MySQL

alter table table_name
add constraint myprimarykey primary key(column);

reference : http://www.w3schools.com/sql/sql_primarykey.asp

How to post pictures to instagram using API

Update:

Instagram are now banning accounts and removing the images based on this method. Please use with caution.


It seems that everyone who has answered this question with something along the lines of it can't be done is somewhat correct. Officially, you cannot post a photo to Instagram with their API. However, if you reverse engineer the API, you can.

function SendRequest($url, $post, $post_data, $user_agent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://i.instagram.com/api/v1/'.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');            
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    }

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

   return array($http, $response);
}

function GenerateGuid() {
     return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(16384, 20479), 
            mt_rand(32768, 49151), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535));
}

function GenerateUserAgent() {  
     $resolutions = array('720x1280', '320x480', '480x800', '1024x768', '1280x720', '768x1024', '480x320');
     $versions = array('GT-N7000', 'SM-N9000', 'GT-I9220', 'GT-I9100');
     $dpis = array('120', '160', '320', '240');

     $ver = $versions[array_rand($versions)];
     $dpi = $dpis[array_rand($dpis)];
     $res = $resolutions[array_rand($resolutions)];

     return 'Instagram 4.'.mt_rand(1,2).'.'.mt_rand(0,2).' Android ('.mt_rand(10,11).'/'.mt_rand(1,3).'.'.mt_rand(3,5).'.'.mt_rand(0,5).'; '.$dpi.'; '.$res.'; samsung; '.$ver.'; '.$ver.'; smdkc210; en_US)';
 }

function GenerateSignature($data) {
     return hash_hmac('sha256', $data, 'b4a23f5e39b5929e0666ac5de94c89d1618a2916');
}

function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $post_data = array('device_timestamp' => time(), 
                        'photo' => '@'.$filename);
        return $post_data;
    }
}


// Set the username and password of the account that you wish to post a photo to
$username = 'ig_username';
$password = 'ig_password';

// Set the path to the file that you wish to post.
// This must be jpeg format and it must be a perfect square
$filename = 'pictures/test.jpg';

// Set the caption for the photo
$caption = "Test caption";

// Define the user agent
$agent = GenerateUserAgent();

// Define the GuID
$guid = GenerateGuid();

// Set the devide ID
$device_id = "android-".$guid;

/* LOG IN */
// You must be logged in to the account that you wish to post a photo too
// Set all of the parameters in the string, and then sign it with their API key using SHA-256
$data ='{"device_id":"'.$device_id.'","guid":"'.$guid.'","username":"'.$username.'","password":"'.$password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = GenerateSignature($data);
$data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';
$login = SendRequest('accounts/login/', true, $data, $agent, false);

if(strpos($login[1], "Sorry, an error occurred while processing this request.")) {
    echo "Request failed, there's a chance that this proxy/ip is blocked";
} else {            
    if(empty($login[1])) {
        echo "Empty response received from the server while trying to login";
    } else {            
        // Decode the array that is returned
        $obj = @json_decode($login[1], true);

        if(empty($obj)) {
            echo "Could not decode the response: ".$body;
        } else {
            // Post the picture
            $data = GetPostData($filename);
            $post = SendRequest('media/upload/', true, $data, $agent, true);    

            if(empty($post[1])) {
                 echo "Empty response received from the server while trying to post the image";
            } else {
                // Decode the response 
                $obj = @json_decode($post[1], true);

                if(empty($obj)) {
                    echo "Could not decode the response";
                } else {
                    $status = $obj['status'];

                    if($status == 'ok') {
                        // Remove and line breaks from the caption
                        $caption = preg_replace("/\r|\n/", "", $caption);

                        $media_id = $obj['media_id'];
                        $device_id = "android-".$guid;
                        $data = '{"device_id":"'.$device_id.'","guid":"'.$guid.'","media_id":"'.$media_id.'","caption":"'.trim($caption).'","device_timestamp":"'.time().'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
                        $sig = GenerateSignature($data);
                        $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';

                       // Now, configure the photo
                       $conf = SendRequest('media/configure/', true, $new_data, $agent, true);

                       if(empty($conf[1])) {
                           echo "Empty response received from the server while trying to configure the image";
                       } else {
                           if(strpos($conf[1], "login_required")) {
                                echo "You are not logged in. There's a chance that the account is banned";
                            } else {
                                $obj = @json_decode($conf[1], true);
                                $status = $obj['status'];

                                if($status != 'fail') {
                                    echo "Success";
                                } else {
                                    echo 'Fail';
                                }
                            }
                        }
                    } else {
                        echo "Status isn't okay";
                    }
                }
            }
        }
    }
}

Just copy and paste the code above in your text editor, change the few variables accordingly and VOILA! I wrote an article about this and I've done it many times. See a demo here.

How to get the current date without the time?

I think you need separately date parts like (day, Month, Year)

DateTime today = DateTime.Today;

Will not work for your case. You can get date separately so you don't need variable today to be as a DateTimeType, so lets just give today variable int Type because the day is only int. So today is 10 March 2020 then the result of

int today = DateTime.Today.Day;

int month = DateTime.Today.Month;

int year = DateTime.Today.Year;

MessageBox.Show(today.ToString()+ " - this is day. "+month.ToString()+ " - this is month. " + year.ToString() + " - this is year");

would be "10 - this is day. 3 - this is month. 2020 - this is year"

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

How to remove anaconda from windows completely?

Anaconda comes with an uninstaller, which should have been installed in the Start menu.

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

Instantiate and Present a viewController in Swift

Swift 5

let vc = self.storyboard!.instantiateViewController(withIdentifier: "CVIdentifier")
self.present(vc, animated: true, completion: nil)

How do I remove a substring from the end of a string in Python?

For urls (as it seems to be a part of the topic by the given example), one can do something like this:

import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)

#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)

Both will output: ('http://www.stackoverflow', '.com')

This can also be combined with str.endswith(suffix) if you need to just split ".com", or anything specific.

Stretch and scale a CSS image in the background - with CSS only

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

MongoDB Show all contents from all collections

var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}

I think this script might get what you want. It prints the name of each collection and then prints its elements in json.

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

Angular and Typescript: Can't find names - Error: cannot find name

I was able to fix this by installing the typings module.

npm install -g typings
typings install

(Using ng 2.0.0-rc.1)

How can I "reset" an Arduino board?

If you still have the serial console open, it will reserve the serial port. Close it, and try again.

How to replace a character by a newline in Vim

\r can do the work here for you.

Use sed to replace all backslashes with forward slashes

sed can perform text transformations on input stream from a file or from a pipeline. Example:

echo 'C:\foo\bar.xml' | sed 's/\\/\//g'

gets

C:/foo/bar.xml

How can a Javascript object refer to values in itself?

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

Getting checkbox values on submit

It's very simple.

The checkbox field is like an input text. If you don't write anything in the field, it will say the field doesn't exist.

<form method="post">
    <input type="checkbox" name="check">This is how it works!<br>
    <button type="submit" name="submit">Submit</button>
</form>
<?php
if(isset($_POST['submit'])) {
    if(!isset($_POST['check'])) {
        echo "Not selected!";
    }else{
        echo "Selected!";
    }
}
?>