Programs & Examples On #Suphp

suPHP is a tool for executing PHP scripts with the permissions of their owners.

Where can I find error log files?

For unix cli users:

Most probably the error_log ini entry isn't set. To verify:

php -i | grep error_log
// error_log => no value => no value

You can either set it in your php.ini cli file, or just simply quickly pipe all STDERR yourself to a file:

./myprog 2> myerror.log

Then quickly:

tail -f myerror.log

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

this command gives you a row vector, if you just want to loop over it, it's fine, but if you want to hstack with some other array with dimension 3xN, you will have

ValueError: all the input arrays must have same number of dimensions

while

>>> test[:,[0]]
array([[1],
       [3],
       [5]])

gives you a column vector, so that you can do concatenate or hstack operation.

e.g.

>>> np.hstack((test, test[:,[0]]))
array([[1, 2, 1],
       [3, 4, 3],
       [5, 6, 5]])

How to see top processes sorted by actual memory usage?

You can see memory usage by executing this code in your terminal:

$ watch -n2 free -m
$ htop

How to determine an interface{} value's "real" type?

Type switches can also be used with reflection stuff:

var str = "hello!"
var obj = reflect.ValueOf(&str)

switch obj.Elem().Interface().(type) {
case string:
    log.Println("obj contains a pointer to a string")
default:
    log.Println("obj contains something else")
}

Regex to check whether a string contains only numbers

/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/

How do I change the default location for Git Bash on Windows?

Add "cd your_repos_path" to your Git profile, which is under the %.

Why is "except: pass" a bad programming practice?

Why is “except: pass” a bad programming practice?

Why is this bad?

try:
    something
except:
    pass

This catches every possible exception, including GeneratorExit, KeyboardInterrupt, and SystemExit - which are exceptions you probably don't intend to catch. It's the same as catching BaseException.

try:
    something
except BaseException:
    pass

Older versions of the documentation say:

Since every error in Python raises an exception, using except: can make many programming errors look like runtime problems, which hinders the debugging process.

Python Exception Hierarchy

If you catch a parent exception class, you also catch all of their child classes. It is much more elegant to only catch the exceptions you are prepared to handle.

Here's the Python 3 exception hierarchy - do you really want to catch 'em all?:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
           +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Don't Do this

If you're using this form of exception handling:

try:
    something
except: # don't just do a bare except!
    pass

Then you won't be able to interrupt your something block with Ctrl-C. Your program will overlook every possible Exception inside the try code block.

Here's another example that will have the same undesirable behavior:

except BaseException as e: # don't do this either - same as bare!
    logging.info(e)

Instead, try to only catch the specific exception you know you're looking for. For example, if you know you might get a value-error on a conversion:

try:
    foo = operation_that_includes_int(foo)
except ValueError as e:
    if fatal_condition(): # You can raise the exception if it's bad,
        logging.info(e)   # but if it's fatal every time,
        raise             # you probably should just not catch it.
    else:                 # Only catch exceptions you are prepared to handle.
        foo = 0           # Here we simply assign foo to 0 and continue. 

Further Explanation with another example

You might be doing it because you've been web-scraping and been getting say, a UnicodeError, but because you've used the broadest Exception catching, your code, which may have other fundamental flaws, will attempt to run to completion, wasting bandwidth, processing time, wear and tear on your equipment, running out of memory, collecting garbage data, etc.

If other people are asking you to complete so that they can rely on your code, I understand feeling compelled to just handle everything. But if you're willing to fail noisily as you develop, you will have the opportunity to correct problems that might only pop up intermittently, but that would be long term costly bugs.

With more precise error handling, you code can be more robust.

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

What is the fastest way to send 100,000 HTTP requests in Python?

A solution using tornado asynchronous networking library

from tornado import ioloop, httpclient

i = 0

def handle_request(response):
    print(response.code)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

http_client = httpclient.AsyncHTTPClient()
for url in open('urls.txt'):
    i += 1
    http_client.fetch(url.strip(), handle_request, method='HEAD')
ioloop.IOLoop.instance().start()

How can I get a file's size in C++?

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);

How to add a Hint in spinner in XML

This can be done in a very simple way. Instead of setting the adapter using the built-in values (android.R.layout.simple_list_item_1), create your own xml layout for both TextView and DropDown, and use them. In the TextView layout, define Hint text and Hint color. Last step, create and empty item as the first item in the item array defined in Strings.

<string-array name="professional_qualification_array">
    <item></item>
    <item>B.Pharm</item>
    <item>M.Pharm</item>
    <item>PharmD</item>
</string-array>

Create XML layout for Spinner TextView (spnr_qualification.xml)

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:hint="Qualification"
    android:textColorHint="@color/light_gray"
    android:textColor="@color/blue_black" />

Create XML layout for spinner DropDown.(drpdn_qual.xml)

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:textColor="#FFFFFF"/>

Define spinner in the main XML layout

<Spinner
android:id="@+id/spnQualification"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
/>

And finally in the code, while setting adapter for the spinner, use your custom XML layout.

ArrayAdapter<CharSequence> qual_adapter = ArrayAdapter.createFromResource(this, R.array.professional_qualification_array,R.layout.spnr_qualification);

qual_adapter.setDropDownViewResource(R.layout.drpdn_qual);

spnQualification.setAdapter(qual_adapter)

C# Macro definitions in Preprocessor

Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

How do I deploy Node.js applications as a single executable file?

In addition to nexe, browserify can be used to bundle up all your dependencies as a single .js file. This does not bundle the actual node executable, just handles the javascript side. It too does not handle native modules. The command line options for pure node compilation would be browserify --output bundle.js --bare --dg false input.js.

How to break/exit from a each() function in JQuery?

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

This answer covers a lot of ground, so it’s divided into three parts:

  • How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems
  • How to avoid the CORS preflight
  • How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems

If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin header, you can still get things to work—by making the request through a CORS proxy.

You can easily run your own proxy using code from https://github.com/Rob--W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master

After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/.

Now, prefix your request URL with the URL for your proxy:

https://cryptic-headland-94862.herokuapp.com/https://example.com

Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:

  1. Forwards the request to https://example.com.
  2. Receives the response from https://example.com.
  3. Adds the Access-Control-Allow-Origin header to the response.
  4. Passes that response, with that added header, back to the requesting frontend code.

The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.


How to avoid the CORS preflight

The code in the question triggers a CORS preflight—since it sends an Authorization header.

https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Even without that, the Content-Type: application/json header would also trigger a preflight.

What “preflight” means: before the browser tries the POST in the code in the question, it’ll first send an OPTIONS request to the server — to determine if the server is opting-in to receiving a cross-origin POST that has Authorization and Content-Type: application/json headers.

It works pretty well with a small curl script - I get my data.

To properly test with curl, you must emulate the preflight OPTIONS request the browser sends:

curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" \
    -H 'Access-Control-Request-Method: POST' \
    -H 'Access-Control-Request-Headers: Content-Type, Authorization' \
    "https://the.sign_in.url"

…with https://the.sign_in.url replaced by whatever your actual sign_in URL is.

The response the browser needs to see from that OPTIONS request must have headers like this:

Access-Control-Allow-Origin:  http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization

If the OPTIONS response doesn’t include those headers, then the browser will stop right there and never even attempt to send the POST request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.

The server in the question is responding to the OPTIONS request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for OPTIONS requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.

So you’re never going to be able to make POST requests directly to that server from your frontend JavaScript code if the server responds to that OPTIONS request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.

The way to avoid triggering a preflight for the case in the question would be:

  • if the server didn’t require an Authorization request header but instead, e.g., relied on authentication data embedded in the body of the POST request or as a query param
  • if the server didn’t require the POST body to have a Content-Type: application/json media type but instead accepted the POST body as application/x-www-form-urlencoded with a parameter named json (or whatever) whose value is the JSON data

How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

I am getting another error message:

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

For a request that includes credentials, browsers won’t let your frontend JavaScript code access the response if the value of the Access-Control-Allow-Origin response header is *. Instead the value in that case must exactly match your frontend code’s origin, http://127.0.0.1:3000.

See Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.

If you control the server you’re sending the request to, then a common way to deal with this case is to configure the server to take the value of the Origin request header, and echo/reflect that back into the value of the Access-Control-Allow-Origin response header; e.g., with nginx:

add_header Access-Control-Allow-Origin $http_origin

But that’s just an example; other (web) server systems provide similar ways to echo origin values.


I am using Chrome. I also tried using that Chrome CORS Plugin

That Chrome CORS plugin apparently just simplemindedly injects an Access-Control-Allow-Origin: * header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake Access-Control-Allow-Origin response header to the actual origin of your frontend JavaScript code, http://127.0.0.1:3000.

So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using curl -H as above.


As far as the frontend JavaScript code for the fetch(…) request in the question:

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Remove those lines. The Access-Control-Allow-* headers are response headers. You never want to send them in a request. The only effect that’ll have is to trigger a browser to do a preflight.

How to use OpenCV SimpleBlobDetector

Note: all the examples here are using the OpenCV 2.X API.

In OpenCV 3.X, you need to use:

Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);

See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers

How to bind Close command to a button

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
{
    public bool Close
    {
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.Close)
        {
            this.AssociatedObject.Close();
        }
    }
}

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
    <behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

How to build PDF file from binary string returned from a web-service using javascript

You can use PDF.js to create PDF files from javascript... it's easy to code... hope this solve your doubt!!!

Regards!

How to get the name of a class without the package?

The following function will work in JDK version 1.5 and above.

public String getSimpleName()

How do I get the find command to print out the file size with the file name?

Why not use du -a ? E.g.

find . -name "*.ear" -exec du -a {} \;

Works on a Mac

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Rather than using JavaScript perhaps try something like

<a href="#">

  <input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />

</a>

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Generally these are either:

Lossless compression Lossless compression algorithms reduce file size without losing image quality, though they are not compressed into as small a file as a lossy compression file. When image quality is valued above file size, lossless algorithms are typically chosen.

Lossy compression Lossy compression algorithms take advantage of the inherent limitations of the human eye and discard invisible information. Most lossy compression algorithms allow for variable quality levels (compression) and as these levels are increased, file size is reduced. At the highest compression levels, image deterioration becomes noticeable as "compression artifacting". The images below demonstrate the noticeable artifacting of lossy compression algorithms; select the thumbnail image to view the full size version.

Each format is different as described below:

JPEG JPEG (Joint Photographic Experts Group) files are (in most cases) a lossy format; the DOS filename extension is JPG (other OS might use JPEG). Nearly every digital camera can save images in the JPEG format, which supports 8 bits per color (red, green, blue) for a 24-bit total, producing relatively small files. When not too great, the compression does not noticeably detract from the image's quality, but JPEG files suffer generational degradation when repeatedly edited and saved. Photographic images may be better stored in a lossless non-JPEG format if they will be re-edited, or if small "artifacts" (blemishes caused by the JPEG's compression algorithm) are unacceptable. The JPEG format also is used as the image compression algorithm in many Adobe PDF files.

