Programs & Examples On #Uart

A Universal Asynchronous Receiver/Transmitter (UART) is used for serial communications over a computer or peripheral device serial port.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

What is the difference between baud rate and bit rate?

Bit per second is what is means - rate of data transmission of ones and zeros per second are used.This is called bit per second(bit/s. However, it should not be confused with bytes per second, abbreviated as bytes/s, Bps, or B/s.

Raw throughput values are normally given in bits per second, but many software applications report transfer rates in bytes per second.

So, the standard unit for bit throughput is the bit per second, which is commonly abbreviated bit/s, bps, or b/s.

Baud is a unit of measure of changes , or transitions , that occurs in a signal in each second.

For example if the signal changes from one value to a zero value(or vice versa) one hundred times per second, that is a rate of 100 baud.

The other one measures data(the throughput of channel), and the other ones measures transitions(called signalling rates).

For example if you look at modern modems they use advanced modulation techniques that encoded more than one bit of data into each transition.

Thanks.

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
    {
        return IsNetworkAvailable(0);
    }

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
                continue;

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)
                continue;

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
                continue;

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
                continue;

            return true;
        }
        return false;
    }

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I got the same error

Could not connect to the Magento WebService API: SOAP-ERROR: Parsing WSDL: Couldn't load from 'example.com/api/soap/?wsdl' : failed to load external entity "example.com/api/soap/?wsdl"

and my issue resolved once I update my Magento Root URL to

example.com/index.php/api/soap/?wsdl

Yes, I was missing index.php that causes the error.

In Maven how to exclude resources from the generated jar?

When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.

Properties files from where? Your main jar? Dependencies?

In the former case, putting resources under src/test/resources as suggested is probably the most straight forward and simplest option.

In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude in the unpackOptions.

Maven2: Best practice for Enterprise Project (EAR file)

This is a good example of the maven-ear-plugin part.

You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is

maven-archetype-j2ee-simple

How to clear the entire array?

Only use Redim statement

 Dim aFirstArray() As Variant

Redim aFirstArray(nRows,nColumns)

converting a base 64 string to an image and saving it

I would suggest via Bitmap:

public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

Can I edit an iPad's host file?

Best Answer: Simply add http or https in your browser, the IP address, colon and port number. Example: https://123.23.145.67:80

How to get a password from a shell script without echoing

First of all, if anyone is going to store any password in a file, I would make sure it's hashed. It's not the best security, but at least it will not be in plain text.

  1. First, create the password and hash it:

    echo "password123" | md5sum  | cut -d '-' -f 1 > /tmp/secret
    
  2. Now, create your program to use the hash. In this case, this little program receives user input for a password without echoing, and then converts it to hash to be compared with the stored hash. If it matches the stored hash, then access is granted:

    #!/bin/bash
    
    PASSWORD_FILE="/tmp/secret"
    MD5_HASH=$(cat /tmp/secret)
    PASSWORD_WRONG=1
    
    
    while [ $PASSWORD_WRONG -eq 1 ]
     do
        echo "Enter your password:"
        read -s ENTERED_PASSWORD
        if [ "$MD5_HASH" != "$(echo $ENTERED_PASSWORD | md5sum | cut -d '-' -f 1)" ]; then
            echo "Access Deniend: Incorrenct password!. Try again"
        else
            echo "Access Granted"
            PASSWORD_WRONG=0
        fi
    done
    

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

How to preview selected image in input type="file" in popup using jQuery?

Demo

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

jQuery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Reference

Best way to check function arguments?

In this elongated answer, we implement a Python 3.x-specific type checking decorator based on PEP 484-style type hints in less than 275 lines of pure-Python (most of which is explanatory docstrings and comments) – heavily optimized for industrial-strength real-world use complete with a py.test-driven test suite exercising all possible edge cases.

Feast on the unexpected awesome of bear typing:

>>> @beartype
... def spirit_bear(kermode: str, gitgaata: (str, int)) -> tuple:
...     return (kermode, gitgaata, "Moksgm'ol", 'Ursus americanus kermodei')
>>> spirit_bear(0xdeadbeef, 'People of the Cane')
AssertionError: parameter kermode=0xdeadbeef not of <class "str">

As this example suggests, bear typing explicitly supports type checking of parameters and return values annotated as either simple types or tuples of such types. Golly!

O.K., that's actually unimpressive. @beartype resembles every other Python 3.x-specific type checking decorator based on PEP 484-style type hints in less than 275 lines of pure-Python. So what's the rub, bub?

Pure Bruteforce Hardcore Efficiency

Bear typing is dramatically more efficient in both space and time than all existing implementations of type checking in Python to the best of my limited domain knowledge. (More on that later.)

Efficiency usually doesn't matter in Python, however. If it did, you wouldn't be using Python. Does type checking actually deviate from the well-established norm of avoiding premature optimization in Python? Yes. Yes, it does.

Consider profiling, which adds unavoidable overhead to each profiled metric of interest (e.g., function calls, lines). To ensure accurate results, this overhead is mitigated by leveraging optimized C extensions (e.g., the _lsprof C extension leveraged by the cProfile module) rather than unoptimized pure-Python (e.g., the profile module). Efficiency really does matter when profiling.

Type checking is no different. Type checking adds overhead to each function call type checked by your application – ideally, all of them. To prevent well-meaning (but sadly small-minded) coworkers from removing the type checking you silently added after last Friday's caffeine-addled allnighter to your geriatric legacy Django web app, type checking must be fast. So fast that no one notices it's there when you add it without telling anyone. I do this all the time! Stop reading this if you are a coworker.

If even ludicrous speed isn't enough for your gluttonous application, however, bear typing may be globally disabled by enabling Python optimizations (e.g., by passing the -O option to the Python interpreter):

$ python3 -O
# This succeeds only when type checking is optimized away. See above!
>>> spirit_bear(0xdeadbeef, 'People of the Cane')
(0xdeadbeef, 'People of the Cane', "Moksgm'ol", 'Ursus americanus kermodei')

Just because. Welcome to bear typing.

What The...? Why "bear"? You're a Neckbeard, Right?

Bear typing is bare-metal type checking – that is, type checking as close to the manual approach of type checking in Python as feasible. Bear typing is intended to impose no performance penalties, compatibility constraints, or third-party dependencies (over and above that imposed by the manual approach, anyway). Bear typing may be seamlessly integrated into existing codebases and test suites without modification.

Everyone's probably familiar with the manual approach. You manually assert each parameter passed to and/or return value returned from every function in your codebase. What boilerplate could be simpler or more banal? We've all seen it a hundred times a googleplex times, and vomited a little in our mouths everytime we did. Repetition gets old fast. DRY, yo.

Get your vomit bags ready. For brevity, let's assume a simplified easy_spirit_bear() function accepting only a single str parameter. Here's what the manual approach looks like:

def easy_spirit_bear(kermode: str) -> str:
    assert isinstance(kermode, str), 'easy_spirit_bear() parameter kermode={} not of <class "str">'.format(kermode)
    return_value = (kermode, "Moksgm'ol", 'Ursus americanus kermodei')
    assert isinstance(return_value, str), 'easy_spirit_bear() return value {} not of <class "str">'.format(return_value)
    return return_value

Python 101, right? Many of us passed that class.

Bear typing extracts the type checking manually performed by the above approach into a dynamically defined wrapper function automatically performing the same checks – with the added benefit of raising granular TypeError rather than ambiguous AssertionError exceptions. Here's what the automated approach looks like:

def easy_spirit_bear_wrapper(*args, __beartype_func=easy_spirit_bear, **kwargs):
    if not (
        isinstance(args[0], __beartype_func.__annotations__['kermode'])
        if 0 < len(args) else
        isinstance(kwargs['kermode'], __beartype_func.__annotations__['kermode'])
        if 'kermode' in kwargs else True):
            raise TypeError(
                'easy_spirit_bear() parameter kermode={} not of {!r}'.format(
                args[0] if 0 < len(args) else kwargs['kermode'],
                __beartype_func.__annotations__['kermode']))

    return_value = __beartype_func(*args, **kwargs)

    if not isinstance(return_value, __beartype_func.__annotations__['return']):
        raise TypeError(
            'easy_spirit_bear() return value {} not of {!r}'.format(
                return_value, __beartype_func.__annotations__['return']))

    return return_value

It's long-winded. But it's also basically* as fast as the manual approach. * Squinting suggested.

Note the complete lack of function inspection or iteration in the wrapper function, which contains a similar number of tests as the original function – albeit with the additional (maybe negligible) costs of testing whether and how the parameters to be type checked are passed to the current function call. You can't win every battle.

Can such wrapper functions actually be reliably generated to type check arbitrary functions in less than 275 lines of pure Python? Snake Plisskin says, "True story. Got a smoke?"

And, yes. I may have a neckbeard.

No, Srsly. Why "bear"?

Bear beats duck. Duck may fly, but bear may throw salmon at duck. In Canada, nature can surprise you.

Next question.

What's So Hot about Bears, Anyway?

Existing solutions do not perform bare-metal type checking – at least, none I've grepped across. They all iteratively reinspect the signature of the type-checked function on each function call. While negligible for a single call, reinspection overhead is usually non-negligible when aggregated over all calls. Really, really non-negligible.

It's not simply efficiency concerns, however. Existing solutions also often fail to account for common edge cases. This includes most if not all toy decorators provided as stackoverflow answers here and elsewhere. Classic failures include:

  • Failing to type check keyword arguments and/or return values (e.g., sweeneyrod's @checkargs decorator).
  • Failing to support tuples (i.e., unions) of types accepted by the isinstance() builtin.
  • Failing to propagate the name, docstring, and other identifying metadata from the original function onto the wrapper function.
  • Failing to supply at least a semblance of unit tests. (Kind of critical.)
  • Raising generic AssertionError exceptions rather than specific TypeError exceptions on failed type checks. For granularity and sanity, type checking should never raise generic exceptions.

Bear typing succeeds where non-bears fail. All one, all bear!

Bear Typing Unbared

Bear typing shifts the space and time costs of inspecting function signatures from function call time to function definition time – that is, from the wrapper function returned by the @beartype decorator into the decorator itself. Since the decorator is only called once per function definition, this optimization yields glee for all.

Bear typing is an attempt to have your type checking cake and eat it, too. To do so, @beartype:

  1. Inspects the signature and annotations of the original function.
  2. Dynamically constructs the body of the wrapper function type checking the original function. Thaaat's right. Python code generating Python code.
  3. Dynamically declares this wrapper function via the exec() builtin.
  4. Returns this wrapper function.

Shall we? Let's dive into the deep end.

# If the active Python interpreter is *NOT* optimized (e.g., option "-O" was
# *NOT* passed to this interpreter), enable type checking.
if __debug__:
    import inspect
    from functools import wraps
    from inspect import Parameter, Signature

    def beartype(func: callable) -> callable:
        '''
        Decorate the passed **callable** (e.g., function, method) to validate
        both all annotated parameters passed to this callable _and_ the
        annotated value returned by this callable if any.

        This decorator performs rudimentary type checking based on Python 3.x
        function annotations, as officially documented by PEP 484 ("Type
        Hints"). While PEP 484 supports arbitrarily complex type composition,
        this decorator requires _all_ parameter and return value annotations to
        be either:

        * Classes (e.g., `int`, `OrderedDict`).
        * Tuples of classes (e.g., `(int, OrderedDict)`).

        If optimizations are enabled by the active Python interpreter (e.g., due
        to option `-O` passed to this interpreter), this decorator is a noop.

        Raises
        ----------
        NameError
            If any parameter has the reserved name `__beartype_func`.
        TypeError
            If either:
            * Any parameter or return value annotation is neither:
              * A type.
              * A tuple of types.
            * The kind of any parameter is unrecognized. This should _never_
              happen, assuming no significant changes to Python semantics.
        '''

        # Raw string of Python statements comprising the body of this wrapper,
        # including (in order):
        #
        # * A "@wraps" decorator propagating the name, docstring, and other
        #   identifying metadata of the original function to this wrapper.
        # * A private "__beartype_func" parameter initialized to this function.
        #   In theory, the "func" parameter passed to this decorator should be
        #   accessible as a closure-style local in this wrapper. For unknown
        #   reasons (presumably, a subtle bug in the exec() builtin), this is
        #   not the case. Instead, a closure-style local must be simulated by
        #   passing the "func" parameter to this function at function
        #   definition time as the default value of an arbitrary parameter. To
        #   ensure this default is *NOT* overwritten by a function accepting a
        #   parameter of the same name, this edge case is tested for below.
        # * Assert statements type checking parameters passed to this callable.
        # * A call to this callable.
        # * An assert statement type checking the value returned by this
        #   callable.
        #
        # While there exist numerous alternatives (e.g., appending to a list or
        # bytearray before joining the elements of that iterable into a string),
        # these alternatives are either slower (as in the case of a list, due to
        # the high up-front cost of list construction) or substantially more
        # cumbersome (as in the case of a bytearray). Since string concatenation
        # is heavily optimized by the official CPython interpreter, the simplest
        # approach is (curiously) the most ideal.
        func_body = '''
@wraps(__beartype_func)
def func_beartyped(*args, __beartype_func=__beartype_func, **kwargs):
'''

        # "inspect.Signature" instance encapsulating this callable's signature.
        func_sig = inspect.signature(func)

        # Human-readable name of this function for use in exceptions.
        func_name = func.__name__ + '()'

        # For the name of each parameter passed to this callable and the
        # "inspect.Parameter" instance encapsulating this parameter (in the
        # passed order)...
        for func_arg_index, func_arg in enumerate(func_sig.parameters.values()):
            # If this callable redefines a parameter initialized to a default
            # value by this wrapper, raise an exception. Permitting this
            # unlikely edge case would permit unsuspecting users to
            # "accidentally" override these defaults.
            if func_arg.name == '__beartype_func':
                raise NameError(
                    'Parameter {} reserved for use by @beartype.'.format(
                        func_arg.name))

            # If this parameter is both annotated and non-ignorable for purposes
            # of type checking, type check this parameter.
            if (func_arg.annotation is not Parameter.empty and
                func_arg.kind not in _PARAMETER_KIND_IGNORED):
                # Validate this annotation.
                _check_type_annotation(
                    annotation=func_arg.annotation,
                    label='{} parameter {} type'.format(
                        func_name, func_arg.name))

                # String evaluating to this parameter's annotated type.
                func_arg_type_expr = (
                    '__beartype_func.__annotations__[{!r}]'.format(
                        func_arg.name))

                # String evaluating to this parameter's current value when
                # passed as a keyword.
                func_arg_value_key_expr = 'kwargs[{!r}]'.format(func_arg.name)

                # If this parameter is keyword-only, type check this parameter
                # only by lookup in the variadic "**kwargs" dictionary.
                if func_arg.kind is Parameter.KEYWORD_ONLY:
                    func_body += '''
    if {arg_name!r} in kwargs and not isinstance(
        {arg_value_key_expr}, {arg_type_expr}):
        raise TypeError(
            '{func_name} keyword-only parameter '
            '{arg_name}={{}} not a {{!r}}'.format(
                {arg_value_key_expr}, {arg_type_expr}))
'''.format(
                        func_name=func_name,
                        arg_name=func_arg.name,
                        arg_type_expr=func_arg_type_expr,
                        arg_value_key_expr=func_arg_value_key_expr,
                    )
                # Else, this parameter may be passed either positionally or as
                # a keyword. Type check this parameter both by lookup in the
                # variadic "**kwargs" dictionary *AND* by index into the
                # variadic "*args" tuple.
                else:
                    # String evaluating to this parameter's current value when
                    # passed positionally.
                    func_arg_value_pos_expr = 'args[{!r}]'.format(
                        func_arg_index)

                    func_body += '''
    if not (
        isinstance({arg_value_pos_expr}, {arg_type_expr})
        if {arg_index} < len(args) else
        isinstance({arg_value_key_expr}, {arg_type_expr})
        if {arg_name!r} in kwargs else True):
            raise TypeError(
                '{func_name} parameter {arg_name}={{}} not of {{!r}}'.format(
                {arg_value_pos_expr} if {arg_index} < len(args) else {arg_value_key_expr},
                {arg_type_expr}))
'''.format(
                    func_name=func_name,
                    arg_name=func_arg.name,
                    arg_index=func_arg_index,
                    arg_type_expr=func_arg_type_expr,
                    arg_value_key_expr=func_arg_value_key_expr,
                    arg_value_pos_expr=func_arg_value_pos_expr,
                )

        # If this callable's return value is both annotated and non-ignorable
        # for purposes of type checking, type check this value.
        if func_sig.return_annotation not in _RETURN_ANNOTATION_IGNORED:
            # Validate this annotation.
            _check_type_annotation(
                annotation=func_sig.return_annotation,
                label='{} return type'.format(func_name))

            # Strings evaluating to this parameter's annotated type and
            # currently passed value, as above.
            func_return_type_expr = (
                "__beartype_func.__annotations__['return']")

            # Call this callable, type check the returned value, and return this
            # value from this wrapper.
            func_body += '''
    return_value = __beartype_func(*args, **kwargs)
    if not isinstance(return_value, {return_type}):
        raise TypeError(
            '{func_name} return value {{}} not of {{!r}}'.format(
                return_value, {return_type}))
    return return_value
'''.format(func_name=func_name, return_type=func_return_type_expr)
        # Else, call this callable and return this value from this wrapper.
        else:
            func_body += '''
    return __beartype_func(*args, **kwargs)
'''

        # Dictionary mapping from local attribute name to value. For efficiency,
        # only those local attributes explicitly required in the body of this
        # wrapper are copied from the current namespace. (See below.)
        local_attrs = {'__beartype_func': func}

        # Dynamically define this wrapper as a closure of this decorator. For
        # obscure and presumably uninteresting reasons, Python fails to locally
        # declare this closure when the locals() dictionary is passed; to
        # capture this closure, a local dictionary must be passed instead.
        exec(func_body, globals(), local_attrs)

        # Return this wrapper.
        return local_attrs['func_beartyped']

    _PARAMETER_KIND_IGNORED = {
        Parameter.POSITIONAL_ONLY, Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD,
    }
    '''
    Set of all `inspect.Parameter.kind` constants to be ignored during
    annotation- based type checking in the `@beartype` decorator.

    This includes:

    * Constants specific to variadic parameters (e.g., `*args`, `**kwargs`).
      Variadic parameters cannot be annotated and hence cannot be type checked.
    * Constants specific to positional-only parameters, which apply to non-pure-
      Python callables (e.g., defined by C extensions). The `@beartype`
      decorator applies _only_ to pure-Python callables, which provide no
      syntactic means of specifying positional-only parameters.
    '''

    _RETURN_ANNOTATION_IGNORED = {Signature.empty, None}
    '''
    Set of all annotations for return values to be ignored during annotation-
    based type checking in the `@beartype` decorator.

    This includes:

    * `Signature.empty`, signifying a callable whose return value is _not_
      annotated.
    * `None`, signifying a callable returning no value. By convention, callables
      returning no value are typically annotated to return `None`. Technically,
      callables whose return values are annotated as `None` _could_ be
      explicitly checked to return `None` rather than a none-`None` value. Since
      return values are safely ignorable by callers, however, there appears to
      be little real-world utility in enforcing this constraint.
    '''

    def _check_type_annotation(annotation: object, label: str) -> None:
        '''
        Validate the passed annotation to be a valid type supported by the
        `@beartype` decorator.

        Parameters
        ----------
        annotation : object
            Annotation to be validated.
        label : str
            Human-readable label describing this annotation, interpolated into
            exceptions raised by this function.

        Raises
        ----------
        TypeError
            If this annotation is neither a new-style class nor a tuple of
            new-style classes.
        '''

        # If this annotation is a tuple, raise an exception if any member of
        # this tuple is not a new-style class. Note that the "__name__"
        # attribute tested below is not defined by old-style classes and hence
        # serves as a helpful means of identifying new-style classes.
        if isinstance(annotation, tuple):
            for member in annotation:
                if not (
                    isinstance(member, type) and hasattr(member, '__name__')):
                    raise TypeError(
                        '{} tuple member {} not a new-style class'.format(
                            label, member))
        # Else if this annotation is not a new-style class, raise an exception.
        elif not (
            isinstance(annotation, type) and hasattr(annotation, '__name__')):
            raise TypeError(
                '{} {} neither a new-style class nor '
                'tuple of such classes'.format(label, annotation))

# Else, the active Python interpreter is optimized. In this case, disable type
# checking by reducing this decorator to the identity decorator.
else:
    def beartype(func: callable) -> callable:
        return func

And leycec said, Let the @beartype bring forth type checking fastly: and it was so.

Caveats, Curses, and Empty Promises

Nothing is perfect. Even bear typing.

Caveat I: Default Values Unchecked

Bear typing does not type check unpassed parameters assigned default values. In theory, it could. But not in 275 lines or less and certainly not as a stackoverflow answer.

The safe (...probably totally unsafe) assumption is that function implementers claim they knew what they were doing when they defined default values. Since default values are typically constants (...they'd better be!), rechecking the types of constants that never change on each function call assigned one or more default values would contravene the fundamental tenet of bear typing: "Don't repeat yourself over and oooover and oooo-oooover again."

Show me wrong and I will shower you with upvotes.

Caveat II: No PEP 484

PEP 484 ("Type Hints") formalized the use of function annotations first introduced by PEP 3107 ("Function Annotations"). Python 3.5 superficially supports this formalization with a new top-level typing module, a standard API for composing arbitrarily complex types from simpler types (e.g., Callable[[Arg1Type, Arg2Type], ReturnType], a type describing a function accepting two arguments of type Arg1Type and Arg2Type and returning a value of type ReturnType).

Bear typing supports none of them. In theory, it could. But not in 275 lines or less and certainly not as a stackoverflow answer.

Bear typing does, however, support unions of types in the same way that the isinstance() builtin supports unions of types: as tuples. This superficially corresponds to the typing.Union type – with the obvious caveat that typing.Union supports arbitrarily complex types, while tuples accepted by @beartype support only simple classes. In my defense, 275 lines.

Tests or It Didn't Happen

Here's the gist of it. Get it, gist? I'll stop now.

As with the @beartype decorator itself, these py.test tests may be seamlessly integrated into existing test suites without modification. Precious, isn't it?

Now the mandatory neckbeard rant nobody asked for.

A History of API Violence

Python 3.5 provides no actual support for using PEP 484 types. wat?

It's true: no type checking, no type inference, no type nuthin'. Instead, developers are expected to routinely run their entire codebases through heavyweight third-party CPython interpreter wrappers implementing a facsimile of such support (e.g., mypy). Of course, these wrappers impose:

  • A compatibility penalty. As the official mypy FAQ admits in response to the frequently asked question "Can I use mypy to type check my existing Python code?": "It depends. Compatibility is pretty good, but some Python features are not yet implemented or fully supported." A subsequent FAQ response clarifies this incompatibility by stating that:
    • "...your code must make attributes explicit and use a explicit protocol representation." Grammar police see your "a explicit" and raise you an implicit frown.
    • "Mypy will support modular, efficient type checking, and this seems to rule out type checking some language features, such as arbitrary runtime addition of methods. However, it is likely that many of these features will be supported in a restricted form (for example, runtime modification is only supported for classes or methods registered as dynamic or ‘patchable’)."
    • For a full list of syntactic incompatibilities, see "Dealing with common issues". It's not pretty. You just wanted type checking and now you refactored your entire codebase and broke everyone's build two days from the candidate release and the comely HR midget in casual business attire slips a pink slip through the crack in your cubicle-cum-mancave. Thanks alot, mypy.
  • A performance penalty, despite interpreting statically typed code. Fourty years of hard-boiled computer science tells us that (...all else being equal) interpreting statically typed code should be faster, not slower, than interpreting dynamically typed code. In Python, up is the new down.
  • Additional non-trivial dependencies, increasing:
    • The bug-laden fragility of project deployment, especially cross-platform.
    • The maintenance burden of project development.
    • Possible attack surface.

I ask Guido: "Why? Why bother inventing an abstract API if you weren't willing to pony up a concrete API actually doing something with that abstraction?" Why leave the fate of a million Pythonistas to the arthritic hand of the free open-source marketplace? Why create yet another techno-problem that could have been trivially solved with a 275-line decorator in the official Python stdlib?

I have no Python and I must scream.

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

How to set radio button selected value using jquery

Can be done using the id of the element

example

<label><input type="radio" name="travel_mode"  value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode"  value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode"  value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode"  value="Road" id="Road"> Other </label>

js:

$('#' + selected).prop('checked',true);

How can I give an imageview click effect like a button on Android?

Thanks for the help on this thread. However, you missed one thing...you need to handle the ACTION_CANCEL as well. If you don't then you might not properly restore the alpha value of the ImageView in the event that a parent view in the view hierarchy intercepts a touch event (think a ScrollView wrapping you ImageView).

Here is a complete class that is based off the above class but takes care of the ACTION_CANCEL as well. It uses an ImageViewCompat helper class to abstract the differences in the pre-post JellyBean API.

public class ChangeAlphaOnPressedTouchListener implements OnTouchListener {

    private final float pressedAlpha;

    public ChangeAlphaOnPressedTouchListener(float pressedAlpha) {
        this.pressedAlpha = pressedAlpha;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView iv = (ImageView) v;
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            ImageViewCompat.setAlpha(iv, pressedAlpha);
            break;

        case MotionEvent.ACTION_MOVE:
            if (isInsideViewBounds(v, event)) {
                ImageViewCompat.setAlpha(iv, pressedAlpha);
            } else {
                ImageViewCompat.setAlpha(iv, 1f);
            }
            break;
        case MotionEvent.ACTION_UP:
            ImageViewCompat.setAlpha(iv, 1f);
            break;
        case MotionEvent.ACTION_CANCEL:
            ImageViewCompat.setAlpha(iv, 1f);
        }
        return false;
    }

    private static boolean isInsideViewBounds(View v, MotionEvent event) {
        return event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0
                && event.getY() < v.getHeight();
    }
}

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

How do I revert a Git repository to a previous commit?

git reflog

Choose the number of the HEAD(s) of git reflog, where you want revert to and do (for this example I choose the 12):

git reset HEAD@{12} --hard

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

This answer is a follow up to DaRKoN_'s answer that utilized the object filter:

[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.

What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:

public class SomeViewModel()
{
     public Person Person { get; set; }
     public Address Address { get; set; }
}

Then I would bind the view to SomeViewModel. You can do the same thing with JSON.

[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
     Person p = jsonViewModel.Person;
     Address a = jsonViewModel.Address;
     // Do stuff
     jsonViewModel.Person = p;
     jsonViewModel.Address = a;
     return Json(jsonViewModel);
}

Then in the view you can use a simple call with JQuery like this:

var json = { 
    Person: { Name: "John Doe", Sex: "Male", Age: 23 }, 
    Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};

$.ajax({
     url: 'home/doJsonStuff',
     type: 'POST',
     contentType: 'application/json',
     dataType: 'json',
     data: JSON.stringify(json), //You'll need to reference json2.js
     success: function (response)
     {
          var person = response.Person;
          var address = response.Address;
     }
});

How can I send and receive WebSocket messages on the server side?

Note: This is some explanation and pseudocode as to how to implement a very trivial server that can handle incoming and outcoming WebSocket messages as per the definitive framing format. It does not include the handshaking process. Furthermore, this answer has been made for educational purposes; it is not a full-featured implementation.

Specification (RFC 6455)


Sending messages

(In other words, server → browser)

The frames you're sending need to be formatted according to the WebSocket framing format. For sending messages, this format is as follows:

  • one byte which contains the type of data (and some additional info which is out of scope for a trivial server)
  • one byte which contains the length
  • either two or eight bytes if the length does not fit in the second byte (the second byte is then a code saying how many bytes are used for the length)
  • the actual (raw) data

The first byte will be 1000 0001 (or 129) for a text frame.

The second byte has its first bit set to 0 because we're not encoding the data (encoding from server to client is not mandatory).

It is necessary to determine the length of the raw data so as to send the length bytes correctly:

  • if 0 <= length <= 125, you don't need additional bytes
  • if 126 <= length <= 65535, you need two additional bytes and the second byte is 126
  • if length >= 65536, you need eight additional bytes, and the second byte is 127

The length has to be sliced into separate bytes, which means you'll need to bit-shift to the right (with an amount of eight bits), and then only retain the last eight bits by doing AND 1111 1111 (which is 255).

After the length byte(s) comes the raw data.

This leads to the following pseudocode:

bytesFormatted[0] = 129

indexStartRawData = -1 // it doesn't matter what value is
                       // set here - it will be set now:

if bytesRaw.length <= 125
    bytesFormatted[1] = bytesRaw.length

    indexStartRawData = 2

else if bytesRaw.length >= 126 and bytesRaw.length <= 65535
    bytesFormatted[1] = 126
    bytesFormatted[2] = ( bytesRaw.length >> 8 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length      ) AND 255

    indexStartRawData = 4

else
    bytesFormatted[1] = 127
    bytesFormatted[2] = ( bytesRaw.length >> 56 ) AND 255
    bytesFormatted[3] = ( bytesRaw.length >> 48 ) AND 255
    bytesFormatted[4] = ( bytesRaw.length >> 40 ) AND 255
    bytesFormatted[5] = ( bytesRaw.length >> 32 ) AND 255
    bytesFormatted[6] = ( bytesRaw.length >> 24 ) AND 255
    bytesFormatted[7] = ( bytesRaw.length >> 16 ) AND 255
    bytesFormatted[8] = ( bytesRaw.length >>  8 ) AND 255
    bytesFormatted[9] = ( bytesRaw.length       ) AND 255

    indexStartRawData = 10

// put raw data at the correct index
bytesFormatted.put(bytesRaw, indexStartRawData)


// now send bytesFormatted (e.g. write it to the socket stream)

Receiving messages

(In other words, browser → server)

The frames you obtain are in the following format:

  • one byte which contains the type of data
  • one byte which contains the length
  • either two or eight additional bytes if the length did not fit in the second byte
  • four bytes which are the masks (= decoding keys)
  • the actual data

The first byte usually does not matter - if you're just sending text you are only using the text type. It will be 1000 0001 (or 129) in that case.

The second byte and the additional two or eight bytes need some parsing, because you need to know how many bytes are used for the length (you need to know where the real data starts). The length itself is usually not necessary since you have the data already.

The first bit of the second byte is always 1 which means the data is masked (= encoded). Messages from the client to the server are always masked. You need to remove that first bit by doing secondByte AND 0111 1111. There are two cases in which the resulting byte does not represent the length because it did not fit in the second byte:

  • a second byte of 0111 1110, or 126, means the following two bytes are used for the length
  • a second byte of 0111 1111, or 127, means the following eight bytes are used for the length

The four mask bytes are used for decoding the actual data that has been sent. The algorithm for decoding is as follows:

decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]

where encodedByte is the original byte in the data, encodedByteIndex is the index (offset) of the byte counting from the first byte of the real data, which has index 0. masks is an array containing of the four mask bytes.

This leads to the following pseudocode for decoding:

secondByte = bytes[1]

length = secondByte AND 127 // may not be the actual length in the two special cases

indexFirstMask = 2          // if not a special case

if length == 126            // if a special case, change indexFirstMask
    indexFirstMask = 4

else if length == 127       // ditto
    indexFirstMask = 10

masks = bytes.slice(indexFirstMask, 4) // four bytes starting from indexFirstMask

indexFirstDataByte = indexFirstMask + 4 // four bytes further

decoded = new array

decoded.length = bytes.length - indexFirstDataByte // length of real data

for i = indexFirstDataByte, j = 0; i < bytes.length; i++, j++
    decoded[j] = bytes[i] XOR masks[j MOD 4]


// now use "decoded" to interpret the received data

How to tell if homebrew is installed on Mac OS X

Another one possible way:

# Check if Ninja is installed
if ! which ninja > /dev/null
then
echo 'Ninja installation...'
brew install ninja
fi

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

How to discard uncommitted changes in SourceTree?

Ok so in Windows sourcetree that is simple, on macOS I looked as well for a while..

Click Command + Shift + R while in source tree a hidden popup will be shown that will let you discard individual files OR ALL! Why is this hidden? We will never know.. but it works!

enter image description here

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Indirectly referenced from required .class file

How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?

If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes

How to draw a filled triangle in android canvas?

Don't moveTo() after each lineTo()

In other words, remove every moveTo() except the first one.

Seriously, if I just copy-paste OP's code and remove the unnecessary moveTo() calls, it works.

Nothing else needs to be done.


EDIT: I know the OP already posted his "final working solution", but he didn't state why it works. The actual reason was quite surprising to me, so I felt the need to add an answer.

How do I add all new files to SVN

On Alpine Linux OS I used this, based on others answers:

svn st | grep ^? | sed 's/? *//' | xargs -I fn svn add "fn"

How to close the current fragment by using Button like the back button?

You can try this logic because it is worked for me.

frag_profile profile_fragment = new frag_profile();

boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
    if (flag == false) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
        transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
        transaction.commit();
        flag = true;
    }

}

@Override
public void onBackPressed() {
    if (flag == true) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.remove(profile_fragment);
        transaction.commit();
        flag = false;
    }
    else super.onBackPressed();
}

How can I use UserDefaults in Swift?

I would say Anbu's answer perfectly fine but I had to add guard while fetching preferences to make my program doesn't fail

Here is the updated code snip in Swift 5

Storing data in UserDefaults

@IBAction func savePreferenceData(_ sender: Any) {
        print("Storing data..")
        UserDefaults.standard.set("RDC", forKey: "UserName") //String
        UserDefaults.standard.set("TestPass", forKey: "Passowrd")  //String
        UserDefaults.standard.set(21, forKey: "Age")  //Integer

    }

Fetching data from UserDefaults

    @IBAction func fetchPreferenceData(_ sender: Any) {
        print("Fetching data..")

        //added guard
        guard let uName = UserDefaults.standard.string(forKey: "UserName") else { return }
        print("User Name is :"+uName)
        print(UserDefaults.standard.integer(forKey: "Age"))
    }

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

Run Python script at startup in Ubuntu

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

How to check whether a Storage item is set?

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.

What is the C++ function to raise a number to a power?

if you want to deal with base_2 only then i recommend using left shift operator << instead of math library.

sample code :

int exp = 16;
for(int base_2 = 1; base_2 < (1 << exp); (base_2 <<= 1)){
std::cout << base_2 << std::endl;
}

sample output :

1   2   4   8   16  32  64  128  256  512  1024  2048  4096  8192  16384  32768

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Load Image from javascript

You can try this:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

This way, you can change the attribute for the image.

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

Javascript how to parse JSON array

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

Simple Random Samples from a Sql database

Apparently in some versions of SQL there's a TABLESAMPLE command, but it's not in all SQL implementations (notably, Redshift).

http://technet.microsoft.com/en-us/library/ms189108(v=sql.105).aspx

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

try this

SET foreign_key_checks = 0;

ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE

SET foreign_key_checks = 1;

How to determine the installed webpack version

If using Angular CLI v7+, the webpack version is printed in the output of ng version:

-> ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.6
@angular-devkit/build-angular     0.10.6
@angular-devkit/build-optimizer   0.10.6
@angular-devkit/build-webpack     0.10.6
@angular-devkit/core              7.0.6
@angular-devkit/schematics        7.0.6
@angular/cli                      7.0.6
@ngtools/webpack                  7.0.6
@schematics/angular               7.0.6
@schematics/update                0.10.6
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

Bash write to file without echo?

awk ' BEGIN { print "Hello, world" } ' > test.txt

would do it

Error: Could not find or load main class

I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.

java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

Using openssl to get the certificate from a server

A one-liner to extract the certificate from a remote server in PEM format, this time using sed:

openssl s_client -connect www.google.com:443 2>/dev/null </dev/null |  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

Concat a string to SELECT * MySql

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t in a string marks an escape sequence for a tab character. For a literal \, use \\.

How to pass the password to su/sudo/ssh without overriding the TTY?

For ssh you can use sshpass: sshpass -p yourpassphrase ssh user@host.

You just need to download sshpass first :)

$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server

How can I remove space (margin) above HTML header?

Try margin-top:

<header style="margin-top: -20px;">
    ...

Edit:

Now I found relative position probably a better choice:

<header style="position: relative; top: -20px;">
    ...

android : Error converting byte to dex

I found in my case, this issue was caused by an improper configuration of build.gradle. I had two different versions of com.google.firebase. Once the versions were the same, the issue was solved

Is there such a thing as min-font-size and max-font-size?

I got some smooth results with these. It flows smoothly between the 3 width ranges, like a continuous piecewise function.

@media screen and (min-width: 581px) and (max-width: 1760px){
    #expandingHeader {
        line-height:5.2vw;
        font-size: 5.99vw;
    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (min-width: 1761px){
    #expandingHeader {
        line-height:.9em;
        font-size: 7.03em;

    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (max-width: 580px){
    #expandingHeader {
        line-height:.9em;
        font-size: 2.3em;
    }
    #tagLine {
        letter-spacing: .1em;
        font-size: .65em;
        line-height: .10em;
    }
}

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Error Message: Gradle sync failed: Minimum supported Gradle version is 4.9. Current version is 4.1-milestone-1. If using the gradle wrapper, try editing the distributionUrl in SampleProj/app/gradle/wrapper/gradle-wrapper.properties to gradle-4.9-all.zip

I am using Android studio IDE version 3.2 beta 2.

Solution: When we open gradle-wrapper.properties file in IDE it shows correct distributionUrl. but originally it has not been updated. So change the distributionUrl property manually.

Example : open a gradle-wrapper.properties file in notepad or any other editor. /Project/app/gradle/wrapper/gradle-wrapper.properties and change distributionUrl property to like this

distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip

document.getElementById vs jQuery $()

Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.

The equivalent would be this

var contents = $('#contents').get(0);

or this

var contents = $('#contents')[0];

These will pull the element out of the jQuery object.

Lookup City and State by Zip Google Geocode Api

couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.

Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP() method.

You will be able to query by any zipcode (ex: 40220) and you will have a response back as the following...

<?xml version="1.0" encoding="UTF-8"?>
 <NewDataSet>
  <Table>
   <CITY>Louisville</CITY> 
   <STATE>KY</STATE> 
   <ZIP>40220</ZIP> 
   <AREA_CODE>502</AREA_CODE> 
   <TIME_ZONE>E</TIME_ZONE> 
  </Table> 
</NewDataSet>

Hope this helps...

How can I view an object with an alert()

you can use the JSON.stringify() method found in modern browsers and provided by json2.js.

var myObj = {"myProp":"Hello"};
alert (JSON.stringify(myObj));    // alerts {"myProp":"Hello"};

or

also check this library : http://devpro.it/JSON/files/JSON-js.html

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

Fastest way to convert string to integer in PHP

More ad-hoc benchmark results:

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'     

real    2m10.397s
user    2m10.220s
sys     0m0.025s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'              

real    2m1.724s
user    2m1.635s
sys     0m0.009s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'             

real    1m21.000s
user    1m20.964s
sys     0m0.007s

How can I get LINQ to return the object which has the max value for a given property?

try this:

var maxid = from i in items
            group i by i.clientid int g
            select new { id = g.Max(i=>i.ID }

Convert absolute path into relative path given a current directory using Bash

Python's os.path.relpath as a shell function

The goal of this relpath exercise is to mimic Python 2.7's os.path.relpath function (available from Python version 2.6 but only working properly in 2.7), as proposed by xni. As a consequence, some of the results may differ from functions provided in other answers.

(I have not tested with newlines in paths simply because it breaks the validation based on calling python -c from ZSH. It would certainly be possible with some effort.)

Regarding “magic” in Bash, I have given up looking for magic in Bash long ago, but I have since found all the magic I need, and then some, in ZSH.

Consequently, I propose two implementations.

The first implementation aims to be fully POSIX-compliant. I have tested it with /bin/dash on Debian 6.0.6 “Squeeze”. It also works perfectly with /bin/sh on OS X 10.8.3, which is actually Bash version 3.2 pretending to be a POSIX shell.

The second implementation is a ZSH shell function that is robust against multiple slashes and other nuisances in paths. If you have ZSH available, this is the recommended version, even if you are calling it in the script form presented below (i.e. with a shebang of #!/usr/bin/env zsh) from another shell.

Finally, I have written a ZSH script that verifies the output of the relpath command found in $PATH given the test cases provided in other answers. I added some spice to those tests by adding some spaces, tabs, and punctuation such as ! ? * here and there and also threw in yet another test with exotic UTF-8 characters found in vim-powerline.

POSIX shell function

First, the POSIX-compliant shell function. It works with a variety of paths, but does not clean multiple slashes or resolve symlinks.

#!/bin/sh
relpath () {
    [ $# -ge 1 ] && [ $# -le 2 ] || return 1
    current="${2:+"$1"}"
    target="${2:-"$1"}"
    [ "$target" != . ] || target=/
    target="/${target##/}"
    [ "$current" != . ] || current=/
    current="${current:="/"}"
    current="/${current##/}"
    appendix="${target##/}"
    relative=''
    while appendix="${target#"$current"/}"
        [ "$current" != '/' ] && [ "$appendix" = "$target" ]; do
        if [ "$current" = "$appendix" ]; then
            relative="${relative:-.}"
            echo "${relative#/}"
            return 0
        fi
        current="${current%/*}"
        relative="$relative${relative:+/}.."
    done
    relative="$relative${relative:+${appendix:+/}}${appendix#/}"
    echo "$relative"
}
relpath "$@"

ZSH shell function

Now, the more robust zsh version. If you would like it to resolve the arguments to real paths à la realpath -f (available in the Linux coreutils package), replace the :a on lines 3 and 4 with :A.

To use this in zsh, remove the first and last line and put it in a directory that is in your $FPATH variable.

#!/usr/bin/env zsh
relpath () {
    [[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
    local target=${${2:-$1}:a} # replace `:a' by `:A` to resolve symlinks
    local current=${${${2:+$1}:-$PWD}:a} # replace `:a' by `:A` to resolve symlinks
    local appendix=${target#/}
    local relative=''
    while appendix=${target#$current/}
        [[ $current != '/' ]] && [[ $appendix = $target ]]; do
        if [[ $current = $appendix ]]; then
            relative=${relative:-.}
            print ${relative#/}
            return 0
        fi
        current=${current%/*}
        relative="$relative${relative:+/}.."
    done
    relative+=${relative:+${appendix:+/}}${appendix#/}
    print $relative
}
relpath "$@"

Test script

Finally, the test script. It accepts one option, namely -v to enable verbose output.

#!/usr/bin/env zsh
set -eu
VERBOSE=false
script_name=$(basename $0)

usage () {
    print "\n    Usage: $script_name SRC_PATH DESTINATION_PATH\n" >&2
    exit ${1:=1}
}
vrb () { $VERBOSE && print -P ${(%)@} || return 0; }

relpath_check () {
    [[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
    target=${${2:-$1}}
    prefix=${${${2:+$1}:-$PWD}}
    result=$(relpath $prefix $target)
    # Compare with python's os.path.relpath function
    py_result=$(python -c "import os.path; print os.path.relpath('$target', '$prefix')")
    col='%F{green}'
    if [[ $result != $py_result ]] && col='%F{red}' || $VERBOSE; then
        print -P "${col}Source: '$prefix'\nDestination: '$target'%f"
        print -P "${col}relpath: ${(qq)result}%f"
        print -P "${col}python:  ${(qq)py_result}%f\n"
    fi
}

run_checks () {
    print "Running checks..."

    relpath_check '/    a   b/å/?*/!' '/    a   b/å/?/xäå/?'

    relpath_check '/'  '/A'
    relpath_check '/A'  '/'
    relpath_check '/  & /  !/*/\\/E' '/'
    relpath_check '/' '/  & /  !/*/\\/E'
    relpath_check '/  & /  !/*/\\/E' '/  & /  !/?/\\/E/F'
    relpath_check '/X/Y' '/  & /  !/C/\\/E/F'
    relpath_check '/  & /  !/C' '/A'
    relpath_check '/A /  !/C' '/A /B'
    relpath_check '/Â/  !/C' '/Â/  !/C'
    relpath_check '/  & /B / C' '/  & /B / C/D'
    relpath_check '/  & /  !/C' '/  & /  !/C/\\/Ê'
    relpath_check '/Å/  !/C' '/Å/  !/D'
    relpath_check '/.A /*B/C' '/.A /*B/\\/E'
    relpath_check '/  & /  !/C' '/  & /D'
    relpath_check '/  & /  !/C' '/  & /\\/E'
    relpath_check '/  & /  !/C' '/\\/E/F'

    relpath_check /home/part1/part2 /home/part1/part3
    relpath_check /home/part1/part2 /home/part4/part5
    relpath_check /home/part1/part2 /work/part6/part7
    relpath_check /home/part1       /work/part1/part2/part3/part4
    relpath_check /home             /work/part2/part3
    relpath_check /                 /work/part2/part3/part4
    relpath_check /home/part1/part2 /home/part1/part2/part3/part4
    relpath_check /home/part1/part2 /home/part1/part2/part3
    relpath_check /home/part1/part2 /home/part1/part2
    relpath_check /home/part1/part2 /home/part1
    relpath_check /home/part1/part2 /home
    relpath_check /home/part1/part2 /
    relpath_check /home/part1/part2 /work
    relpath_check /home/part1/part2 /work/part1
    relpath_check /home/part1/part2 /work/part1/part2
    relpath_check /home/part1/part2 /work/part1/part2/part3
    relpath_check /home/part1/part2 /work/part1/part2/part3/part4 
    relpath_check home/part1/part2 home/part1/part3
    relpath_check home/part1/part2 home/part4/part5
    relpath_check home/part1/part2 work/part6/part7
    relpath_check home/part1       work/part1/part2/part3/part4
    relpath_check home             work/part2/part3
    relpath_check .                work/part2/part3
    relpath_check home/part1/part2 home/part1/part2/part3/part4
    relpath_check home/part1/part2 home/part1/part2/part3
    relpath_check home/part1/part2 home/part1/part2
    relpath_check home/part1/part2 home/part1
    relpath_check home/part1/part2 home
    relpath_check home/part1/part2 .
    relpath_check home/part1/part2 work
    relpath_check home/part1/part2 work/part1
    relpath_check home/part1/part2 work/part1/part2
    relpath_check home/part1/part2 work/part1/part2/part3
    relpath_check home/part1/part2 work/part1/part2/part3/part4

    print "Done with checks."
}
if [[ $# -gt 0 ]] && [[ $1 = "-v" ]]; then
    VERBOSE=true
    shift
fi
if [[ $# -eq 0 ]]; then
    run_checks
else
    VERBOSE=true
    relpath_check "$@"
fi

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

How to force HTTPS using a web.config file

I was not allowed to install URL Rewrite in my environment, so, I found another path.

Adding this to my web.config added the error rewrite and worked on IIS 7.5:

<system.webServer>
    <httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="C:\WebSites\yoursite\" >    
    <remove statusCode="403" subStatusCode="4" />
    <error statusCode="403" subStatusCode="4" responseMode="File" path="redirectToHttps.html" />
</httpErrors>

Then, following the advice here: https://www.sslshopper.com/iis7-redirect-http-to-https.html

I configured the IIS website to require SSL and created the html file that does the redirect (redirectToHttps.html) upon the 403 (Forbidden) error:

<html>
<head><title>Redirecting...</title></head>
<script language="JavaScript">
function redirectHttpToHttps()
{
    var httpURL= window.location.hostname + window.location.pathname + window.location.search;
    var httpsURL= "https://" + httpURL;
    window.location = httpsURL;
}
redirectHttpToHttps();
</script>
<body>
</body>
</html>

I hope someone finds this useful as I could not find all of the pieces in one place anywhere else.

What is the best java image processing library/approach?

imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.

There are a lot of advantages of GraphicsMagick, but one for all:

  • GM is used to process billions of files at the world's largest photo sites (e.g. Flickr and Etsy).

saving a file (from stream) to disk using c#

Just do it with a simple filestream.

var sr1 = new FileStream(FilePath, FileMode.Create);
                sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
                sr1.Close();
                sr1.Dispose();

_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon()

is what you should use. the thing is behind the scenes asp.net will destroy the session but immediately give the user a brand new session on the next page request. So if you're checking to see if the session is gone right after calling abandon it will look like it didn't work.

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

'make' is a command for UNIX/Linux. Instead of it, use 'nmake' command in MS Windows. Or you'd better use an emulator like CYGWIN.

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

Angularjs prevent form submission when input validation fails

Your forms are automatically put into $scope as an object. It can be accessed via $scope[formName]

Below is an example that will work with your original setup and without having to pass the form itself as a parameter in ng-submit.

var controller = function($scope) {

    $scope.login = {
        submit: function() {
            if($scope.loginform.$invalid) return false;

        }
    }

};

Working example: http://plnkr.co/edit/BEWnrP?p=preview

How can I give eclipse more memory than 512M?

Configuring this worked for me: -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m on Eclipse Java Photon June 2018

Running Windows 10, 8 GB ram and 64 bit. You can extend -Xmx2048 -XX:MaxpermSize= 1024m to 4096m too, if your computer has good ram.Mine worked well.

How do I change the root directory of an Apache server?

I had to edit /etc/apache2/sites-available/default. The lines are the same as mentioned by RDL.

What's the difference between next() and nextLine() methods from Scanner class?

The key point is to find where the method will stop and where the cursor will be after calling the methods.

All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.


For example, consider the following illustration:

|23_24_25_26_27\n

| -> the current cursor position

_ -> whitespace

stream -> Bold (the information got by the calling method)

See what happens when you call these methods:

nextInt()    

read 23|_24_25_26_27\n

nextDouble()

read 23_24|_25_26_27\n

next()

read 23_24_25|_26_27\n

nextLine()

read 23_24_25_26_27\n|


After this, the method should be called depending on your requirement.

Sublime Text 2 multiple line edit

On Windows, I prefer Ctrl + Alt + Down.

It selects the lines one by one and automatically starts the multi-line editor mode. It is a bit faster this way. If you have a lot of lines to edit then selecting the text and Ctrl + Shift + L is a better choice.

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I had this problem running unit tests (xunit) in Visual Studio 2015 and came across the following fix:

Menu Bar -> Test -> Test Settings -> Default Processor Architecture -> X64

Convert Mat to Array/Vector in OpenCV

Instead of getting image row by row, you can put it directly to an array. For CV_8U type image, you can use byte array, for other types check here.

Mat img; // Should be CV_8U for using byte[]
int size = (int)img.total() * img.channels();
byte[] data = new byte[size];
img.get(0, 0, data); // Gets all pixels

add Shadow on UIView using swift 3

Very simple and few lines of code:

let viewShadow = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
viewShadow.center = self.view.center
viewShadow.backgroundColor = UIColor.yellow
viewShadow.layer.shadowColor = UIColor.red.cgColor
viewShadow.layer.shadowOpacity = 1
viewShadow.layer.shadowOffset = CGSize.zero
viewShadow.layer.shadowRadius = 5
self.view.addSubview(viewShadow)

Look like : enter image description here

python selenium click on button

For python, use the

from selenium.webdriver import ActionChains

and

ActionChains(browser).click(element).perform()

Exit/save edit to sudoers file? Putty SSH

To make changes to sudo from putty/bash:

  • Type visudo and press enter.
  • Navigate to the place you wish to edit using the up and down arrow keys.
  • Press insert to go into editing mode.
  • Make your changes - for example: user ALL=(ALL) ALL.
  • Note - it matters whether you use tabs or spaces when making changes.
  • Once your changes are done press esc to exit editing mode.
  • Now type :wq to save and press enter.
  • You should now be back at bash.
  • Now you can press ctrl + D to exit the session if you wish.

How do I call one constructor from another in Java?

I will tell you an easy way

There are two types of constructors:

  1. Default constructor
  2. Parameterized constructor

I will explain in one Example

class ConstructorDemo 
{
      ConstructorDemo()//Default Constructor
      {
         System.out.println("D.constructor ");
      }

      ConstructorDemo(int k)//Parameterized constructor
      {
         this();//-------------(1)
         System.out.println("P.Constructor ="+k);       
      }

      public static void main(String[] args) 
      {
         //this(); error because "must be first statement in constructor
         new ConstructorDemo();//-------(2)
         ConstructorDemo g=new ConstructorDemo(3);---(3)    
       }
   }                  

In the above example I showed 3 types of calling

  1. this() call to this must be first statement in constructor
  2. This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.

Note: this must be the first statement in the constructor.

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

Test if something is not undefined in JavaScript

Check if you're response[0] actually exists, the error seems to suggest it doesn't.

Get the contents of a table row with a button click

Try this:

$(".use-address").click(function() {
   $(this).closest('tr').find('td').each(function() {
        var textval = $(this).text(); // this will be the text of each <td>
   });
});

This will find the closest tr (going up through the DOM) of the currently clicked button and then loop each td - you might want to create a string / array with the values.

Example here

Getting the full address using an array example here

ldconfig error: is not a symbolic link

Solved, at least at the point of the question.

I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.

VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:

ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link

I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.

My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.

Thanks.

How to make a simple popup box in Visual C#?

Try this:

string text = "My text that I want to display";
MessageBox.Show(text);

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Once you set the app.config file, visual studio will generate a copy in the bin folder named App.exe.config. Copy this to the application directory during deployment. Sounds obvious but surprisingly a lot of people miss this step. WinForms developers are not used to config files :).

Property '...' has no initializer and is not definitely assigned in the constructor

Get this error at the time of adding Node in my Angular project -

TSError: ? Unable to compile TypeScript: (path)/base.api.ts:19:13 - error TS2564: Property 'apiRoot Path' has no initializer and is not definitely assigned in the constructor.

private apiRootPath: string;

Solution -

Added "strictPropertyInitialization": false in 'compilerOptions' of tsconfig.json.

my package.json -

"dependencies": {
    ...
    "@angular/common": "~10.1.3",
    "@types/express": "^4.17.9",
    "express": "^4.17.1",
    ...
}

Ref URL - https://www.ryadel.com/en/ts2564-ts-property-has-no-initializer-typescript-error-fix-visual-studio-2017-vs2017/

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I have a feeling that you are rendering your section from within an @section in the _Layout file that is referring to a partial view with an @section, i.e. you've nested an @section within an @section. In the _Layout file, remove the @section around the rendersection.

Truncate Decimal number not Round Off

This is similar to TcKs suggestion above, but using math.truncate rather than int conversions

VB: but you'll get the idea

Private Function TruncateToDecimalPlace(byval ToTruncate as decimal, byval DecimalPlaces as integer) as double 
dim power as decimal = Math.Pow(10, decimalplaces)
return math.truncate(totruncate * power) / power
end function

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

Gerrit error when Change-Id in commit messages are missing

We solved this issue this morning by re-cloning repository and re-applying changes. This is the simplest way to re-sync your local copy with Gerrit. As always we created a backup first.

Although there are a number of other wildly complicated solutions, its often advantageous to take a simple approach to avoid making things worse.

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

What's better at freeing memory with PHP: unset() or $var = null

Code example from comment

echo "PHP Version: " . phpversion() . PHP_EOL . PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;



$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    unset($a);
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;

Running in docker container from image php:7.4-fpm and others..

PHP Version: 7.4.8
took 0.22569918632507 seconds null
took 0.11705803871155 seconds unset
took 0.20791196823121 seconds null
took 0.11697316169739 seconds unset

PHP Version: 7.3.20
took 0.22086310386658 seconds null
took 0.11882591247559 seconds unset
took 0.21383500099182 seconds null
took 0.11916995048523 seconds unset

PHP Version: 7.2.32
took 0.24728178977966 seconds null
took 0.12719893455505 seconds unset
took 0.23839902877808 seconds null
took 0.12744522094727 seconds unset

PHP Version: 7.1.33
took 0.51380109786987 seconds null
took 0.50135898590088 seconds unset
took 0.50358104705811 seconds null
took 0.50115609169006 seconds unset

PHP Version: 7.0.33
took 0.50918698310852 seconds null
took 0.50490307807922 seconds unset
took 0.50227618217468 seconds null
took 0.50514912605286 seconds unset

PHP Version: 5.6.40
took 1.0063569545746 seconds null
took 1.6303179264069 seconds unset
took 1.0689589977264 seconds null
took 1.6382601261139 seconds unset

PHP Version: 5.4.45
took 1.0791940689087 seconds null
took 1.6308979988098 seconds unset
took 1.0029168128967 seconds null
took 1.6320278644562 seconds unset

But, with other example:

<?php
ini_set("memory_limit", "512M");

echo "PHP Version: " . phpversion() . PHP_EOL . PHP_EOL;

$start = microtime(true);
$arr = [];
for ($i = 0; $i < 1000000; $i++) {
    $arr[] = 'a';
}
$arr = null;
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;



$start = microtime(true);
$arr = [];
for ($i = 0; $i < 1000000; $i++) {
    $arr[] = 'a';
}
unset($arr);
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;

Results:

PHP Version: 7.4.8
took 0.053696155548096 seconds
took 0.053897857666016 seconds

PHP Version: 7.3.20
took 0.054572820663452 seconds
took 0.054342031478882 seconds

PHP Version: 7.2.32
took 0.05678391456604 seconds
took 0.057311058044434 seconds


PHP Version: 7.1.33
took 0.097366094589233 seconds
took 0.073100090026855 seconds

PHP Version: 7.0.33
took 0.076443910598755 seconds
took 0.077098846435547 seconds

PHP Version: 7.0.33
took 0.075634002685547 seconds
took 0.075317859649658 seconds

PHP Version: 5.6.40
took 0.29681086540222 seconds
took 0.28199100494385 seconds

PHP Version: 5.4.45
took 0.30513095855713 seconds
took 0.29265689849854 seconds

How to execute cmd commands via Java

Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call: rt.exec("cmd myfile.bat"); or similar

Quicksort with Python

Quick sort without additional memory (in place)

Usage:

array = [97, 200, 100, 101, 211, 107]
quicksort(array)
# array -> [97, 100, 101, 107, 200, 211]
def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
        if array[i] <= array[begin]:
            pivot += 1
            array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    return pivot



def quicksort(array, begin=0, end=None):
    if end is None:
        end = len(array) - 1
    def _quicksort(array, begin, end):
        if begin >= end:
            return
        pivot = partition(array, begin, end)
        _quicksort(array, begin, pivot-1)
        _quicksort(array, pivot+1, end)
    return _quicksort(array, begin, end)

Creating a simple login form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Login Page</title>
      <style>
         /* Basics */
         html, body {
         width: 100%;
         height: 100%;
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         color: #444;
         -webkit-font-smoothing: antialiased;
         background: #f0f0f0;
         }
         #container {
         position: fixed;
         width: 340px;
         height: 280px;
         top: 50%;
         left: 50%;
         margin-top: -140px;
         margin-left: -170px;
         background: #fff;
         border-radius: 3px;
         border: 1px solid #ccc;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
         }
         form {
         margin: 0 auto;
         margin-top: 20px;
         }
         label {
         color: #555;
         display: inline-block;
         margin-left: 18px;
         padding-top: 10px;
         font-size: 14px;
         }
         p a {
         font-size: 11px;
         color: #aaa;
         float: right;
         margin-top: -13px;
         margin-right: 20px;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         p a:hover {
         color: #555;
         }
         input {
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         font-size: 12px;
         outline: none;
         }
         input[type=text],
         input[type=password] ,input[type=time]{
         color: #777;
         padding-left: 10px;
         margin: 10px;
         margin-top: 12px;
         margin-left: 18px;
         width: 290px;
         height: 35px;
         border: 1px solid #c7d0d2;
         border-radius: 2px;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         input[type=text]:hover,
         input[type=password]:hover,input[type=time]:hover {
         border: 1px solid #b6bfc0;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
         }
         input[type=text]:focus,
         input[type=password]:focus,input[type=time]:focus {
         border: 1px solid #a8c9e4;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
         }
         #lower {
         background: #ecf2f5;
         width: 100%;
         height: 69px;
         margin-top: 20px;
         box-shadow: inset 0 1px 1px #fff;
         border-top: 1px solid #ccc;
         border-bottom-right-radius: 3px;
         border-bottom-left-radius: 3px;
         }
         input[type=checkbox] {
         margin-left: 20px;
         margin-top: 30px;
         }
         .check {
         margin-left: 3px;
         font-size: 11px;
         color: #444;
         text-shadow: 0 1px 0 #fff;
         }
         input[type=submit] {
         float: right;
         margin-right: 20px;
         margin-top: 20px;
         width: 80px;
         height: 30px;
         font-size: 14px;
         font-weight: bold;
         color: #fff;
         background-color: #acd6ef; /*IE fallback*/
         background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         border-radius: 30px;
         border: 1px solid #66add6;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
         cursor: pointer;
         }
         input[type=submit]:hover {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         }
         input[type=submit]:active {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
         background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         }
      </style>
   </head>
   <body>
      <!-- Begin Page Content -->
      <div id="container">
         <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
               <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
               <input type="submit" value="Login">
            </div>
            <!--/ lower-->
         </form>
      </div>
      <!--/ container-->
      <!-- End Page Content -->
   </body>
</html>

Create a list from two object lists with linq

This is Linq

var mergedList = list1.Union(list2).ToList();

This is Normaly (AddRange)

var mergedList=new List<Person>();
mergeList.AddRange(list1);
mergeList.AddRange(list2);

This is Normaly (Foreach)

var mergedList=new List<Person>();

foreach(var item in list1)
{
    mergedList.Add(item);
}
foreach(var item in list2)
{
     mergedList.Add(item);
}

This is Normaly (Foreach-Dublice)

var mergedList=new List<Person>();

foreach(var item in list1)
{
    mergedList.Add(item);
}
foreach(var item in list2)
{
   if(!mergedList.Contains(item))
   {
     mergedList.Add(item);
   }
}

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I get the same issue. In fact, the request didn't reach the jersey annoted method. I solved the problem with add the annotation: @Consumes(MediaType.APPLICATION_FORM_URLENCODED) The annotation @Consumes("/") don't work!

    @Path("/"+PropertiesHabilitation.KEY_EstNouvelleGH)
    @POST
    //@Consumes("*/*")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void  get__EstNouvelleGH( @Context HttpServletResponse response) {
        ...
    }

How to change href attribute using JavaScript after opening the link in a new window?

You can change this in the page load.

My intention is that when the page comes to the load function, switch the links (the current link in the required one)

python pandas dataframe to dictionary

in some versions the code below might not work

mydict = dict(zip(df.id, df.value))

so make it explicit

id_=df.id.values
value=df.value.values
mydict=dict(zip(id_,value))

Note i used id_ because the word id is reserved word

How to draw circle in html page?

_x000D_
_x000D_
.circle{_x000D_
    height: 65px;_x000D_
    width: 65px;_x000D_
    border-radius: 50%;_x000D_
    border:1px solid red;_x000D_
    line-height: 65px;_x000D_
    text-align: center;_x000D_
}
_x000D_
<div class="circle"><span>text</span></div>
_x000D_
_x000D_
_x000D_

jquery .live('click') vs .click()

In addition to T.J. Crowders answer, I have added some more handlers - including the newer .on(...) handler to the snippet so you can see which events are being hidden and which ones not.

What I also found is that .live() is not only deprecated, but was deleted since jQuery 1.9.x. But the other ones, i.e.
.click, .delegate/.undelegate and .on/.off
are still there.

Also note there is more discussion about this topic here on Stackoverflow.

If you need to fix legacy code that is relying on .live, but you require to use a new version of jQuery (> 1.8.3), you can fix it with this snippet:

// fix if legacy code uses .live, but you want to user newer jQuery library
if (!$.fn.live) {
    // in this case .live does not exist, emulate .live by calling .on
    $.fn.live = function(events, handler) {
      $(this).on(events, null, {}, handler);
    };
}

The intention of the snippet below, which is an extension of T.J.'s script, is that you can try out by yourself instantly what happens if you bind multiple handlers - so please run the snippet and click on the texts below:

_x000D_
_x000D_
jQuery(function($) {_x000D_
_x000D_
  // .live connects function with all spans_x000D_
  $('span').live('click', function() {_x000D_
    display("<tt>live</tt> caught a click!");_x000D_
  });_x000D_
_x000D_
  // --- catcher1 events ---_x000D_
_x000D_
  // .click connects function with id='catcher1'_x000D_
  $('#catcher1').click(function() {_x000D_
    display("Click Catcher1 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // --- catcher2 events ---_x000D_
_x000D_
  // .click connects function with id='catcher2'_x000D_
  $('#catcher2').click(function() {_x000D_
    display("Click Catcher2 caught a click and prevented <tt>live</tt>, <tt>delegate</tt> and <tt>on</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .delegate connects function with id='catcher2'_x000D_
  $(document).delegate('#catcher2', 'click', function() {_x000D_
    display("Delegate Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .on connects function with id='catcher2'_x000D_
  $(document).on('click', '#catcher2', {}, function() {_x000D_
    display("On Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // --- catcher3 events ---_x000D_
_x000D_
  // .delegate connects function with id='catcher3'_x000D_
  $(document).delegate('#catcher3', 'click', function() {_x000D_
    display("Delegate Catcher3 caught a click and <tt>live</tt> and <tt>on</tt> can see it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .on connects function with id='catcher3'_x000D_
  $(document).on('click', '#catcher3', {}, function() {_x000D_
    display("On Catcher3 caught a click and and <tt>live</tt> and <tt>delegate</tt> can see it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  function display(msg) {_x000D_
    $("<p>").html(msg).appendTo(document.body);_x000D_
  }_x000D_
_x000D_
});
_x000D_
<!-- with JQuery 1.8.3 it still works, but .live was removed since 1.9.0 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>_x000D_
_x000D_
<style>_x000D_
span.frame {_x000D_
    line-height: 170%; border-style: groove;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<div>_x000D_
  <span class="frame">Click me</span>_x000D_
  <span class="frame">or me</span>_x000D_
  <span class="frame">or me</span>_x000D_
  <div>_x000D_
    <span class="frame">I'm two levels in</span>_x000D_
    <span class="frame">so am I</span>_x000D_
  </div>_x000D_
  <div id='catcher1'>_x000D_
    <span class="frame">#1 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
  <div id='catcher2'>_x000D_
    <span class="frame">#2 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
  <div id='catcher3'>_x000D_
    <span class="frame">#3 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error message "No exports were found that match the constraint contract name"

I had to uninstall some external components like Postsharp and Apex and then it worked. I also tried the chosen solution but it gave me more errors.

Total size of the contents of all the files in a directory

There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).

1.

$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes

real    0m0.221s
user    0m0.068s
sys     0m0.160s

2.

$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes

real    0m0.256s
user    0m0.164s
sys     0m0.196s

3.

$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes

real    0m0.553s
user    0m0.308s
sys     0m0.416s


These two also work, but they rely on commands that don't exist on Git Bash for Windows:

1.

$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes

real    0m0.233s
user    0m0.116s
sys     0m0.176s

2.

$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes

real    0m0.242s
user    0m0.104s
sys     0m0.152s


If you only want the total for the current directory, then add -maxdepth 1 to find.


Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.

$ du -sbh
832M    .

$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525

$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471

$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133

Is it possible to embed animated GIFs in PDFs?

It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.

How to align text below an image in CSS?

You can use the HTML5 Caption feature.

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Why should I use var instead of a type?

As the others have said, there is no difference in the compiled code (IL) when you use either of the following:

var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?

Consider the following and you'll get what I mean:

KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:

var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

What is IPV6 for localhost and 0.0.0.0?

Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).

Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr (which will be converted to http://[::ffff:7f00:1]:19983/solr)

Calculate last day of month in JavaScript

Here is an answer that conserves GMT and time of the initial date

_x000D_
_x000D_
var date = new Date();_x000D_
_x000D_
var first_date = new Date(date); //Make a copy of the date we want the first and last days from_x000D_
first_date.setUTCDate(1); //Set the day as the first of the month_x000D_
_x000D_
var last_date = new Date(first_date); //Make a copy of the calculated first day_x000D_
last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month_x000D_
last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month_x000D_
_x000D_
console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd
_x000D_
_x000D_
_x000D_

Accessing a Dictionary.Keys Key through a numeric index

You could always do this:

string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]

But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys on MSDN is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.

How to change the link color in a specific class for a div CSS

It can be something like this:

a.register:link { color:#FFF; text-decoration:none; font-weight:normal; }
a.register:visited { color: #FFF; text-decoration:none; font-weight:normal; }
a.register:hover { color: #FFF; text-decoration:underline; font-weight:normal; }
a.register:active { color: #FFF; text-decoration:none; font-weight:normal; }

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Reloading .env variables without restarting server (Laravel 5, shared hosting)

A short solution:

use Dotenv;

with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());

In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this

app('db')->purge($connection->getName()); 

after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager needs to re-read config parameters.

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

Determining image file size + dimensions via Javascript?

You can find dimension of an image on the page using something like

document.getElementById('someImage').width

file size, however, you will have to use something server-side

catching stdout in realtime from subprocess

if you run something like this in a thread and save the ffmpeg_time property in a property of a method so you can access it, it would work very nice I get outputs like this: output be like if you use threading in tkinter

input = 'path/input_file.mp4'
output = 'path/input_file.mp4'
command = "ffmpeg -y -v quiet -stats -i \"" + str(input) + "\" -metadata title=\"@alaa_sanatisharif\" -preset ultrafast -vcodec copy -r 50 -vsync 1 -async 1 \"" + output + "\""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
for line in self.process.stdout:
    reg = re.search('\d\d:\d\d:\d\d', line)
    ffmpeg_time = reg.group(0) if reg else ''
    print(ffmpeg_time)

How to remove first 10 characters from a string?

str = str.Remove(0,10); Removes the first 10 characters

or

str = str.Substring(10); Creates a substring starting at the 11th character to the end of the string.

For your purposes they should work identically.

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

What is the correct value for the disabled attribute?

  • For XHTML, <input type="text" disabled="disabled" /> is the valid markup.
  • For HTML5, <input type="text" disabled /> is valid and used by W3C on their samples.
  • In fact, both ways works on all major browsers.

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

JavaScript get window X/Y position for scroll

function FastScrollUp()
{
     window.scroll(0,0)
};

function FastScrollDown()
{
     $i = document.documentElement.scrollHeight ; 
     window.scroll(0,$i)
};
 var step = 20;
 var h,t;
 var y = 0;
function SmoothScrollUp()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, -step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollUp()},20);

};


function SmoothScrollDown()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollDown()},20);

}

Getting the folder name from a path

Simple & clean. Only uses System.IO.FileSystem - works like a charm:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

How do I convert a Django QuerySet into list of dicts?

You could define a function using model_to_dict as follows:

def queryset_to_list(qs,fields=None, exclude=None):
    my_list=[]
    for x in qs:
        my_list.append(model_to_dict(x,fields=fields,exclude=exclude))
    return my_list

Suppose your Model has following fields

id
name
email

Run following commands in django shell

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'[email protected]'},{'id':2, 'name':'xyz', 'email':'[email protected]'}]

Say you want only id and name in the list of queryset dictionary

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]

Similarly you can exclude fields in your output.

efficient way to implement paging

Try using

FROM [TableX]
ORDER BY [FieldX]
OFFSET 500 ROWS
FETCH NEXT 100 ROWS ONLY

to get the rows from 501 to 600 in the SQL server, without loading them in memory. Note that this syntax has become available with SQL Server 2012 only

Font is not available to the JVM with Jasper Reports

JasperReports raises a JRFontNotFoundException in the case where the font used inside a report template is not available to the JVM as either as a system font or a font coming from a JR font extension. This ensure that all problems caused by font metrics mismatches are avoided and we have an early warning about the inconsistency.

Jasper reports is trying to help you in your report development, stating that it can not export your report correctly since it can not find the font defined in TextField or StaticText

<font fontName="Arial"/>

Yes you can disable this by setting net.sf.jasperreports.awt.ignore.missing.font to true but you will have export inconsistencies.

Yes you can install the font as JVM system font (but you need to do it on every PC used that may generate report and you can still have encoding problems).

The correct way!

Use Font Extensions!, if you like to create your own (see link below), jasper reports also distributes a default font-extension jar (jasperreports-fonts-x.x.x.jar), that supports fontName DejaVu Sans, DejaVu Serif and DejaVu Sans Mono

<font fontName="DejaVu Sans"/>

From the JasperReport Ultimate Guide:

We strongly encourage people to use only fonts derived from font extensions, because this is the only way to make sure that the fonts will be available to the application when the reports are executed at runtime. Using system fonts always brings the risk for the reports not to work properly when deployed on a new machine that might not have those fonts installed

Links on StackOverflow on how to render fonts correctly in pdf

Checklist on how to render font correctly in pdf

Generate font-extensions with JasperSoft Studio

Generate font-extensions with iReport

Address validation using Google Maps API

Validate it against FedEx's api. They have an API to generate labels from XML code. The process involves a step to validate the address.

estimating of testing effort as a percentage of development time

The only time I factor in extra time for testing is if I'm unfamiliar with the testing technology I'll be using (e.g. using Selenium tests for the first time). Then I factor in maybe 10-20% for getting up to speed on the tools and getting the test infrastructure in place.

Otherwise testing is just an innate part of development and doesn't warrant an extra estimate. In fact, I'd probably increase the estimate for code done without tests.

EDIT: Note that I'm usually writing code test-first. If I have to come in after the fact and write tests for existing code that's going to slow things down. I don't find that test-first development slows me down at all except for very exploratory (read: throw-away) coding.

Cache an HTTP 'Get' service response in AngularJS?

Angular's $http has a cache built in. According to the docs:

cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.

Boolean value

So you can set cache to true in its options:

$http.get(url, { cache: true}).success(...);

or, if you prefer the config type of call:

$http({ cache: true, url: url, method: 'GET'}).success(...);

Cache Object

You can also use a cache factory:

var cache = $cacheFactory('myCache');

$http.get(url, { cache: cache })

You can implement it yourself using $cacheFactory (especially handly when using $resource):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);
   });
}

Converting RGB to grayscale/intensity

Check out the Color FAQ for information on this. These values come from the standardization of RGB values that we use in our displays. Actually, according to the Color FAQ, the values you are using are outdated, as they are the values used for the original NTSC standard and not modern monitors.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I've had this a couple of times. It's especially frustrating as it's right off the bat, and the error message holds no clue as to what might be the issue.

To fix this, right click your project title, in this case "TestMvcApplication" and click build.

This forces the code to compile before you run it. Don't ask me why, but this has been the solution 100% of the time for me.

jQuery Datepicker onchange event issue

My solution is:

events: {
    'apply.daterangepicker #selector': 'function'
}

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ ]] has more features - I suggest you take a look at the Advanced Bash Scripting Guide for more info, specifically the extended test command section in Chapter 7. Tests.

Incidentally, as the guide notes, [[ ]] was introduced in ksh88 (the 1988 version of the Korn shell).

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

For me these was my problem, solution from https://unix.stackexchange.com/questions/282908/server-refused-public-key-signature-despite-accepting-key-putty

"Looking at the log /var/log/secure showed that it was just downright refused. I'm somewhat new to centos since I'm mainly a debian kind of guy, so I was unaware of /var/log/secure

After checking this and doing a bit of searching, it turns out PermitRootLogin no needs to be PermitRootLogin without-password if you want to specifically use just keys for root login. That did the trick. Thanks everyone for contributing."

Is there a way to use PhantomJS in Python?

this is what I do, python3.3. I was processing huge lists of sites, so failing on the timeout was vital for the job to run through the entire list.

command = "phantomjs --ignore-ssl-errors=true "+<your js file for phantom>
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

# make sure phantomjs has time to download/process the page
# but if we get nothing after 30 sec, just move on
try:
    output, errors = process.communicate(timeout=30)
except Exception as e:
    print("\t\tException: %s" % e)
    process.kill()

# output will be weird, decode to utf-8 to save heartache
phantom_output = ''
for out_line in output.splitlines():
    phantom_output += out_line.decode('utf-8')

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Java: JSON -> Protobuf & back conversion

Try JsonFormat.printer().print(MessageOrBuilder), it looks good for proto3. Yet, it is unclear how to convert the actual protobuf message (which is provided as the java package of my choice defined in the .proto file) to a com.google.protbuf.Message object.

Import SQL file by command line in Windows 7

To import SQL file what works for me

For Wamp-Server

  1. Find mysql in wamp. In my computer it's location is "C:\wamp64\bin\mysql\mysql5.7.21\bin"

Open cmd and once you get inside bin you have to write " mysql -uroot -p database_name < filename.sql"

remember to put sql file under bin.

in nutshell you have to do this:-

C:\wamp64\bin\mysql\mysql5.7.21\bin>mysql -uroot -p database_name < filename.sql

After this, it will ask for the password, mine password was nothing(BLANK).

hope it helps someone.

How do I change a tab background color when using TabLayout?

Have you tried checking the API?

You will need to create a listener for the OnTabSelectedListener event, then when a user selects any tab you should check if it is the correct one, then change the background color using tabLayout.setBackgroundColor(int color), or if it is not the correct tab make sure you change back to the normal color again with the same method.

How to convert int to char with leading zeros?

I was wondering, would this be on any use to you?

declare @val int,@len=800
select replace(str(@val,@len),' ','0')

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

UnicodeDecodeError when reading CSV file in Pandas with Python

Simplest of all Solutions:

import pandas as pd
df = pd.read_csv('file_name.csv', engine='python')

Alternate Solution:

  • Open the csv file in Sublime text editor or VS Code.
  • Save the file in utf-8 format.

In sublime, Click File -> Save with encoding -> UTF-8

Then, you can read your file as usual:

import pandas as pd
data = pd.read_csv('file_name.csv', encoding='utf-8')

and the other different encoding types are:

encoding = "cp1252"
encoding = "ISO-8859-1"

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

var regexp = /^[a-zA-Z0-9-_]+$/;

How to add a scrollbar to an HTML5 table?

@jogesh_pi answer is a good solution, i've created a example here http://jsfiddle.net/pqgaS/5/, check it, hope this help

<div id="listtableWrapperScroll">
    <table id="listtable">
        <tr>
            <td>Data Data</td>
            <td>Data Data</td>
            <td>Data Data</td>                
        </tr>
    </table>
</div>

#listtableWrapperScroll{
    height:100px;
    width:460px;
    overflow-y:scroll;
    border:1px solid #777777;
    background:#FFFFF2;
}
#listtableWrapperScroll #listtable{
    width:440px;       
}
#listtableWrapperScroll #listtable tr td{
    border-bottom:1px dashed #444;
}

Convert text into number in MySQL query

To get number try with SUBSTRING_INDEX(field, '-', 1) then convert.

SQL Server SELECT LAST N Rows

In a very general way and to support SQL server here is

SELECT TOP(N) *
FROM tbl_name
ORDER BY tbl_id DESC

and for the performance, it is not bad (less than one second for more than 10,000 records On Server machine)

JQuery: How to get selected radio button value?

jQuery("input:radio[name=myradiobutton]:checked").val();

How to get a list of installed android applications and pick one to run

Following is the code to get the list of activities/applications installed on Android :

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

You will get all the necessary data in the ResolveInfo to start a application. You can check ResolveInfo javadoc here.

How does bitshifting work in Java?

When you shift right 2 bits you drop the 2 least significant bits. So:

x = 00101011

x >> 2

// now (notice the 2 new 0's on the left of the byte)
x = 00001010

This is essentially the same thing as dividing an int by 2, 2 times.

In Java

byte b = (byte) 16;
b = b >> 2;
// prints 4
System.out.println(b);

how to delete all cookies of my website in php

make sure you call your setcookie function before any output happens on your site.

also, if your users are logging out, you should also delete/invalidate their session variables.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

jQuery Form Validation before Ajax submit

first you don't need to add the classRules explicitly since required is automatically detected by the jquery.validate plugin. so you can use this code :

  1. on form submit , you prevent the default behavior
  2. if the form is Invalid stop the execution.
  3. else if valid send the ajax request.
$('#form').submit(function (e) {
  e.preventDefault();
  var $form = $(this);

  // check if the input is valid using a 'valid' property
  if (!$form.valid) return false;

  $.ajax({
    type: 'POST',
    url: 'add.php',
    data: $('#form').serialize(),
    success: function (response) {
      $('#answers').html(response);
    },
  });
});

Get protocol + host name from URL

>>> import urlparse
>>> url = 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah'
>>> urlparse.urljoin(url, '/')
'http://stackoverflow.com/'

Test if a property is available on a dynamic variable

I thought I'd do a comparison of Martijn's answer and svick's answer...

The following program returns the following results:

Testing with exception: 2430985 ticks
Testing with reflection: 155570 ticks

void Main()
{
    var random = new Random(Environment.TickCount);

    dynamic test = new Test();

    var sw = new Stopwatch();

    sw.Start();

    for (int i = 0; i < 100000; i++)
    {
        TestWithException(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with exception: " + sw.ElapsedTicks.ToString() + " ticks");

    sw.Restart();

    for (int i = 0; i < 100000; i++)
    {
        TestWithReflection(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with reflection: " + sw.ElapsedTicks.ToString() + " ticks");
}

class Test
{
    public bool Exists { get { return true; } }
}

bool FlipCoin(Random random)
{
    return random.Next(2) == 0;
}

bool TestWithException(dynamic d, bool useExisting)
{
    try
    {
        bool result = useExisting ? d.Exists : d.DoesntExist;
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

bool TestWithReflection(dynamic d, bool useExisting)
{
    Type type = d.GetType();

    return type.GetProperties().Any(p => p.Name.Equals(useExisting ? "Exists" : "DoesntExist"));
}

As a result I'd suggest using reflection. See below.


Responding to bland's comment:

Ratios are reflection:exception ticks for 100000 iterations:

Fails 1/1: - 1:43 ticks
Fails 1/2: - 1:22 ticks
Fails 1/3: - 1:14 ticks
Fails 1/5: - 1:9 ticks
Fails 1/7: - 1:7 ticks
Fails 1/13: - 1:4 ticks
Fails 1/17: - 1:3 ticks
Fails 1/23: - 1:2 ticks
...
Fails 1/43: - 1:2 ticks
Fails 1/47: - 1:1 ticks

...fair enough - if you expect it to fail with a probability with less than ~1/47, then go for exception.


The above assumes that you're running GetProperties() each time. You may be able to speed up the process by caching the result of GetProperties() for each type in a dictionary or similar. This may help if you're checking against the same set of types over and again.

Spool Command: Do not output SQL statement to file

set echo off
spool c:\test.csv 
select /*csv*/ username, user_id, created from all_users;
spool off;

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

What is the difference between user variables and system variables?

Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

No notification sound when sending notification from firebase in android

In the notification payload of the notification there is a sound key.

From the official documentation its use is:

Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.

Eg:

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",

    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon",
      "sound" : "mySound"
    }
  }

If you want to use default sound of the device, you should use: "sound": "default".

See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Since C++11 std::regex_search can also be used to provide even more complex expressions matching. The following example handles also floating numbers thorugh std::stof and a subsequent cast to int.

However the parseInt method shown below could throw a std::invalid_argument exception if the prefix is not matched; this can be easily adapted depending on the given application:

#include <iostream>
#include <regex>

int parseInt(const std::string &str, const std::string &prefix) {
  std::smatch match;
  std::regex_search(str, match, std::regex("^" + prefix + "([+-]?(?=\\.?\\d)\\d*(?:\\.\\d*)?(?:[Ee][+-]?\\d+)?)$"));
  return std::stof(match[1]);
}

int main() {
    std::cout << parseInt("foo=13.3", "foo=") << std::endl;
    std::cout << parseInt("foo=-.9", "foo=") << std::endl;
    std::cout << parseInt("foo=+13.3", "foo=") << std::endl;
    std::cout << parseInt("foo=-0.133", "foo=") << std::endl;
    std::cout << parseInt("foo=+00123456", "foo=") << std::endl;
    std::cout << parseInt("foo=-06.12e+3", "foo=") << std::endl;

//    throw std::invalid_argument
//    std::cout << parseInt("foo=1", "bar=") << std::endl;

    return 0;
}

The kind of magic of the regex pattern is well detailed in the following answer.

EDIT: the previous answer did not performed the conversion to integer.

Select row with most recent date per user

Already solved, but just for the record, another approach would be to create two views...

CREATE TABLE lms_attendance
(id int, user int, time int, io varchar(3));

CREATE VIEW latest_all AS
SELECT la.user, max(la.time) time
FROM lms_attendance la 
GROUP BY la.user;

CREATE VIEW latest_io AS
SELECT la.* 
FROM lms_attendance la
JOIN latest_all lall 
    ON lall.user = la.user
    AND lall.time = la.time;

INSERT INTO lms_attendance 
VALUES
(1, 9, 1370931202, 'out'),
(2, 9, 1370931664, 'out'),
(3, 6, 1370932128, 'out'),
(4, 12, 1370932128, 'out'),
(5, 12, 1370933037, 'in');

SELECT * FROM latest_io;

Click here to see it in action at SQL Fiddle

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

Convert string to date in Swift

just Step 1 > get the String value from JSON or dataSource

Step 2 > create a local variable and assign it.

let startDate = CurrentDashBoard.startdate

Step 3> create an instance of DateFormatter.

let dateFormatter = DateFormatter()

step 4> call the dateFormat from dateFormatter and provide saved date dataType.

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")

step 5> Assign the Local variable to this variable to convert.

let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate

Step 6> provide your required date Formate by the following code.

dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"

Step 6> Assign it to label/text

cell.lblStartDate.text = String(format: "%@", strstartDate)

Code:

let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate : 
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)

How to trigger event when a variable's value is changed?

The .NET framework actually provides an interface that you can use for notifying subscribers when a property has changed: System.ComponentModel.INotifyPropertyChanged. This interface has one event PropertyChanged. Its usually used in WPF for binding but I have found it useful in business layers as a way to standardize property change notification.

In terms of thread safety I would put a lock under in the setter so that you don't run into any race conditions.

Here are my thoughts in code :) :

public class MyClass : INotifyPropertyChanged
{
    private object _lock;

    public int MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            lock(_lock)
            {
                //The property changed event will get fired whenever
                //the value changes. The subscriber will do work if the value is
                //1. This way you can keep your business logic outside of the setter
                if(value != _myProperty)
                {
                    _myProperty = value;
                    NotifyPropertyChanged("MyProperty");
                }
            }
        }
    }

    private NotifyPropertyChanged(string propertyName)
    {
        //Raise PropertyChanged event
    }
    public event PropertyChangedEventHandler PropertyChanged;
}


public class MySubscriber
{
    private MyClass _myClass;        

    void PropertyChangedInMyClass(object sender, PropertyChangedEventArgs e)
    {
        switch(e.PropertyName)
        {
            case "MyProperty":
                DoWorkOnMyProperty(_myClass.MyProperty);
                break;
        }
    }

    void DoWorkOnMyProperty(int newValue)
    {
        if(newValue == 1)
        {
             //DO WORK HERE
        }
    }
}

Hope this is helpful :)

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

How to catch integer(0)?

You can easily catch integer(0) with function identical(x,y)

x = integer(0)
identical(x, integer(0))
[1] TRUE

foo = function(x){identical(x, integer(0))}
foo(x)
[1] TRUE

foo(0)
[1] FALSE

Calculating Distance between two Latitude and Longitude GeoCoordinates

For those who are using Xamarin and don't have access to the GeoCoordinate class, you can use the Android Location class instead:

public static double GetDistanceBetweenCoordinates (double lat1, double lng1, double lat2, double lng2) {
            var coords1 = new Location ("");
            coords1.Latitude = lat1;
            coords1.Longitude = lng1;
            var coords2 = new Location ("");
            coords2.Latitude = lat2;
            coords2.Longitude = lng2;
            return coords1.DistanceTo (coords2);
        }

Call a python function from jinja2

I like @AJP's answer. I used it verbatim until I ended up with a lot of functions. Then I switched to a Python function decorator.

from jinja2 import Template

template = '''
Hi, my name is {{ custom_function1(first_name) }}
My name is {{ custom_function2(first_name) }}
My name is {{ custom_function3(first_name) }}
'''
jinga_html_template = Template(template)

def template_function(func):
    jinga_html_template.globals[func.__name__] = func
    return func

@template_function
def custom_function1(a):
    return a.replace('o', 'ay')

@template_function
def custom_function2(a):
    return a.replace('o', 'ill')

@template_function
def custom_function3(a):
    return 'Slim Shady'

fields = {'first_name': 'Jo'}
print(jinga_html_template.render(**fields))

Good thing functions have a __name__!

What is hashCode used for? Is it unique?

MSDN says:

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table.

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For uniqueness, the hash code must be based on the value of an instance field or property instead of a static field or property.

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections.IHashCodeProvider interface. Starting with version 2.0, the hash code provider is based on the System.Collections.IEqualityComparer interface.

Basically, hash codes exist to make hashtables possible.
Two equal objects are guaranteed to have equal hashcodes.
Two unequal objects are not guaranteed to have unequal hashcodes (that's called a collision).

Hive load CSV with commas in quoted fields

The problem is that Hive doesn't handle quoted texts. You either need to pre-process the data by changing the delimiter between the fields (e.g: with a Hadoop-streaming job) or you can also give a try to use a custom CSV SerDe which uses OpenCSV to parse the files.

Making a UITableView scroll when text field is selected

Keyboard notifications work, but Apple's sample code for that assumes that the scroll view is the root view of the window. This is usually not the case. You have to compensate for tab bars, etc., to get the right offset.

It is easier than it sounds. Here is the code I use in a UITableViewController. It has two instance variables, hiddenRect and keyboardShown.

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    if (keyboardShown)
        return;

    NSDictionary* info = [aNotification userInfo];

    // Get the frame of the keyboard.
    NSValue *centerValue = [info objectForKey:UIKeyboardCenterEndUserInfoKey];
    NSValue *boundsValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGPoint keyboardCenter = [centerValue CGPointValue];
    CGRect keyboardBounds = [boundsValue CGRectValue];
    CGPoint keyboardOrigin = CGPointMake(keyboardCenter.x - keyboardBounds.size.width / 2.0,
                                         keyboardCenter.y - keyboardBounds.size.height / 2.0);
    CGRect keyboardScreenFrame = { keyboardOrigin, keyboardBounds.size };


    // Resize the scroll view.
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = scrollView.frame;
    CGRect keyboardFrame = [scrollView.superview convertRect:keyboardScreenFrame fromView:nil];
    hiddenRect = CGRectIntersection(viewFrame, keyboardFrame);

    CGRect remainder, slice;
    CGRectDivide(viewFrame, &slice, &remainder, CGRectGetHeight(hiddenRect), CGRectMaxYEdge);
    scrollView.frame = remainder;

    // Scroll the active text field into view.
    CGRect textFieldRect = [/* selected cell */ frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];

    keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    // Reset the height of the scroll view to its original value
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = [scrollView frame];
    scrollView.frame = CGRectUnion(viewFrame, hiddenRect);

    keyboardShown = NO;
}

How to have an auto incrementing version number (Visual Studio)?

  • Star in version (like "2.10.3.*") - it is simple, but the numbers are too large

  • AutoBuildVersion - looks great but its dont work on my VS2010.

  • @DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.

so I changed the script a bit... commamd:

"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"

and script (this works to the "Debug" and "Release" configurations):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Including one C source file in another?

you should add header like this

#include <another.c>

note : both file should placed in same place

i use this in codevison AVR for ATMEGA micro controllers and work truly but its not work in normal C language file

How to get different colored lines for different plots in a single figure?

Setting them later

If you don't know the number of the plots you are going to plot you can change the colours once you have plotted them retrieving the number directly from the plot using .lines, I use this solution:

Some random data

import matplotlib.pyplot as plt
import numpy as np

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)


for i in range(1,15):
    ax1.plot(np.array([1,5])*i,label=i)

The piece of code that you need:

colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired   
colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
for i,j in enumerate(ax1.lines):
    j.set_color(colors[i])
  

ax1.legend(loc=2)

The result is the following:enter image description here

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Install msi with msiexec in a Specific Directory

Use TARGETDIR instead of INSTALLDIR. Note that the quote marks for TARGETDIR property are only around the path in the case of spaces.

msiexec /i "msi path" TARGETDIR="C:\myfolder" /qb

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Use a service api.

URL: https://fcm.googleapis.com/fcm/send

Method Type: POST

Headers:

Content-Type: application/json
Authorization: key=your api key

Body/Payload:

{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
  },
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
    },
  "to" : "to_id(firebase refreshedToken)"
} 

And with this in your app you can add below code in your activity to be called:

<intent-filter>
    <action android:name="OPEN_ACTIVITY_1" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Also check the answer on Firebase onMessageReceived not called when app in background

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

Git: "Corrupt loose object"

simply running a git prune fixed this issue for me

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I too faced the same problem, and I did a "Factory data reset", and it worked fine after that.

When creating a service with sc.exe how to pass in context parameters?

I found a way to use sc.

sc config binPath= "\"c:\path with spaces in it\service_executable.exe\" "

In other words, use \ to escape any "'s you want to survive the transit into the registry.

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

Twitter Bootstrap 3: how to use media queries?

If you're using LESS or SCSS/SASS and you're using a LESS/SCSS version of Bootstrap, you can use variables as well, provided you have access to them. A LESS translation of @full-decent's answer would be as follows:

@media(max-width: @screen-xs-max){}
@media(min-width: @screen-sm-min){}  /* deprecated: @screen-tablet, or @screen-sm */
@media(min-width: @screen-md-min){}  /* deprecated: @screen-desktop, or @screen-md */
@media(min-width: @screen-lg-min){}  /* deprecated: @screen-lg-desktop, or @screen-lg */

There are also variables for @screen-sm-max and @screen-md-max, which are 1 pixel less than @screen-md-min and @screen-lg-min, respectively, typically for use with @media(max-width).

EDIT: If you're using SCSS/SASS, variables start with a $ instead of a @, so it'd be $screen-xs-max etc.

Is it better in C++ to pass by value or pass by constant reference?

As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.

SQL to Entity Framework Count Group-By

Edit: EF Core 2.1 finally supports GroupBy

But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.


Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy() for translation to GROUP BY in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.

Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.

For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.

If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.

https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

React Router with optional path parameter

The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.


React Router v1, v2 and v3

Since version 1.0.0 you define optional parameters with:

<Route path="to/page(/:pathParam)" component={MyPage} />

and for multiple optional parameters:

<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />

You use parenthesis ( ) to wrap the optional parts of route, including the leading slash (/). Check out the Route Matching Guide page of the official documentation.

Note: The :paramName parameter matches a URL segment up to the next /, ?, or #. For more about paths and params specifically, read more here.


React Router v4 and above

React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.

Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).

As such, to define an optional parameter, you do:

<Route path="/to/page/:pathParam?" component={MyPage} />

and for multiple optional parameters:

<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />

Note: React Router v4 is incompatible with (read more here). Use version v3 or earlier (v2 recommended) instead.

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}

How can I view live MySQL queries?

You can log every query to a log file really easily:

mysql> SHOW VARIABLES LIKE "general_log%";

+------------------+----------------------------+
| Variable_name    | Value                      |
+------------------+----------------------------+
| general_log      | OFF                        |
| general_log_file | /var/run/mysqld/mysqld.log |
+------------------+----------------------------+

mysql> SET GLOBAL general_log = 'ON';

Do your queries (on any db). Grep or otherwise examine /var/run/mysqld/mysqld.log

Then don't forget to

mysql> SET GLOBAL general_log = 'OFF';

or the performance will plummet and your disk will fill!

How can I list all commits that changed a specific file?

To just get a list of the commit hashes use git rev-list

 git rev-list HEAD <filename>

Output:

b7c4f0d7ebc3e4c61155c76b5ebc940e697600b1
e3920ac6c08a4502d1c27cea157750bd978b6443
ea62422870ea51ef21d1629420c6441927b0d3ea
4b1eb462b74c309053909ab83451e42a7239c0db
4df2b0b581e55f3d41381f035c0c2c9bd31ee98d

which means 5 commits have touched this file. It's reverse chronological order, so the first commit in the list b7c4f0d7 is the most recent one.

Can I make 'git diff' only the line numbers AND changed file names?

Note: if you're just looking for the names of changed files (without the line numbers for lines that were changed), that's easy, click this link to another answer here.


There's no built-in option for this (and I don't think it's all that useful either), but it is possible to do this in git, with the help of an "external diff" script.

Here's a pretty crappy one; it will be up to you to fix up the output the way you would like it.

#! /bin/sh
#
# run this with:
#    GIT_EXTERNAL_DIFF=<name of script> git diff ...
#
case $# in
1) "unmerged file $@, can't show you line numbers"; exit 1;;
7) ;;
*) echo "I don't know what to do, help!"; exit 1;;
esac

path=$1
old_file=$2
old_hex=$3
old_mode=$4
new_file=$5
new_hex=$6
new_mode=$7

printf '%s: ' $path
diff $old_file $new_file | grep -v '^[<>-]'

For details on "external diff" see the description of GIT_EXTERNAL_DIFF in the git manual page (around line 700, pretty close to the end).

How to filter files when using scp to copy dir recursively?

To exclude dotfiles in base directory:

scp -r [!.]* server:/path/to/something

[!.]* is a shell glob that expands to all files in working directory not starting with a dot.

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream; 

// Create a trust manager that does not validate certificate chains like the default 

TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
        }
};

// Install the all-trusting trust manager
try 
{
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} 
catch (Exception e) 
{
    System.out.println(e);
}

Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool e.g. local testing with temporary certifcates.