TIFF The TIFF (Tagged Image File Format) is a flexible format that normally saves 8 bits or 16 bits per color (red, green, blue) for 24-bit and 48-bit totals, respectively, using either the TIFF or the TIF filenames. The TIFF's flexibility is both blessing and curse, because no single reader reads every type of TIFF file. TIFFs are lossy and lossless; some offer relatively good lossless compression for bi-level (black&white) images. Some digital cameras can save in TIFF format, using the LZW compression algorithm for lossless storage. The TIFF image format is not widely supported by web browsers. TIFF remains widely accepted as a photograph file standard in the printing business. The TIFF can handle device-specific colour spaces, such as the CMYK defined by a particular set of printing press inks.

PNG The PNG (Portable Network Graphics) file format was created as the free, open-source successor to the GIF. The PNG file format supports truecolor (16 million colours) while the GIF supports only 256 colours. The PNG file excels when the image has large, uniformly coloured areas. The lossless PNG format is best suited for editing pictures, and the lossy formats, like JPG, are best for the final distribution of photographic images, because JPG files are smaller than PNG files. Many older browsers currently do not support the PNG file format, however, with Internet Explorer 7, all contemporary web browsers fully support the PNG format. The Adam7-interlacing allows an early preview, even when only a small percentage of the image data has been transmitted.

GIF GIF (Graphics Interchange Format) is limited to an 8-bit palette, or 256 colors. This makes the GIF format suitable for storing graphics with relatively few colors such as simple diagrams, shapes, logos and cartoon style images. The GIF format supports animation and is still widely used to provide image animation effects. It also uses a lossless compression that is more effective when large areas have a single color, and ineffective for detailed images or dithered images.

BMP The BMP file format (Windows bitmap) handles graphics files within the Microsoft Windows OS. Typically, BMP files are uncompressed, hence they are large; the advantage is their simplicity, wide acceptance, and use in Windows programs.

Use for Web Pages / Web Applications

The following is a brief summary for these image formats when using them with a web page / application.

  • PNG is great for IE6 and up (will require a small CSS patch to get transparency working well). Great for illustrations and photos.
  • JPG is great for photos online
  • GIF is good for illustrations when you do not wish to move to PNG
  • BMP shouldn't be used online within web pages - wastes bandwidth


  • Source: Image File Formats

    How to set JAVA_HOME in Linux for all users

    On Linux I add this line to my ~/.profile:

    export JAVA_HOME=$(readlink -ze /usr/bin/javac | xargs -0 dirname -z | xargs -0 dirname)
    

    Interface type check with Typescript

    How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html

    interface Bird {
        fly();
        layEggs();
    }
    
    interface Fish {
        swim();
        layEggs();
    }
    
    function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
        return (<Fish>pet).swim !== undefined;
    }
    
    // Both calls to 'swim' and 'fly' are now okay.
    
    if (isFish(pet)) {
        pet.swim();
    }
    else {
        pet.fly();
    }
    

    Android - Back button in the title bar

    I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.

    1) Stardard android compatiblity

    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.core.app.NavUtils;
    
    import android.view.MenuItem;
    import android.view.View;
    
    public class EditDiscoveryActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_edit_discovery);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            /*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });*/
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    
        @Override
        public boolean onSupportNavigateUp() {
            onBackPressed();
            return true;
        }
    
    }
    

    2) Use a custom icon

    If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml

    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#ffffff"
            android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
        </vector>
    

    With this code.

    toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    

    Hope it will helps some people here !

    AngularJS: How can I pass variables between controllers?

    Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

    https://github.com/gsklee/ngStorage

    Define your defaults:

    $scope.$storage = $localStorage.$default({
        prop1: 'First',
        prop2: 'Second'
    });
    

    Access the values:

    $scope.prop1 = $localStorage.prop1;
    $scope.prop2 = $localStorage.prop2;
    

    Store the values

    $localStorage.prop1 = $scope.prop1;
    $localStorage.prop2 = $scope.prop2;
    

    Remember to inject ngStorage in your app and $localStorage in your controller.

    Nested lists python

    If you really need the indices you can just do what you said again for the inner list:

    l = [[2,2,2],[3,3,3],[4,4,4]]
    for index1 in xrange(len(l)):
        for index2 in xrange(len(l[index1])):
            print index1, index2, l[index1][index2]
    

    But it is more pythonic to iterate through the list itself:

    for inner_l in l:
        for item in inner_l:
            print item
    

    If you really need the indices you can also use enumerate:

    for index1, inner_l in enumerate(l):
        for index2, item in enumerate(inner_l):
            print index1, index2, item, l[index1][index2]
    

    Visual Studio 2013 License Product Key

    I solved this, without having to completely reinstall Visual Studio 2013.

    For those who may come across this in the future, the following steps worked for me:

    1. Run the ISO (or vs_professional.exe).
    2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

      • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

      • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

        HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

      • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

      • Exit the registry

    3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

      Visual Studio Repair button

      • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
    4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

    5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


    Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

    License: Product key applied

    Hope this helps somebody in the future!

    Reference blog 'story'

    Calculating distance between two points, using latitude longitude?

    was a lot of great answers provided however I found some performance shortcomings, so let me offer a version with performance in mind. Every constant is precalculated and x,y variables are introduced to avoid calculating the same value twice. Hope it helps

        private static final double r2d = 180.0D / 3.141592653589793D;
        private static final double d2r = 3.141592653589793D / 180.0D;
        private static final double d2km = 111189.57696D * r2d;
        public static double meters(double lt1, double ln1, double lt2, double ln2) {
            double x = lt1 * d2r;
            double y = lt2 * d2r;
            return Math.acos( Math.sin(x) * Math.sin(y) + Math.cos(x) * Math.cos(y) * Math.cos(d2r * (ln1 - ln2))) * d2km;
        }
    

    How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

    A bit of pandas code:

    import pandas
    
    def to_millis(dt):
        return int(pandas.to_datetime(dt).value / 1000000)
    

    Warning: implode() [function.implode]: Invalid arguments passed

    It happens when $ret hasn't been defined. The solution is simple. Right above $tags = get_tags();, add the following line:

    $ret = array();
    

    Flutter - Wrap text on overflow, like insert ellipsis or fade

    Using Ellipsis

    Text(
      "This is a long text",
      overflow: TextOverflow.ellipsis,
    ),
    

    enter image description here


    Using Fade

    Text(
      "This is a long text",
      overflow: TextOverflow.fade,
      maxLines: 1,
      softWrap: false,
    ),
    

    enter image description here


    Using Clip

    Text(
      "This is a long text",
      overflow: TextOverflow.clip,
      maxLines: 1,
      softWrap: false,
    ),
    

    enter image description here


    Note:

    If you are using Text inside a Row, you can put above Text inside Expanded like:

    Expanded(
      child: AboveText(),
    )
    

    Append an int to a std::string

    You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

    from cplusplus.com :

    string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

    PostgreSQL - SQL state: 42601 syntax error

    Your function would work like this:

    CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
    RETURNS TABLE (name text, rowcount integer) AS 
    $$
    BEGIN
    
    RETURN QUERY EXECUTE '
    WITH v_tb_person AS (' || sql || $x$)
    SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
    UNION
    SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
    
    END     
    $$ LANGUAGE plpgsql;
    

    Call:

    SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
    
    • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

    • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

    • I use dollar quoting to avoid quoting hell.

    However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

    Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

    The query itself seems rather odd, btw. But that's beside the point here.

    Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

    1. Show where memory is allocated sudo du -x -h / | sort -h | tail -40
    2. Delete from either your /tmp or /home/user_name/.cache folder if these are taking up a lot of memory. You can do this by running sudo rm -R /path/to/folder

    Step 2 outlines fairly common folders to delete from (/tmp and /home/user_name/.cache). If you get back other results when running the first command showing you have lots of memory being used elsewhere, I advise being a bit more cautious when deleting from those locations.

    Slack URL to open a channel from browser

    Sure you can:

    https://<organization>.slack.com/messages/<channel>/

    for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)

    How to install a specific version of a ruby gem?

    You can use the -v or --version flag. For example

    gem install bitclock -v '< 0.0.2'
    

    To specify upper AND lower version boundaries you can specify the --version flag twice

    gem install bitclock -v '>= 0.0.1' -v '< 0.0.2'
    

    or use the syntax (for example)

    gem install bitclock -v '>= 0.0.1, < 0.0.2'
    

    The other way to do it is

    gem install bitclock:'>= 0.0.1'
    

    but with the last option it is not possible to specify upper and lower bounderies simultaneously.

    [gem 3.0.3 and ruby 2.6.6]

    How to recursively list all the files in a directory in C#?

    In Framework 2.0 you can use (It list files of root folder, it's best the most popular answer):

    static void DirSearch(string dir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(dir))
                Console.WriteLine(f);
            foreach (string d in Directory.GetDirectories(dir))
            {
                Console.WriteLine(d);
                DirSearch(d);
            }
    
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

    How do I type a TAB character in PowerShell?

    TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

    From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

    Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

    Beware when comparing a .Net DateTime to SqlDateTime.MinValue or MaxValue. For example, the following will throw an exception:

    DateTime dte = new DateTime(1000, 1, 1);
    if (dte >= SqlDateTime.MinValue)
        //do something
    

    The reason is that MinValue returns a SqlDateTime, not a DateTime. So .Net tries to convert dte to a SqlDateTime for comparison and because it's outside the acceptable SqlDateTime range it throws the exception.

    One solution to this is to compare your DateTime to SqlDateTime.MinValue.Value.

    Select last N rows from MySQL

    You can do it with a sub-query:

    SELECT * FROM (
        SELECT * FROM table ORDER BY id DESC LIMIT 50
    ) sub
    ORDER BY id ASC
    

    This will select the last 50 rows from table, and then order them in ascending order.

    Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

    I experienced the same issue when trying to install tensorflow from a jupyter notebook using Anaconda. --user did not work.

    conda install tensorflow worked for me, and I didn't have to change any security settings.

    How can I put CSS and HTML code in the same file?

    <html>
    <head>
        <style type="text/css">
        .title {
            color: blue;
            text-decoration: bold;
            text-size: 1em;
        }
    
        .author {
            color: gray;
        }
        </style>
    </head>
    <body>
        <p>
        <span class="title">La super bonne</span>
        <span class="author">proposée par Jérém</span>
        </p>
    </body>
    </html>
    

    On a side note, it would have been much easier to just do this.

    Python truncate a long string

    For a Django solution (which has not been mentioned in the question):

    from django.utils.text import Truncator
    value = Truncator(value).chars(75)
    

    Have a look at Truncator's source code to appreciate the problem: https://github.com/django/django/blob/master/django/utils/text.py#L66

    Concerning truncation with Django: Django HTML truncation

    How to comment lines in rails html.erb files?

    This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

    The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


    1. CONTIGUOUS NON-PRINTING Ruby Code

      • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

      • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

      • DETAILS:

        Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

          <%# if flash[:myErrors] %>
            <%# if flash[:myErrors].any? %>
              <%# if @post.id.nil? %>
                <%# if @myPost!=-1 %>
                  <%# @post = @myPost %>
                <%# else %>
                  <%# @post = Post.new %>
                <%# end %>
              <%# end %>
            <%# end %>
          <%# end %>
        

        YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

          <%# 
            if flash[:myErrors] then
              if flash[:myErrors].any? then
                if @post.id.nil? then
                  if @myPost!=-1 then
                    @post = @myPost 
                  else 
                    @post = Post.new 
                  end 
                end 
              end 
            end 
          %>
        

    How to resolve ambiguous column names when retrieving results?

    I just figured this out. It's probably a bad practice but it worked for me in this case.

    I am one of the lazy people who doesn't want to alias or write out every column name with a table prefix.

    You can select all of the columns from a specific table by using table_name.* in your select statement.

    When you have duplicated column names, mysql will overwrite from first to last. The data from the first duplicated column name will be overwritten when it encounters that column name again. So the duplicate column name that comes in last wins.

    If I am joining 3 tables, each containing a duplicated column name, the order of the tables in the select statement will determine what data I am getting for the duplicate column.

    Example:

    SELECT table1.* , table2.* , table3.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;
    

    In the example above, the value of dup I get will be from table3.

    What if I want dup to be the value from table1?

    Then I need to do this:

    SELECT table3.* , table2.* , table1.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;
    

    Now, table1 comes last, so the value of dup will be the value from table1.

    I got the value I wanted for dup without having to write out every single freaking column and I still get all of the columns to work with. Yay!

    I know the value of dup should be the same in all 3 tables, but what if table3 doesn't have a matching value for dup? Then dup would be blank in the first example, and that would be a bummer.

    How to retrieve inserted id after inserting row in SQLite using Python?

    All credits to @Martijn Pieters in the comments:

    You can use the function last_insert_rowid():

    The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

    How do I create a master branch in a bare Git repository?

    You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

    Prepare a dummy directory:

    $ rm -rf /tmp/empty_directory
    $ mkdir  /tmp/empty_directory
    

    Create the master branch without a parent (works even on a completely empty repo):

    $ cd your-bare-repository.git
    
    $ git checkout --work-tree=/tmp/empty_directory --orphan master
    Switched to a new branch 'master'                  <--- abort if "master" already exists
    

    Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

    $ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 
    
    $ git branch
    * master
    

    Clean up the directory, it is still empty.

    $ rmdir  /tmp/empty_directory
    

    Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

    Saving and Reading Bitmaps/Images from Internal memory in Android

    Use the below code to save the image to internal directory.

    private String saveToInternalStorage(Bitmap bitmapImage){
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
             // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            File mypath=new File(directory,"profile.jpg");
    
            FileOutputStream fos = null;
            try {           
                fos = new FileOutputStream(mypath);
           // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {
                try {
                  fos.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
            } 
            return directory.getAbsolutePath();
        }
    

    Explanation :

    1.The Directory will be created with the given name. Javadocs is for to tell where exactly it will create the directory.

    2.You will have to give the image name by which you want to save it.

    To Read the file from internal memory. Use below code

    private void loadImageFromStorage(String path)
    {
    
        try {
            File f=new File(path, "profile.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
                ImageView img=(ImageView)findViewById(R.id.imgPicker);
            img.setImageBitmap(b);
        } 
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    
    }
    

    How to fade changing background image

    This was the only reasonable thing I found to fade a background image.

    <div id="foo">
      <!-- some content here -->
    </div>
    

    Your CSS; now enhanced with CSS3 transition.

    #foo {
      background-image: url(a.jpg);
      transition: background 1s linear;
    }
    

    Now swap out the background

    document.getElementById("foo").style.backgroundImage = "url(b.jpg)";
    

    Voilà, it fades!


    Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

    Curl : connection refused

    Make sure you have a service started and listening on the port.

    netstat -ln | grep 8080
    

    and

    sudo netstat -tulpn
    

    System.Data.OracleClient requires Oracle client software version 8.1.7

    I've run into this error dozens of times:

    Cause

    Security permissions were not properly set when the Oracle client was installed on Windows with NTFS. The result of this is that content of the ORACLE_HOME directory is not visible to Authenticated Users on the machine; this causes an error while the System.Data.OracleClient is communicating with the Oracle Connectivity software from ASP.NET using Authenticated User privileges.

    Solution

    To fix the problem you have to give the Authenticated Users group privilege to the Oracle Home directory.

    • Log on to Windows as a user with Administrator privileges.
    • Start Windows Explorer and navigate to the ORACLE_HOME folder.
    • Choose properties on the ORACLE_HOME folder.
    • Click the Security tab of the Properties window.
    • Click on Authenticated Users item in the Name list.
    • Un-check the Read and Execute box in the Permissions list under the Allow column.
    • Re-check the Read and Execute box under the Allow column.
    • Click the Advanced button and in the Permission Entries verify that Authenticated Users are listed with permission: Read & Execute, and Apply To: This folder, subfolders and files. If not, edit that line and make sure that Apply To drop-down box is set to This folder, subfolders and files. This should already be set properly but it is important that you verify it.
    • Click the OK button until you close out all of the security properties windows. The cursor may present the hour glass for a few seconds as it applies the permissions you just changed to all subfolders and files.
    • Reboot, to assure that the changes have taken effect.

    Try your application again.

    How to call a JavaScript function, declared in <head>, in the body when I want to call it

    You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

    How do I remove the old history from a git repository?

    When rebase or push to head/master this error may occurred

    remote: GitLab: You are not allowed to access some of the refs!
    To git@giturl:main/xyz.git
     ! [remote rejected] master -> master (pre-receive hook declined)
    error: failed to push some refs to 'git@giturl:main/xyz.git'
    

    To resolve this issue in git dashboard should remove master branch from "Protected branches"

    enter image description here

    then you can run this command

    git push -f origin master
    

    or

    git rebase --onto temp $1 master
    

    Is it possible to access to google translate api for free?

    Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

    UPD 19.03.2019 Here is a version for browser on GitHub.

    Format JavaScript date as yyyy-mm-dd

    new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                     (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
    

    How to convert date to string and to date again?

    Use DateFormat#parse(String):

    Date date = dateFormat.parse("2013-10-22");
    

    How to dynamically remove items from ListView on a button click?

    Have a button on list and let it onclick feature in xml like to get postion first

    public void OnClickButton(View V){
      final int postion = listView.getPositionForView(V);
        System.out.println("postion selected is : "+postion);
    Delete(postion);
    
    }
    public void Delete(int position){
        if (adapter.getCount() > 0) {
    
            //Log.d("largest no is",""+largestitemno);
            //deleting the latest added by subtracting one 1 
            comment = (GenrricStoring) adapter.getItem(position);
            //Log.d("Deleting item is: ",""+comment);
            dbconnection.deleteComment(comment);
            List<GenrricStoring> values = dbconnection.getAllComments();
            //updating the content on the screen
            this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
            listView.setAdapter(adapter);
        }
        else
        {
            int duration = Toast.LENGTH_SHORT;
            //for showing nothing is left in the list
            Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
    
            toast.show();
        }
    
    }
    

    Removing numbers from string

    And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

    For Python 2:

    from string import digits
    
    s = 'abc123def456ghi789zero0'
    res = s.translate(None, digits)
    # 'abcdefghizero'
    

    For Python 3:

    from string import digits
    
    s = 'abc123def456ghi789zero0'
    remove_digits = str.maketrans('', '', digits)
    res = s.translate(remove_digits)
    # 'abcdefghizero'
    

    android asynctask sending callbacks to ui

    You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

    For example:

    Your interface:

    public interface OnTaskCompleted{
        void onTaskCompleted();
    }
    

    Your Activity:

    public class YourActivity implements OnTaskCompleted{
        // your Activity
    }
    

    And your AsyncTask:

    public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
        private OnTaskCompleted listener;
    
        public YourTask(OnTaskCompleted listener){
            this.listener=listener;
        }
    
        // required methods
    
        protected void onPostExecute(Object o){
            // your stuff
            listener.onTaskCompleted();
        }
    }
    

    EDIT

    Since this answer got quite popular, I want to add some things.

    If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

    • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
    • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
    • Convoluted code which does everything in Activity

    When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

    File Upload using AngularJS

    I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!

    <input type="file" multiple ng-simple-upload web-api-url="/api/Upload" callback-fn="myCallback" />
    

    ng-simple-upload more on Github with an example using Web API.

    Bootstrap Align Image with text

    Try using .pull-left to left align image along with text.

    Ex:

    <p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>
    

    String formatting in Python 3

    Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

    f"({self.goals} goals, ${self.penalties})"
    

    This is similar to the previous .format standard, but lets one easily do things like:

    >>> width = 10
    >>> precision = 4
    >>> value = decimal.Decimal('12.34567')
    >>> f'result: {value:{width}.{precision}}'
    'result:      12.35'
    

    Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

    This happens when you try to run the Angular command "ng s" or "ng serve" on the other folder instead of the root folder of the Angular application.

    Also upgrade the Angular using the following command:

    ng update @angular/cli --migrate-only --from=1.7.4
    

    This will sort it out.

    Get top most UIViewController

    The best solution for me is an extension with a function. Create a swift file with this extension

    First is the UIWindow extension:

    public extension UIWindow {
        var visibleViewController: UIViewController? {
            return UIWindow.visibleVC(vc: self.rootViewController)
        }
    
        static func visibleVC(vc: UIViewController?) -> UIViewController? {
            if let navigationViewController = vc as? UINavigationController {
                return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
            } else if let tabBarVC = vc as? UITabBarController {
                return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
            } else {
                if let presentedVC = vc?.presentedViewController {
                    return UIWindow.visibleVC(vc: presentedVC)
                } else {
                    return vc
                }
            }
        }
    }
    

    inside that file add function

    func visibleViewController() -> UIViewController? {
        let appDelegate = UIApplication.shared.delegate
        if let window = appDelegate!.window {
            return window?.visibleViewController
        }
        return nil
    }
    

    And if you want to use it, you can call it anywhere. Example:

      override func viewDidLoad() {
        super.viewDidLoad()
          if let topVC = visibleViewController() {
                 //show some label or text field 
        }
    }
    

    File code is like this:

    import UIKit
    
    public extension UIWindow {
        var visibleViewController: UIViewController? {
            return UIWindow.visibleVC(vc: self.rootViewController)
        }
    
        static func visibleVC(vc: UIViewController?) -> UIViewController? {
            if let navigationViewController = vc as? UINavigationController {
                return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
            } else if let tabBarVC = vc as? UITabBarController {
                return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
            } else {
                if let presentedVC = vc?.presentedViewController {
                    return UIWindow.visibleVC(vc: presentedVC)
                } else {
                    return vc
                }
            }
        }
    }
    
    func visibleViewController() -> UIViewController? {
        let appDelegate = UIApplication.shared.delegate
        if let window = appDelegate!.window {
            return window?.visibleViewController
        }
        return nil
    }
    

    Change keystore password from no password to a non blank password

    Add -storepass to keytool arguments.

    keytool -storepasswd -storepass '' -keystore mykeystore.jks
    

    But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

    $JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
    

    Difference between DOM parentNode and parentElement

    Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

    console.log(document.body.parentNode, "is body's parent node");    // returns <html>
    console.log(document.body.parentElement, "is body's parent element"); // returns <html>
    
    var html = document.body.parentElement;
    console.log(html.parentNode, "is html's parent node"); // returns document
    console.log(html.parentElement, "is html's parent element"); // returns null
    

    How to disable Hyper-V in command line?

    This command works

    Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All
    

    Run it then agree to restart the computer when prompted.

    I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.

    Why do we need the "finally" clause in Python?

    I was trying to run a code where i wanted to read excel sheets. Issue was, if there is a file which has no sheet named say : SheetSum I am not able to move it to error location!! Code i wrote was:

    def read_file(data_file):
        # data_file = '\rr\ex.xlsx'
        sheets = {}
        try:
            print("Reading file: "+data_file)
            sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
        except Exception as excpt:
            print("Exception occurred", exc_info=True)
        return sheets
    
    read_file(file)
    shutil.move( file, dirpath +'\\processed_files')
    

    Giving Error :

    [WinError 32] The process cannot access the file because it is being used by another process

    I had to add full try except with finally block and tell finally i need to close the file in any case like:

    def read_file(data_file):
        # data_file = '\rr\ex.xlsx'
        sheets = {}
        try:
            print("Reading file: "+data_file)
            sheets_file = open(data_file,'rb')
            sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
        except Exception as excpt:
            print("Exception occurred", exc_info=True)
        finally:
            sheets_file.close()
        return sheets
    
    read_file(file)
    shutil.move( file, dirpath +'\\processed_files')
    

    Otherwise, file still remains open is the background.

    If finally is present, it specifies a cleanup handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.

    ..More Here

    Manipulate a url string by adding GET parameters

    Use strpos to detect a ?. Since ? can only appear in the URL at the beginning of a query string, you know if its there get params already exist and you need to add params using &

    function addGetParamToUrl(&$url, $varName, $value)
    {
        // is there already an ?
        if (strpos($url, "?"))
        {
            $url .= "&" . $varName . "=" . $value; 
        }
        else
        {
            $url .= "?" . $varName . "=" . $value;
        }
    }
    

    c++ parse int from string

    You can use boost::lexical_cast:

    #include <iostream>
    #include <boost/lexical_cast.hpp>
    
    int main( int argc, char* argv[] ){
    std::string s1 = "10";
    std::string s2 = "abc";
    int i;
    
       try   {
          i = boost::lexical_cast<int>( s1 );
       }
       catch( boost::bad_lexical_cast & e ){
          std::cout << "Exception caught : " << e.what() << std::endl;
       }
    
       try   {
          i = boost::lexical_cast<int>( s2 );
       }
       catch( boost::bad_lexical_cast & e ){
          std::cout << "Exception caught : " << e.what() << std::endl;
       }
    
       return 0;
    }
    

    How can I display a messagebox in ASP.NET?

    just try this, it works fine in my browser:

    your response writing code should be

    Response.Write("<script>alert('login successful');</script>");
    

    Hope this works

    Center align "span" text inside a div

    You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

    You could give the span a set width, then add the margin:0 auto again. This would center-align it.

    .left 
    {
       background-color: #999999;
       height: 50px;
       width: 24.5%;
    }
    span.panelTitleTxt 
    {
       display:block;
       width:100px;
       height: 100%;
       margin: 0 auto;
    }
    

    Understanding the Gemfile.lock file

    Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

    Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem).

    Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically.

    Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency.

    When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation.

    Same happens when you share your code with different machines

    You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines

    Why do we need to maintain consistency along multiple machines ?

    • Running different versions on different machines could lead to broken code

    • Suppose, your app used the version 1.5.3 and it works 14 months ago
      without any problems, and you try to install on different machine
      without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will
      fail. Maintaining consistency is of utmost importance (preferred
      practice).

    It is also possible to update gem(s) in Gemfile.lock by using bundle update.

    This is based on the concept of conservative updating

    Bootstrap 3 .col-xs-offset-* doesn't work?

    Its not working because col-xs-offset-* is mentioned out of the media query. if you want to use it, you have to mention all the offset (eg: class="col-xs-offset-3 col-sm-offset-2 col-md-offset-1 col-lg-offset-0")

    But this is not right, they should mention col-xs-offset-* in the media query

    DateTime vs DateTimeOffset

    This piece of code from Microsoft explains everything:

    // Find difference between Date.Now and Date.UtcNow
      date1 = DateTime.Now;
      date2 = DateTime.UtcNow;
      difference = date1 - date2;
      Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
    
      // Find difference between Now and UtcNow using DateTimeOffset
      dateOffset1 = DateTimeOffset.Now;
      dateOffset2 = DateTimeOffset.UtcNow;
      difference = dateOffset1 - dateOffset2;
      Console.WriteLine("{0} - {1} = {2}", 
                        dateOffset1, dateOffset2, difference);
      // If run in the Pacific Standard time zone on 4/2/2007, the example
      // displays the following output to the console:
      //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
      //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
    

    How can I update the current line in a C# Windows Console App?

    You can use the \b (backspace) escape sequence to backup a particular number of characters on the current line. This just moves the current location, it does not remove the characters.

    For example:

    string line="";
    
    for(int i=0; i<100; i++)
    {
        string backup=new string('\b',line.Length);
        Console.Write(backup);
        line=string.Format("{0}%",i);
        Console.Write(line);
    }
    

    Here, line is the percentage line to write to the console. The trick is to generate the correct number of \b characters for the previous output.

    The advantage of this over the \r approach is that if works even if your percentage output is not at the beginning of the line.

    PHP Parse HTML code

    Use PHP Document Object Model:

    <?php
       $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
       $DOM = new DOMDocument;
       $DOM->loadHTML($str);
    
       //get all H1
       $items = $DOM->getElementsByTagName('h1');
    
       //display all H1 text
       for ($i = 0; $i < $items->length; $i++)
            echo $items->item($i)->nodeValue . "<br/>";
    ?>
    

    This outputs as:

     T1
     T2
     T3
    

    [EDIT]: After OP Clarification:

    If you want the content like Lorem ipsum. etc, you can directly use this regex:

    <?php
       $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
       echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
    ?>
    

    this outputs:

    Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

    replacing text in a file with Python

    This is a short and simple example I just used:

    If:

    fp = open("file.txt", "w")
    

    Then:

    fp.write(line.replace('is', 'now'))
    // "This is me" becomes "This now me"
    

    Not:

    line.replace('is', 'now')
    fp.write(line)
    // "This is me" not changed while writing
    

    remove objects from array by object property

    With lodash/underscore:

    If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:

    var items= [{id:'abc',name:'oh'}, // delete me
                      {id:'efg',name:'em'},
                      {id:'hij',name:'ge'}];
    
    items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);
    

    With ES5 or higher

    (without lodash/underscore)

    With ES5 onwards we have findIndex method on array, so its easier without lodash/underscore

    items.splice(items.findIndex(function(i){
        return i.id === "abc";
    }), 1);
    

    (ES5 is supported in almost all morden browsers)

    About findIndex, and its Browser compatibility

    How to disassemble a binary executable in Linux to get the assembly code?

    You might find ODA useful. It's a web-based disassembler that supports tons of architectures.

    http://onlinedisassembler.com/

    Displaying the Indian currency symbol on a website

    WebRupee API Available Here:

    <script src="http://cdn.jagansindia.in/webrupee" type="text/javascript"></script>
    

    You can also read full details here

    SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

    In my case, everything was set up correctly, but my Docker infrastructure needed more RAM. I'm using Docker for Mac, where default RAM was around 1 GB, and as MySQL uses around 1.5Gb of RAM ( and probably was crashing ??? ), changing the Docker RAM utilization level to 3-4 Gb solved the issue.

    Multiple distinct pages in one HTML file

    have all the pages in distinct div areas

    <div style="" id="page1">
    First Page Contents
    </div>
    
    <div style="display:none" id="page2">
    Second Page Contents
    </div>
    

    then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like /pages/page1.html)

    var $prehashval = "";
    function loop()
    {
        if (location.hash.slice(1)!=$prehashval)
            hashChanged();
    
        $prehashval = location.hash.slice(1);
        setTimeout("loop()", 100);
    }
    function hashChanged()
    {
        var $output;
        switch (location.hash.slice(1))
        {
            case "page1":
                document.getElementById('page1').style.display = "";
                document.getElementById('page2').style.display = "none";
                break;
            case "page2":
                document.getElementById('page1').style.display = "none";
                document.getElementById('page2').style.display = "";
                break;
            default:
                $output = location.hash.slice(1);
        }
    }
    loop();
    

    Adding an onclick function to go to url in JavaScript?

    HTML

    <input type="button" value="My Button" 
    onclick="location.href = 'https://myurl'" />
    

    MVC

    <input type="button" value="My Button" 
    onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />
    

    How to refresh datagrid in WPF

    From MSDN -

    CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();
    

    Permutation of array

    If you're using C++, you can use std::next_permutation from the <algorithm> header file:

    int a[] = {3,4,6,2,1};
    int size = sizeof(a)/sizeof(a[0]);
    std::sort(a, a+size);
    do {
      // print a's elements
    } while(std::next_permutation(a, a+size));
    

    How can I iterate JSONObject to get individual items

    You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

    public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
        Iterator<String> keys = json.keys();
        while(keys.hasNext()){
            String key = keys.next();
            String val = null;
            try{
                 JSONObject value = json.getJSONObject(key);
                 parse(value,out);
            }catch(Exception e){
                val = json.getString(key);
            }
    
            if(val != null){
                out.put(key,val);
            }
        }
        return out;
    }
    
     public static void main(String[] args) throws JSONException {
    
        String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
    
        JSONObject object = new JSONObject(json);
    
        JSONObject info = object.getJSONObject("ipinfo");
    
        Map<String,String> out = new HashMap<String, String>();
    
        parse(info,out);
    
        String latitude = out.get("latitude");
        String longitude = out.get("longitude");
        String city = out.get("city");
        String state = out.get("state");
        String country = out.get("country");
        String postal = out.get("postal_code");
    
        System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
    
        System.out.println("ALL VALUE " + out);
    
    }
    

    Output:

        Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
    ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
    

    JOptionPane Yes or No window

    You are always checking for a true condition, hence your message will always show.

    You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

    When one of the showXxxDialog methods returns an integer, the possible values are:

    YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

    From here

    linux: kill background task

    Just use the killall command:

    killall taskname

    for more info and more advanced options, type "man killall".

    Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

    I don't know whether this is efficient or not but I would like to suggest this solution.

    1. Compute xor of the 100 elements
    2. Compute xor of the 98 elements (after the 2 elements are removed)
    3. Now (result of 1) XOR (result of 2) gives you the xor of the two missing nos i..e a XOR b if a and b are the missing elements
      4.Get the sum of the missing Nos with your usual approach of the sum formula diff and lets say the diff is d.

    Now run a loop to get the possible pairs (p,q) both of which lies in [1 , 100] and sum to d.

    When a pair is obtained check whether (result of 3) XOR p = q and if yes we are done.

    Please correct me if I am wrong and also comment on time complexity if this is correct

    How to make a div have a fixed size?

    Try the following css:

    #innerbox
    {
       width:250px; /* or whatever width you want. */
       max-width:250px; /* or whatever width you want. */
       display: inline-block;
    }
    

    This makes the div take as little space as possible, and its width is defined by the css.

    // Expanded answer

    To make the buttons fixed widths do the following :

    #innerbox input
    {
       width:150px; /* or whatever width you want. */
       max-width:150px; /* or whatever width you want. */
    }
    

    However, you should be aware that as the size of the text changes, so does the space needed to display it. As such, it's natural that the containers need to expand. You should perhaps review what you are trying to do; and maybe have some predefined classes that you alter on the fly using javascript to ensure the content placement is perfect.

    W3WP.EXE using 100% CPU - where to start?

    1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
    2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
    3. Load testing, using tools such as Visual Studio Team Test or WCAT
    4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
    5. Use logparser to see which requests arrived at the time of the CPU spike
    6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
    7. CPU and memory profiling (can be difficult on a production system)
    8. Process Explorer
    9. Windows Resource Monitor
    10. Detailed error logging
    11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
    12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

    Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

    import UIkit 
    
    extension UITextField
    
    {
    
    func underlinedLogin()
    
    {
    
        let border = CALayer()
    
        let width = CGFloat(1.0)
    
        border.borderColor = UIColor.black.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
        border.borderWidth = width
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }
    

    }

    call method on viewdidload

    mobileNumberTextField.underlinedLogin()

    passwordTextField.underlinedLogin()

    //select like text field on mainstoryboard

    image

    Install Node.js on Ubuntu

    You can use nvm to install Node.js. It allows you work with different versions without conflicts.

    Where does Hive store files in HDFS?

    describe formatted <table_name>; inside hive shell.

    Notice the "Location" value that shows the location of the table.

    How to present a modal atop the current view in Swift

    First, remove all explicit setting of modal presentation style in code and do the following:

    1. In the storyboard set the ModalViewController's modalPresentation style to Over Current context

    img1

    1. Check the checkboxes in the Root/Presenting ViewController - Provide Context and Define Context. They seem to be working even unchecked.

    Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

    My problem was: django-reversion>=1.8.7,<1.9

    for django 1.9.7 you should use: django-reversion==1.10.0

    I were upgraded django-cms 3.2 to 3.3, and found it by commenting apps, then uncommenting back.

    Correct answer here: https://stackoverflow.com/a/34040556/2837890

    Using jQuery to programmatically click an <a> link

    Try this:

    $('#myAnchor')[0].click();
    

    It works for me.

    Java List.contains(Object with field value equal to x)

    Predicate

    If you dont use Java 8, or library which gives you more functionality for dealing with collections, you could implement something which can be more reusable than your solution.

    interface Predicate<T>{
            boolean contains(T item);
        }
    
        static class CollectionUtil{
    
            public static <T> T find(final Collection<T> collection,final  Predicate<T> predicate){
                for (T item : collection){
                    if (predicate.contains(item)){
                        return item;
                    }
                }
                return null;
            }
        // and many more methods to deal with collection    
        }
    

    i'm using something like that, i have predicate interface, and i'm passing it implementation to my util class.

    What is advantage of doing this in my way? you have one method which deals with searching in any type collection. and you dont have to create separate methods if you want to search by different field. alll what you need to do is provide different predicate which can be destroyed as soon as it no longer usefull/

    if you want to use it, all what you need to do is call method and define tyour predicate

    CollectionUtil.find(list, new Predicate<MyObject>{
        public boolean contains(T item){
            return "John".equals(item.getName());
         }
    });
    

    How to count the number of letters in a string without the spaces?

    Counting number of letters in a string using regex.

    import re
    s = 'The grey old fox is an idiot'
    count = len(re.findall('[a-zA-Z]',s))
    

    How do I use su to execute the rest of the bash script as that user?

    Inspired by the idea from @MarSoft but I changed the lines like the following:

    USERNAME='desireduser'
    COMMAND=$0
    COMMANDARGS="$(printf " %q" "${@}")"
    if [ $(whoami) != "$USERNAME" ]; then
      exec sudo -E su $USERNAME -c "/usr/bin/bash -l $COMMAND $COMMANDARGS"
      exit
    fi
    

    I have used sudo to allow a password less execution of the script. If you want to enter a password for the user, remove the sudo. If you do not need the environment variables, remove -E from sudo.

    The /usr/bin/bash -l ensures, that the profile.d scripts are executed for an initialized environment.

    How can I resize an image dynamically with CSS as the browser width/height changes?

    Try

    .img{
       width:100vw; /* Matches to the Viewport Width */
       height:auto;
       max-width:100% !important;
    }
    

    Only works with display block and inline block, this has no effect on flex items as I've just spent ages trying to find out.

    Validating IPv4 addresses with regexp

    I think this one is the shortest.

    ^(([01]?\d\d?|2[0-4]\d|25[0-5]).){3}([01]?\d\d?|2[0-4]\d|25[0-5])$
    

    How to ignore the certificate check when ssl

    Based on Adam's answer and Rob's comment I used this:

    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => certificate.Issuer == "CN=localhost";
    

    which filters the "ignoring" somewhat. Other issuers can be added as required of course. This was tested in .NET 2.0 as we need to support some legacy code.

    CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

    Had this problem with angular, using an auth interceptor to edit the header, before the request gets executed. We used an api-token for authentification, so i had credentials enabled. now, it seems it is not neccessary/allowed anymore

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
          //withCredentials: true, //not needed anymore
          setHeaders: {
            'Content-Type' : 'application/json',
            'API-TOKEN' : 'xxx'
          },
        });
        
        return next.handle(req);
      }
    

    Besides that, there is no side effects right now.

    Splitting templated C++ classes into .hpp/.cpp files--is it possible?

    Only if you #include "stack.cpp at the end of stack.hpp. I'd only recommend this approach if the implementation is relatively large, and if you rename the .cpp file to another extension, as to differentiate it from regular code.

    Assign an initial value to radio button as checked

    For anyone looking for an Angular2 (2.4.8) solution, since this is a generically-popular question when searching:

    <div *ngFor="let choice of choices">
      <input type="radio" [checked]="choice == defaultChoice">
    </div>
    

    This will add the checked attribute to the input given the condition, but will add nothing if the condition fails.

    Do not do this:

    [attr.checked]="choice == defaultChoice"
    

    because this will add the attribute checked="false" to every other input element.

    Since the browser only looks for the presence of the checked attribute (the key), ignoring its value, so the last input in the group will be checked.

    flutter run: No connected devices

    I had the same issue. Setting up the Android SDK is also a correct answer. But this is very simple -

    1. Import an android project to a new Android studio window.
    2. Close your current Flutter project Android studio window.
    3. Import that Flutter project to new Android Studio window.

    Check object empty

    In Java, you can verify using Object utils.

    import static java.util.Objects.isNull;
    if(IsNull(yourObject)){
      //your block here
    }
    

    SQL Server after update trigger

    CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
    AFTER UPDATE
    AS
    BEGIN
        DECLARE @ID INT
    
        SELECT @ID = D.ID
        FROM inserted D
    
        UPDATE MYTABLE
        SET mytable.CHANGED_ON = GETDATE()
            ,CHANGED_BY = USER_NAME(USER_ID())
        WHERE ID = @ID
    END
    

    How to save a figure in MATLAB from the command line?

    If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.

    How to Compare a long value is equal to Long value

    Since Java 7 you can use java.util.Objects.equals(Object a, Object b):

    These utilities include null-safe or null-tolerant methods

    Long id1 = null;
    Long id2 = 0l;
    Objects.equals(id1, id2));
    

    How to quit a java app from within the program

    System.exit(ABORT); Quit's the process immediately.

    Find a file by name in Visual Studio Code

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

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

    vertical-align: middle with Bootstrap 2

    i use this

    <style>
    html, body{height:100%;margin:0;padding:0 0} 
    .container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}   
    .row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
    .centering{float:none;margin:0 auto} 
    </style>
    <body>
    <div class="container-fluid">
         <div class="row-fluid">
         <div class="offset3 span6 centering">
                content here
             </div>
        </div>
     </div>
    </body>
    

    J2ME/Android/BlackBerry - driving directions, route between two locations

    J2ME Map Route Provider

    maps.google.com has a navigation service which can provide you route information in KML format.

    To get kml file we need to form url with start and destination locations:

    public static String getUrl(double fromLat, double fromLon,
                                double toLat, double toLon) {// connect to map web service
        StringBuffer urlString = new StringBuffer();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");// from
        urlString.append(Double.toString(fromLat));
        urlString.append(",");
        urlString.append(Double.toString(fromLon));
        urlString.append("&daddr=");// to
        urlString.append(Double.toString(toLat));
        urlString.append(",");
        urlString.append(Double.toString(toLon));
        urlString.append("&ie=UTF8&0&om=0&output=kml");
        return urlString.toString();
    }
    

    Next you will need to parse xml (implemented with SAXParser) and fill data structures:

    public class Point {
        String mName;
        String mDescription;
        String mIconUrl;
        double mLatitude;
        double mLongitude;
    }
    
    public class Road {
        public String mName;
        public String mDescription;
        public int mColor;
        public int mWidth;
        public double[][] mRoute = new double[][] {};
        public Point[] mPoints = new Point[] {};
    }
    

    Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

     public static String getUrl(double fromLat, double fromLon,
         double toLat, double toLon)
    

    then create connection with this url and get InputStream.
    Then pass this InputStream and get parsed data structure:

     public static Road getRoute(InputStream is) 
    

    Full source code RoadProvider.java

    BlackBerry

    class MapPathScreen extends MainScreen {
        MapControl map;
        Road mRoad = new Road();
        public MapPathScreen() {
            double fromLat = 49.85, fromLon = 24.016667;
            double toLat = 50.45, toLon = 30.523333;
            String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
            InputStream is = getConnection(url);
            mRoad = RoadProvider.getRoute(is);
            map = new MapControl();
            add(new LabelField(mRoad.mName));
            add(new LabelField(mRoad.mDescription));
            add(map);
        }
        protected void onUiEngineAttached(boolean attached) {
            super.onUiEngineAttached(attached);
            if (attached) {
                map.drawPath(mRoad);
            }
        }
        private InputStream getConnection(String url) {
            HttpConnection urlConnection = null;
            InputStream is = null;
            try {
                urlConnection = (HttpConnection) Connector.open(url);
                urlConnection.setRequestMethod("GET");
                is = urlConnection.openInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return is;
        }
    }
    

    See full code on J2MEMapRouteBlackBerryEx on Google Code

    Android

    Android G1 screenshot

    public class MapRouteActivity extends MapActivity {
        LinearLayout linearLayout;
        MapView mapView;
        private Road mRoad;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mapView = (MapView) findViewById(R.id.mapview);
            mapView.setBuiltInZoomControls(true);
            new Thread() {
                @Override
                public void run() {
                    double fromLat = 49.85, fromLon = 24.016667;
                    double toLat = 50.45, toLon = 30.523333;
                    String url = RoadProvider
                            .getUrl(fromLat, fromLon, toLat, toLon);
                    InputStream is = getConnection(url);
                    mRoad = RoadProvider.getRoute(is);
                    mHandler.sendEmptyMessage(0);
                }
            }.start();
        }
    
        Handler mHandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                TextView textView = (TextView) findViewById(R.id.description);
                textView.setText(mRoad.mName + " " + mRoad.mDescription);
                MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
                List<Overlay> listOfOverlays = mapView.getOverlays();
                listOfOverlays.clear();
                listOfOverlays.add(mapOverlay);
                mapView.invalidate();
            };
        };
    
        private InputStream getConnection(String url) {
            InputStream is = null;
            try {
                URLConnection conn = new URL(url).openConnection();
                is = conn.getInputStream();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return is;
        }
        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }
    }
    

    See full code on J2MEMapRouteAndroidEx on Google Code

    How to order results with findBy() in Doctrine

    $cRepo = $em->getRepository('KaleLocationBundle:Country');
    
    // Leave the first array blank
    $countries = $cRepo->findBy(array(), array('name'=>'asc'));
    

    Find methods calls in Eclipse project

    Right click on method and click on Open call Hierarchy

    eclipse right click call hierarchy

    How to delete node from XML file using C#

    DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

    How to return a value from pthread threads in C?

    Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?

    This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.

    But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.

    Circular (or cyclic) imports in Python

    There are a lot of great answers here. While there are usually quick solutions to the problem, some of which feel more pythonic than others, if you have the luxury of doing some refactoring, another approach is to analyze the organization of your code, and try to remove the circular dependency. You may find, for example, that you have:

    File a.py

    from b import B
    
    class A:
        @staticmethod
        def save_result(result):
            print('save the result')
    
        @staticmethod
        def do_something_a_ish(param):
            A.save_result(A.use_param_like_a_would(param))
    
        @staticmethod
        def do_something_related_to_b(param):
            B.do_something_b_ish(param)
    

    File b.py

    from a import A
    
    class B:
        @staticmethod
        def do_something_b_ish(param):
            A.save_result(B.use_param_like_b_would(param))
    

    In this case, just moving one static method to a separate file, say c.py:

    File c.py

    def save_result(result):
        print('save the result')
    

    will allow removing the save_result method from A, and thus allow removing the import of A from a in b:

    Refactored File a.py

    from b import B
    from c import save_result
    
    class A:
        @staticmethod
        def do_something_a_ish(param):
            A.save_result(A.use_param_like_a_would(param))
    
        @staticmethod
        def do_something_related_to_b(param):
            B.do_something_b_ish(param)
    

    Refactored File b.py

    from c import save_result
    
    class B:
        @staticmethod
        def do_something_b_ish(param):
            save_result(B.use_param_like_b_would(param))
    

    In summary, if you have a tool (e.g. pylint or PyCharm) that reports on methods that can be static, just throwing a staticmethod decorator on them might not be the best way to silence the warning. Even though the method seems related to the class, it might be better to separate it out, especially if you have several closely related modules that might need the same functionality and you intend to practice DRY principles.

    How to open an existing project in Eclipse?

    Maybe you have closed the project and configured the project explorer view to filter closed projects.

    In that case, have a look at Filters in the Project Explorer view. Make sure that closed projects are disabled in the "Filters" view.

    How To Set A JS object property name from a variable

    With ECMAScript 6, you can use variable property names with the object literal syntax, like this:

    var keyName = 'myKey';
    var obj = {
                  [keyName]: 1
              };
    obj.myKey;//1
    

    This syntax is available in the following newer browsers:

    Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+

    (https://kangax.github.io/compat-table/es6/)

    You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.

    Looping through dictionary object

    public class TestModels
    {
        public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
    
        public TestModels()
        {
            sp.Add(0, new {name="Test One", age=5});
            sp.Add(1, new {name="Test Two", age=7});
        }
    }
    

    How to deserialize xml to object

    The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

    public static T DeserializeXMLFileToObject<T>(string XmlFilename)
    {
        T returnObject = default(T);
        if (string.IsNullOrEmpty(XmlFilename)) return default(T);
    
        try
        {
            StreamReader xmlStream = new StreamReader(XmlFilename);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            returnObject = (T)serializer.Deserialize(xmlStream);
        }
        catch (Exception ex)
        {
            ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
        }
        return returnObject;
    }
    

    Then you'd call it like this:

    MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);
    

    Procedure expects parameter which was not supplied

    I had the same issue, to solve it just add exactly the same parameter name to your parameter collection as in your stored procedures.

    Example

    Let's say you create a stored procedure:

    create procedure up_select_employe_by_ID 
         (@ID int) 
    as
        select * 
        from employe_t 
        where employeID = @ID
    

    So be sure to name your parameter exactly as it is in your stored procedure this would be

    cmd.parameter.add("@ID", sqltype,size).value = @ID
    

    if you go

    cmd.parameter.add("@employeID", sqltype,size).value = @employeid 
    

    then the error happens.

    Storing Images in PostgreSQL

    In the database, there are two options:

    • bytea. Stores the data in a column, exported as part of a backup. Uses standard database functions to save and retrieve. Recommended for your needs.
    • blobs. Stores the data externally, not normally exported as part of a backup. Requires special database functions to save and retrieve.

    I've used bytea columns with great success in the past storing 10+gb of images with thousands of rows. PG's TOAST functionality pretty much negates any advantage that blobs have. You'll need to include metadata columns in either case for filename, content-type, dimensions, etc.

    How do you get the Git repository's name in some Git repository?

    A little bit late for this question, but if you:

    cat /path/to/repo/.git/config
    

    You will see the url of the repository which will include the reponame:

    [core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
    [remote "origin"]
        url = https://github.com/your_git_user_name/your_git_repo_name.git
        fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "master"]
        remote = origin
        merge = refs/heads/master
    

    Is there any free OCR library for Android?

    ANother option could be to post the image to a webapp (possibly at a later moment), and have it OCR-processed there without the C++ -> Java port issues and possibly clogging the mobile CPU.

    `&mdash;` or `&#8212;` is there any difference in HTML output?

    Could be that using the numeral code is more universal, as it's a direct reference to a character in the html entity table, but I guess they both work everywhere. The first notation is just massively easier to remember for a lot of characters.

    How to create a showdown.js markdown extension

    In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

    EDIT

    It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

    var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

    I submitted a pull request to update this.

    Filter output in logcat by tagname

    use this:

    adb logcat -s "TAGNAME"
    

    how to make div click-able?

    I suggest to use a CSS class called clickbox and activate it with jQuery:

    $(".clickbox").click(function(){
         window.location=$(this).find("a").attr("href"); 
         return false;
     });
    

    Now the only thing you have to do is mark your div as clickable and provide a link:

    <div id="logo" class="clickbox"><a href="index.php"></a></div>
    

    Plus a CSS style to change the mouse cursor:

    .clickbox {
        cursor: pointer;
    }
    

    Easy, isn't it?

    Best Practice for Forcing Garbage Collection in C#

    Large objects are allocated on LOH (large object heap), not on gen 0. If you're saying that they don't get garbage-collected with gen 0, you're right. I believe they are collected only when the full GC cycle (generations 0, 1 and 2) happens.

    That being said, I believe on the other side GC will adjust and collect memory more aggressively when you work with large objects and the memory pressure is going up.

    It is hard to say whether to collect or not and in which circumstances. I used to do GC.Collect() after disposing of dialog windows/forms with numerous controls etc. (because by the time the form and its controls end up in gen 2 due to creating many instances of business objects/loading much data - no large objects obviously), but actually didn't notice any positive or negative effects in the long term by doing so.

    How can I align text directly beneath an image?

    This centers the "A" below the image:

    <div style="text-align:center">
      <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/opentoselect.gif" />
      <br />
      A
    </div>
    

    That is ASP.Net and it would render the HTML as:

    <div style="text-align:center">
    <img id="Image1" src="Images/opentoselect.gif" style="border-width:0px;" />
    <br />
    A
    </div>
    

    Are there any standard exit status codes in Linux?

    Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

    How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

    The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

    Convert JSON to DataTable

    Deserialize your jsonstring to some class

    List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);
    

    Write following extension method to your project

    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection props =
        TpeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for(int i = 0 ; i < props.Count ; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;        
    }
    

    Call extension method like

    UserList.ToDataTable<User>();
    

    Setting device orientation in Swift iOS

    If someone wants the answer, I think I just got it. Try this:

    • Go to your .plist file and check all the orientations.
    • In the view controller you want to force orientation, add the following code:
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
    }
    

    Hope it helps !

    EDIT :

    To force rotation, use the following code :

    let value = UIInterfaceOrientation.LandscapeRight.rawValue
    UIDevice.currentDevice().setValue(value, forKey: "orientation")
    

    It works for iOS 7 & 8 !

    Full Page <iframe>

    This is what I have used in the past.

    html, body {
      height: 100%;
      overflow: auto;
    }
    

    Also in the iframe add the following style

    border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%
    

    How to get the first 2 letters of a string in Python?

    It is as simple as string[:2]. A function can be easily written to do it, if you need.

    Even this, is as simple as

    def first2(s):
        return s[:2]
    

    Bin size in Matplotlib (Histogram)

    Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:

    plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])
    

    If you just want them equally distributed, you can simply use range:

    plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))
    

    Added to original answer

    The above line works for data filled with integers only. As macrocosme points out, for floats you can use:

    import numpy as np
    plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))
    

    Getting Excel to refresh data on sheet from within VBA

    This should do the trick...

    'recalculate all open workbooks
    Application.Calculate
    
    'recalculate a specific worksheet
    Worksheets(1).Calculate
    
    ' recalculate a specific range
    Worksheets(1).Columns(1).Calculate
    

    byte array to pdf

    Usually this happens if something is wrong with the byte array.

    File.WriteAllBytes("filename.PDF", Byte[]);
    

    This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

    Asynchronous implementation of this is also available.

    public static System.Threading.Tasks.Task WriteAllBytesAsync 
    (string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
    

    How does tuple comparison work in Python?

    The Python documentation does explain it.

    Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

    .htaccess redirect all pages to new domain

    Use conditional redirects with Options -FollowSymLinks and AllowOverride -Options disabled by the Hoster if a few local files should be served too:

    Sample .htaccess

    # Redirect everything except index.html to http://foo
    <FilesMatch "(?<!index\.html)$">
        Redirect 301 / http://foo/
    </FilesMatch>
    

    This example will serve local index.html and redirects all other staff to new domain.

    Django CSRF Cookie Not Set

    Make sure your django session backend is configured properly in settings.py. Then try this,

    class CustomMiddleware(object):
      def process_request(self,request:HttpRequest):
          get_token(request)
    

    Add this middleware in settings.py under MIDDLEWARE_CLASSES or MIDDLEWARE depending on the django version

    get_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.

    What is the difference between __str__ and __repr__?

    From the book Fluent Python:

    A basic requirement for a Python object is to provide usable string representations of itself, one used for debugging and logging, another for presentation to end users. That is why the
    special methods __repr__ and __str__ exist in the data model.

    SOAP client in .NET - references or examples?

    Take a look at "using WCF Services with PHP". It explains the basics of what you need.

    As a theory summary:

    WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

    The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

    You have the first part of the article here, explaining how to create a very basic WCF Service.

    More resources:

    Using WCF with PHP5.

    Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

    Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

    Try reopening VS code or Atom with more specific directory where your app.js is present. I had a lot of folders opened and this problem occured. But once I opened my specific folder and tried once again, it worked.

    Python assigning multiple variables to same value? list behavior

    You can use id(name) to check if two names represent the same object:

    >>> a = b = c = [0, 3, 5]
    >>> print(id(a), id(b), id(c))
    46268488 46268488 46268488
    

    Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:

    >>> a[0] = 1
    >>> print(id(a), id(b), id(c))
    46268488 46268488 46268488
    >>> print(a, b, c)
    [1, 3, 5] [1, 3, 5] [1, 3, 5]
    

    If you assign a new list to a, then its id will change, so it won't affect b and c's values:

    >>> a = [1, 8, 5]
    >>> print(id(a), id(b), id(c))
    139423880 46268488 46268488
    >>> print(a, b, c)
    [1, 8, 5] [1, 3, 5] [1, 3, 5]
    

    Integers are immutable, so you cannot change the value without creating a new object:

    >>> x = y = z = 1
    >>> print(id(x), id(y), id(z))
    507081216 507081216 507081216
    >>> x = 2
    >>> print(id(x), id(y), id(z))
    507081248 507081216 507081216
    >>> print(x, y, z)
    2 1 1
    

    What does the construct x = x || y mean?

    To add some explanation to all said before me, I should give you some examples to understand logical concepts.

    var name = false || "Mohsen"; # name equals to Mohsen
    var family = true || "Alizadeh" # family equals to true
    

    It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

    And operator have the opposite structure like below.

    var name = false && "Mohsen" # name equals to false
    var family = true && "Alizadeh" # family equals to Alizadeh
    

    When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

    This was happening to me when I had to fix an old project that had not been looked at in a while. The chromedriver associated to the project was not compatible with my version of chrome, so when I updated the chromedriver it worked fine.

    How to use the command update-alternatives --config java

    There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all and choosing the right alternatives for everything else besides java and javac.

    How to move div vertically down using CSS

    Give margin-top

    div{margin-top:10px;}
    

    How do I load an url in iframe with Jquery

    $("#button").click(function () { 
        $("#frame").attr("src", "http://www.example.com/");
    });
    

    HTML:

     <div id="mydiv">
         <iframe id="frame" src="" width="100%" height="300">
         </iframe>
     </div>
     <button id="button">Load</button>
    

    Re-render React component when prop changes

    A friendly method to use is the following, once prop updates it will automatically rerender component:

    render {
    
    let textWhenComponentUpdate = this.props.text 
    
    return (
    <View>
      <Text>{textWhenComponentUpdate}</Text>
    </View>
    )
    
    }
    

    Parse JSON from JQuery.ajax success data

    From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

    Or you can set the dataType to json to convert it automatically.

    How can I import Swift code to Objective-C?

    You need to import ProductName-Swift.h. Note that it's the product name - the other answers make the mistake of using the class name.

    This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject.

    Considerations:

    • If your product name contains spaces, replace them with underscores (e.g. My Project becomes My_Project-Swift.h)

    • If your target is a framework, you need to import <ProductName/ProductName-Swift.h>

    • Make sure your Swift file is member of the target

    Node.js version on the command line? (not the REPL)

    If you're referring to the shell command line, either of the following will work:

    node -v
    
    node --version
    

    Just typing node version will cause node.js to attempt loading a module named version, which doesn't exist unless you like working with confusing module names.

    Can pandas automatically recognize dates?

    While loading csv file contain date column.We have two approach to to make pandas to recognize date column i.e

    1. Pandas explicit recognize the format by arg date_parser=mydateparser

    2. Pandas implicit recognize the format by agr infer_datetime_format=True

    Some of the date column data

    01/01/18

    01/02/18

    Here we don't know the first two things It may be month or day. So in this case we have to use Method 1:- Explicit pass the format

        mydateparser = lambda x: pd.datetime.strptime(x, "%m/%d/%y")
        df = pd.read_csv(file_name, parse_dates=['date_col_name'],
    date_parser=mydateparser)
    

    Method 2:- Implicit or Automatically recognize the format

    df = pd.read_csv(file_name, parse_dates=[date_col_name],infer_datetime_format=True)
    

    How to specify the port an ASP.NET Core application is hosted on?

    Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
    

    You can build your project and go to bin run command like this

    dotnet <yours>.dll --urls=http://localhost:5001
    

    or with multi-urls

    dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"
    

    How do I detect if software keyboard is visible on Android Device or not?

    As you might know android Software keyboard will be visible only when there is a possible event of typing. In other words Keyboard get visible only when EditText is focused. that means you can get weather the Keyboard is visible or not by using OnFocusChangeListener.

    //Declare this Globally
    
    public boolean isKeyBoardVisible = false;
    
    //In OnCreate *[For Activity]*, OnCreateView *[For Fragment]*
    
    text_send.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
                isKeyBoardVisible = true;
            else
                isKeyBoardVisible = false;
        }
    });
    

    Now you can use isKeyBoardVisible variable anywhere in the class to get weather the keyboard is Open or Not. It worked well for me.

    Note: This process doesn't work when the Keyboard is opened programmatically using InputMethodManager because that doesn't invoke OnFocusChangeListener.

    Get Current date & time with [NSDate date]

    NSLocale* currentLocale = [NSLocale currentLocale];
    [[NSDate date] descriptionWithLocale:currentLocale];  
    

    or use

    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
    NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
    

    How do I measure request and response times at once using cURL?

    Option 1. To measure total time:

    curl -o /dev/null -s -w 'Total: %{time_total}s\n'  https://www.google.com
    

    Sample output:

    enter image description here

    Option 2. To get time to establish connection, TTFB: time to first byte and total time:

    curl -o /dev/null -s -w 'Establish Connection: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n'  https://www.google.com
    

    Sample output:

    enter image description here

    Ref: Get response time with curl

    How to provide shadow to Button

    Try this if this works for you

    enter image description here

    android:background="@drawable/drop_shadow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="3dp"
            android:paddingTop="3dp"
            android:paddingRight="4dp"
            android:paddingBottom="5dp"
    

    open new tab(window) by clicking a link in jquery

    Try this:

    window.open(url, '_blank');
    

    This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

    stop all instances of node.js server

    Windows Machine:

    Need to kill a Node.js server, and you don't have any other Node processes running, you can tell your machine to kill all processes named node.exe. That would look like this:

    taskkill /im node.exe
    

    And if the processes still persist, you can force the processes to terminate by adding the /f flag:

    taskkill /f /im node.exe
    

    If you need more fine-grained control and need to only kill a server that is running on a specific port, you can use netstat to find the process ID, then send a kill signal to it. So in your case, where the port is 8080, you could run the following:

    C:\>netstat -ano | find "LISTENING" | find "8080"
    

    The fifth column of the output is the process ID:

      TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       14828
      TCP    [::]:8080              [::]:0                 LISTENING       14828
    

    You could then kill the process with taskkill /pid 14828. If the process refuses to exit, then just add the /f (force) parameter to the command.


    Linux machine:

    The process is almost identical. You could either kill all Node processes running on the machine (use -$SIGNAL if SIGKILL is insufficient):

    killall node
    

    Or also using netstat, you can find the PID of a process listening on a port:

    $ netstat -nlp | grep :8080
    tcp        0      0 0.0.0.0:8080         0.0.0.0:*                   LISTEN      1073/node
    

    The process ID in this case is the number before the process name in the sixth column, which you could then pass to the kill command:

    $ kill 1073
    

    If the process refuses to exit, then just use the -9 flag, which is a SIGTERM and cannot be ignored:

    $ kill -9 1073
    

    How can I set the focus (and display the keyboard) on my EditText programmatically

    I couldn't get any of these answers to work on their own. The solution for me was to combine them:

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    editText.requestFocus();
    imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    

    I'm not sure why that was required for me -- according to the docs it seems that either method should have worked on their own.

    Why does make think the target is up to date?

    my mistake was making the target name "filename.c:" instead of just "filename:"

    Print a file, skipping the first X lines, in Bash

    A less verbose version with AWK:

    awk 'NR > 1e6' myfile.txt
    

    But I would recommend using integer numbers.

    How to read a local text file?

    This might help,

        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
    
        xmlhttp.open("GET", "sample.txt", true);
        xmlhttp.send();
    

    Material effect on button with background color

    When you use android:background, you are replacing much of the styling and look and feel of a button with a blank color.

    Update: As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.Colored style which uses your theme's colorButtonNormal for the disabled color and colorAccent for the enabled color.

    This allows you apply it to your button directly via

    <Button
      ...
      style="@style/Widget.AppCompat.Button.Colored" />
    

    If you need a custom colorButtonNormal or colorAccent, you can use a ThemeOverlay as explained in this pro-tip and android:theme on the button.

    Previous Answer

    You can use a drawable in your v21 directory for your background such as:

    <?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
            android:color="?attr/colorControlHighlight">
        <item android:drawable="?attr/colorPrimary"/>
    </ripple>
    

    This will ensure your background color is ?attr/colorPrimary and has the default ripple animation using the default ?attr/colorControlHighlight (which you can also set in your theme if you'd like).

    Note: you'll have to create a custom selector for less than v21:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/primaryPressed" android:state_pressed="true"/>
        <item android:drawable="@color/primaryFocused" android:state_focused="true"/>
        <item android:drawable="@color/primary"/>
    </selector>
    

    Assuming you have some colors you'd like for the default, pressed, and focused state. Personally, I took a screenshot of a ripple midway through being selected and pulled the primary/focused state out of that.

    How to import a new font into a project - Angular 5

    You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

    @font-face {
      font-family: lato;
      src: url(assets/font/Lato.otf) format("opentype");
    }
    

    Once done, you can apply this font any where like:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: 'lato', 'arial', sans-serif;
    }
    

    You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

    "styles": [
      "styles.css",
      "fonts.css"
    ],
    

    Replace multiple strings at once

    text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
    

    List attributes of an object

    dir(instance)
    # or (same value)
    instance.__dir__()
    # or
    instance.__dict__
    

    Then you can test what type is with type() or if is a method with callable().

    Why rgb and not cmy?

    There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).

    With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.

    On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.

    Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.

    P.D.: my father worked at graphic arts, this is why i know this... :-P

    The system cannot find the file specified in java

    First Create folder same as path which you Specified. after then create File

    File dir = new File("C:\\USER\\Semple_file\\");
    File file = new File("C:\\USER\\Semple_file\\abc.txt");
    
    if(!file.exists())
    {
        dir.mkdir();
        file.createNewFile();
        System.out.println("File,Folder Created.);
    }
    

    Export P7b file with all the certificate chain into CER file

    The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.

    1. Open the .p7b in a text editor.
    2. Change the leader and trailer so the file looks similar to this:

      -----BEGIN PKCS7-----
      [... certificate content here ...]
      -----END PKCS7-----
      

    For example, my StartCom certificate began with:

        -----BEGIN CERTIFICATE----- 
    

    and ended with:

        -----END CERTIFICATE----- 
    
    1. Save and close the .p7b.
    2. Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):

      openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
      

    The output is a .cer with the certificate chain.

    Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206

    fill an array in C#

    Say you want to fill with number 13.

    int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

    or

    List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

    if you prefer a list.

    How to order a data frame by one descending and one ascending column?

    I used this code to produce your desired output. Is this what you were after?

    rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
    2   3   5   52  43  61  6   b
    6   4   3   72  NA  59  1   a
    1   5   6   55  48  60  6   f
    2   4   4   65  64  58  2   b"), header = TRUE)
    rum$I2 <- as.character(rum$I2)
    rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]
    
      P1 P2 P3 T1 T2 T3 I1 I2
    1  2  3  5 52 43 61  6  b
    3  1  5  6 55 48 60  6  f
    4  2  4  4 65 64 58  2  b
    2  6  4  3 72 NA 59  1  a
    

    How do I add all new files to SVN

    The solution

    svn status | grep ^? | sed 's/?    //' | xargs svn add
    

    does not work with whitespaces. Instead one can use

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

    (seems like the number of leading blanks is different on my system -- just adjust it).

    Displaying all table names in php from MySQL database

    you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.

    How to use target in location.href

    <a href="url" target="_blank"> <input type="button" value="fake button" /> </a>
    

    How to prevent downloading images and video files from my website?

    You can mark folders or files so that they don't have read access (any of the main web servers support this). This allows you to store them on the server without any level of access to the outside world. You may want to do this if you have a service that generates images for someone else to download later, or if you use your web account for FTP access, but don't want anyone to view the files. (i.e. upload a .bak file to the server for someone else to FTP down again).

    However, as others have said, getting into copyright areas where people can view the image or video but not save them locally is not fully possibly, although there are tools to discourage illegal usage.

    Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

    Are you using the HTML5 required attribute?

    That will cause Chrome 10 to display a balloon prompting the user to fill out the field.

    What is a NoReverseMatch error, and how do I fix it?

    The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

    The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

    To start debugging it, you need to start by disecting the error message given to you.

    • NoReverseMatch at /my_url/

      This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

    • Reverse for 'my_url_name'

      This is the name of the url that it cannot find

    • with arguments '()' and

      These are the non-keyword arguments its providing to the url

    • keyword arguments '{}' not found.

      These are the keyword arguments its providing to the url

    • n pattern(s) tried: []

      These are the patterns that it was able to find in your urls.py files that it tried to match against

    Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

    Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

    Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

    The url name

    • Are there any typos?
    • Have you provided the url you're trying to access the given name?
    • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

    Arguments and Keyword Arguments

    The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

    Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

    If they aren't correct:

    • The value is missing or an empty string

      This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

    • The keyword argument has a typo

      Correct this either in the url pattern, or in the url you're constructing.

    If they are correct:

    • Debug the regex

      You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

      Common Mistakes:

      • Matching against the . wild card character or any other regex characters

        Remember to escape the specific characters with a \ prefix

      • Only matching against lower/upper case characters

        Try using either a-Z or \w instead of a-z or A-Z

    • Check that pattern you're matching is included within the patterns tried

      If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

    Django Version

    In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


    If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

    Convert string to Python class object?

    I don't see why this wouldn't work. It's not as concrete as everyone else's answers but if you know the name of your class then it's enough.

    def str_to_class(name):
        if name == "Foo":
            return Foo
        elif name == "Bar":
            return Bar
    

    load scripts asynchronously

    I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.

    export default class ScriptLoader {
      constructor (options) {
        const { src, global, protocol = document.location.protocol } = options
        this.src = src
        this.global = global
        this.protocol = protocol
        this.isLoaded = false
      }
    
      loadScript () {
        return new Promise((resolve, reject) => {
          // Create script element and set attributes
          const script = document.createElement('script')
          script.type = 'text/javascript'
          script.async = true
          script.src = `${this.protocol}//${this.src}`
    
          // Append the script to the DOM
          const el = document.getElementsByTagName('script')[0]
          el.parentNode.insertBefore(script, el)
    
          // Resolve the promise once the script is loaded
          script.addEventListener('load', () => {
            this.isLoaded = true
            resolve(script)
          })
    
          // Catch any errors while loading the script
          script.addEventListener('error', () => {
            reject(new Error(`${this.src} failed to load.`))
          })
        })
      }
    
      load () {
        return new Promise(async (resolve, reject) => {
          if (!this.isLoaded) {
            try {
              await this.loadScript()
              resolve(window[this.global])
            } catch (e) {
              reject(e)
            }
          } else {
            resolve(window[this.global])
          }
        })
      }
    }
    

    Usage is like this:

    const loader = new Loader({
        src: 'cdn.segment.com/analytics.js',
        global: 'Segment',
    })
    
    // scriptToLoad will now be a reference to `window.Segment`
    const scriptToLoad = await loader.load()
    

    jQuery select all except first

    _x000D_
    _x000D_
    $(document).ready(function(){_x000D_
    _x000D_
      $(".btn1").click(function(){_x000D_
              $("div.test:not(:first)").hide();_x000D_
      });_x000D_
    _x000D_
      $(".btn2").click(function(){_x000D_
               $("div.test").show();_x000D_
              $("div.test:not(:first):not(:last)").hide();_x000D_
      });_x000D_
    _x000D_
      $(".btn3").click(function(){_x000D_
              $("div.test").hide();_x000D_
              $("div.test:not(:first):not(:last)").show();_x000D_
      });_x000D_
    _x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    _x000D_
    <button class="btn1">Hide All except First</button>_x000D_
    <button class="btn2">Hide All except First & Last</button>_x000D_
    <button class="btn3">Hide First & Last</button>_x000D_
    _x000D_
    <br/>_x000D_
    _x000D_
    <div class='test'>First</div>_x000D_
    <div class='test'>Second</div>_x000D_
    <div class='test'>Third</div>_x000D_
    <div class='test'>Last</div>
    _x000D_
    _x000D_
    _x000D_

    Disable-web-security in Chrome 48+

    On OS X, to open a new Chrome window - without having to close the already open windows first - pass in the additional -n flag. Make sure to specify empty string for data-dir (necessary for newer versions of Chrome, like v50 something+).

    open -na /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir=""
    

    I found that using Chrome 60+ on Mac OS X Sierra, the above command no longer worked, but a slight modification does:

    open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_sess_1" --disable-web-security
    

    The data directory path is important. Even if you're standing in your home directory when issuing the command, you can't simply refer to a local directory. It needs to be an absolute path.

    Convert JsonObject to String

    You can try Gson convertor, to get the exact conversion like json.stringify

    val jsonString:String = jsonObject.toString()
    val gson:Gson = GsonBuilder().setPrettyPrinting().create()
    val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
    val jsonInString:String= gson.toJson(json)
    println(jsonInString)
    

    Time calculation in php (add 10 hours)?

    In order to increase or decrease time using strtotime you could use a Relative format in the first argument.

    In your case to increase the current time by 10 hours:

    $date = date('h:i:s A', strtotime('+10 hours'));
    

    In case you need to apply the change to another timestamp, the second argument can be specified.

    Note:

    Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

    So, the recommended way since PHP 5.3:

    $dt = new DateTime(); // assuming we need to add to the current time
    $dt->add(new DateInterval('PT10H'));
    $date = $dt->format('h:i:s A');
    

    or using aliases:

    $dt = date_create(); // assuming we need to add to the current time
    date_add($dt, date_interval_create_from_date_string('10 hours')); 
    $date = date_format($dt, 'h:i:s A');
    

    In all cases the default time zone will be used unless a time zone is specified.

    How to make Apache serve index.php instead of index.html?

    As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

    root@host:/etc/apache2/mods-enabled$ vi dir.conf 
    

    And change the order of that line, bringing index.php to the first position:

    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm