Programs & Examples On #Hyper v

Hyper-V is the Microsoft Windows hypervisor starting in Windows Server 2008 R2 and also running on Hyper-V Server 2008, Hyper-V Server 2012, Windows Server 2012, and as an optional component of Windows 8.

Can't ping a local VM from the host

I know this is an old post, but I ran into this same issue with my VMs. Log into the VM and go to Control Panel > System and Security > Windows Firewall > Allowed Apps. Then check all of the boxes next to "File and Printer Sharing" to enable file sharing. This should allow you to ping the VM. The screenshot below is from a 2016 Windows Server but the same method will work on older ones.

enter image description here

I can't install intel HAXM

For me who has an AMD Processor:

  1. Click on the windows button in the bottom left hand corner

  2. Look for Enable/Disable Windows features (just type : "windows features", it will appear)

  3. And contrary to the other posts here, enable Hyper-V and Windows Hypervisor Platform

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Ruby on Rails generates model field:type - what are the options for field:type?

It's very simple in ROR to create a model that references other.

rails g model Item name:string description:text product:references

This code will add 'product_id' column in the Item table

How to add title to subplots in Matplotlib?

ax.title.set_text('My Plot Title') seems to work too.

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()

matplotlib add titles on subplots

Unable to resolve host "<insert URL here>" No address associated with hostname

May you have taken permission

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

BUT

You may have forgot to TURN ON Internet in Mobile or Whatever Device.

PivotTable's Report Filter using "greater than"

Maybe in your data source add a column which does a sumif over all rows. Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2). This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values

Django DB Settings 'Improperly Configured' Error

In 2017 with django 1.11.5 and python 3.6 (from the comment this also works with Python 2.7):

import django
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

The .py in which you put this code should be in mysite (the parent one)

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

Check if input value is empty and display an alert

Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

How to run code after some delay in Flutter?

(Adding response on old q as this is the top result on google)

I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.

However, what did work was...

await Future.delayed(const Duration(milliseconds: 500));

yield newState;

Awaiting an empty future then running the function afterwards.

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

Amazon products API - Looking for basic overview and information

I found a good alternative for requesting amazon product information here: http://api-doc.axesso.de/

Its an free rest api which return alle relevant information related to the requested product.

How to replace innerHTML of a div using jQuery?

If you instead have a jQuery object you want to render instead of the existing content: Then just reset the content and append the new.

var itemtoReplaceContentOf = $('#regTitle');
itemtoReplaceContentOf.html('');
newcontent.appendTo(itemtoReplaceContentOf);

Or:

$('#regTitle').empty().append(newcontent);

Invalid application path

I eventually tracked this down to the Anonymous Authentication Credentials. I don't know what had changed, because this application used to work, but anyway, this is what I did: Click on the Application -> Authentication. Make sure Anonymous Authentication is enabled (it was, in my case), but also click on Edit... and change the anonymous user identity to "Application pool identity" not "Specific user". Making this change worked for me.

Regards.

What is the easiest way to install BLAS and LAPACK for scipy?

For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy

How to determine a user's IP address in node

There are two ways to get the ip address :

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

But there is a problem with above approaches.

If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1.

So, the best solution to get the ip address of user is :-

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Use the following Regex to satisfy the below conditions:

Conditions:

  1. Min 1 uppercase letter.
  2. Min 1 lowercase letter.
  3. Min 1 special character.
  4. Min 1 number.
  5. Min 8 characters.
  6. Max 30 characters.

Regex:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8,30}$/

How to install both Python 2.x and Python 3.x in Windows

What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.

How to...

  1. Start > in the search type in environment select "Edit environment variables to your account"1

  2. Scroll down to Path, select path, click edit.

  3. Add C:\Python27; so you should have paths to both versions of Python there, but if you don't this you can easily edit it so that you do..... C:\Python27;C:\Python33;

  4. Navigate to the Python27 folder in C:\ and rename a copy of python.exe to python2.exe

  5. Navigate to the Python34 folder in C:\ and rename a copy of python.exe to python3.exe

  6. Test: open up commmand prompt and type python2 ....BOOM! Python 2.7.6. exit out.

  7. Test: open up commmand prompt and type python3 ....BOOM! Python 3.4.3. exit out.

Note: (so as not to break pip commands in step 4 and 5, keep copy of python.exe in the same directory as the renamed file)

adding 30 minutes to datetime php/mysql

Try this one

DATE_ADD(datefield, INTERVAL 30 MINUTE)

JavaScript Nested function

function x() {}

is equivalent (or very similar) to

var x = function() {}

unless I'm mistaken.

So there is nothing funny going on.

Build error: You must add a reference to System.Runtime

The only way that worked for me - add the assembly to web.config

<compilation debug="true" targetFramework="4.5">
  <assemblies>     
    <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />   
  </assemblies>
</compilation>

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

Javascript find json value

Just use the ES6 find() function in a functional way:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_

or Lodash _.find:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Excel VBA Check if directory exists error

To be certain that a folder exists (and not a file) I use this function:

Public Function FolderExists(strFolderPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
    On Error GoTo 0
End Function

It works both, with \ at the end and without.

Add x and y labels to a pandas plot

what about ...

import pandas as pd
import matplotlib.pyplot as plt

values = [[1,2], [2,5]]

df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])

(df2.plot(lw=2,
          colormap='jet',
          marker='.',
          markersize=10,
          title='Video streaming dropout by category')
    .set(xlabel='x axis',
         ylabel='y axis'))

plt.show()

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

How to order by with union in SQL?

Why not use TOP X?

SELECT pass1.* FROM 
 (SELECT TOP 2000000 tblA.ID, tblA.CustomerName 
  FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL 
SELECT pass2.* FROM 
  (SELECT TOP 2000000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

The TOP 2000000 is an arbitrary number, that is big enough to capture all of the data. Adjust as per your requirements.

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

     <asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
                                                                    FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
                                                                            Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
                                                                    </ItemTemplate>
                                                                    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                                                                    <ItemStyle HorizontalAlign="Center" Width="50px" />
                                                                    <FooterTemplate>
                                                                        <asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
                                                                    </FooterTemplate>
                                                                </asp:TemplateField>


 private void TotalExEmpOFMonth()
    {
        Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
        /*Sum of the  Total Amount Of month*/
        foreach (GridViewRow gvr in GrdPFRecord.Rows)
        {
            TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
            lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
            lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));



        }
    }

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

Adding productFlavors{} to the app build.gradle solved the issue for me. See below:

buildTypes {
        release {
             ...
        }
    }
productFlavors {
    }

How to tell if browser/tab is active

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}

How to add a new audio (not mixing) into a video using ffmpeg?

Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {



            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");




            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};


            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {


                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");


                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }


        }

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.

The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.

RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."

unique object identifier in javascript

For browsers implementing the Object.defineProperty() method, the code below generates and returns a function that you can bind to any object you own.

This approach has the advantage of not extending Object.prototype.

The code works by checking if the given object has a __objectID__ property, and by defining it as a hidden (non-enumerable) read-only property if not.

So it is safe against any attempt to change or redefine the read-only obj.__objectID__ property after it has been defined, and consistently throws a nice error instead of silently fail.

Finally, in the quite extreme case where some other code would already have defined __objectID__ on a given object, this value would simply be returned.

var getObjectID = (function () {

    var id = 0;    // Private ID counter

    return function (obj) {

         if(obj.hasOwnProperty("__objectID__")) {
             return obj.__objectID__;

         } else {

             ++id;
             Object.defineProperty(obj, "__objectID__", {

                 /*
                  * Explicitly sets these two attribute values to false,
                  * although they are false by default.
                  */
                 "configurable" : false,
                 "enumerable" :   false,

                 /* 
                  * This closure guarantees that different objects
                  * will not share the same id variable.
                  */
                 "get" : (function (__objectID__) {
                     return function () { return __objectID__; };
                  })(id),

                 "set" : function () {
                     throw new Error("Sorry, but 'obj.__objectID__' is read-only!");
                 }
             });

             return obj.__objectID__;

         }
    };

})();

HTML5 Canvas Rotate Image

@Steve Farthing's answer is absolutely right.

But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
    if(angleInDegrees == 360){  // add this lines
        angleInDegrees = 0
    }
});

Then you will get the desired result. Thanks. Hope this will help someone :)

How do I get the parent directory in Python?

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))

Fatal error: Cannot use object of type stdClass as array in

CodeIgniter returns result rows as objects, not arrays. From the user guide:

result()


This function returns the query result as an array of objects, or an empty array on failure.

You'll have to access the fields using the following notation:

foreach ($getvidids->result() as $row) {
    $vidid = $row->videoid;
}

Run react-native on android emulator

I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,

android avd

Once the emulator is running, you can check with adb devices if the emulator shows up. Then you can simply use react-native run-android to run the app on the emulator.

Make sure you've platform tools installed to be able to use adb. Or you can use

brew install android-platform-tools

Dynamically load a function from a DLL

This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.

It is called like,

IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
      SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);

where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.

DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;

An interface class looks like,

class IMyInterface
{
    DEFINE_INTERFACE(IMyInterface);

public:
    virtual ~IMyInterface() {};

    virtual void MyMethod1() = 0;
    ...
};

The header file is like this

#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED

#pragma once

The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.

#define SN_APPLY_LIBRARIES(L, A)                          \
    L(A, sn, "sn.dll")                                    \
    L(A, http_server_lib, "http_server_lib.dll")          \
    L(A, http_server, "")

Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.

#define SN_APPLY_ENTRYPOINTS_sn(M)                                     \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def)                   \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)

#define SN_APPLY_ENTRYPOINTS_http_server_lib(M)                        \
    M(IHTTP_Server, HTTP::server::server, http_server_lib, def)

#define SN_APPLY_ENTRYPOINTS_http_server(M)

With the libraries all setup, the header file uses the macro definitions to define the needful.

#define APPLY_ENTRY(A, N, L) \
    SN_APPLY_ENTRYPOINTS_##N(A)

#define DEFINE_INTERFACE(I) \
    public: \
        static const long Id = SN::I##_def_entry; \
    private:

namespace SN
{
    #define DEFINE_LIBRARY_ENUM(A, N, L) \
        N##_library,

This creates an enum for the libraries.

    enum LibraryValues
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
        LastLibrary
    };

    #define DEFINE_ENTRY_ENUM(I, C, L, D) \
        I##_##D##_entry,

This creates an enum for interface implementations.

    enum EntryValues
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
        LastEntry
    };

    long CallEntryPoint(long id, long interfaceId);

This defines the factory class. Not much to it here.

    template <class I>
    class SN_Factory
    {
    public:
        SN_Factory()
        {
        }

        static I *CreateObject(long id = I::Id )
        {
            return (I *)CallEntryPoint(id, I::Id);
        }
    };
}

#endif //SN_FACTORY_H_INCLUDED

Then the CPP is,

#include "sn_factory.h"

#include <windows.h>

Create the external entry point. You can check that it exists using depends.exe.

extern "C"
{
    __declspec(dllexport) long entrypoint(long id)
    {
        #define CREATE_OBJECT(I, C, L, D) \
            case SN::I##_##D##_entry: return (int) new C();

        switch (id)
        {
            SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
        case -1:
        default:
            return 0;
        }
    }
}

The macros set up all the data needed.

namespace SN
{
    bool loaded = false;

    char * libraryPathArray[SN::LastLibrary];
    #define DEFINE_LIBRARY_PATH(A, N, L) \
        libraryPathArray[N##_library] = L;

    static void LoadLibraryPaths()
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
    }

    typedef long(*f_entrypoint)(long id);

    f_entrypoint libraryFunctionArray[LastLibrary - 1];
    void InitlibraryFunctionArray()
    {
        for (long j = 0; j < LastLibrary; j++)
        {
            libraryFunctionArray[j] = 0;
        }

        #define DEFAULT_LIBRARY_ENTRY(A, N, L) \
            libraryFunctionArray[N##_library] = &entrypoint;

        SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
    }

    enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
    #define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
            libraryForEntryPointArray[I##_##D##_entry] = L##_library;
    void LoadLibraryForEntryPointArray()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
    }

    enum SN::EntryValues defaultEntryArray[SN::LastEntry];
        #define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
            defaultEntryArray[I##_##D##_entry] = I##_def_entry;

    void LoadDefaultEntries()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
    }

    void Initialize()
    {
        if (!loaded)
        {
            loaded = true;
            LoadLibraryPaths();
            InitlibraryFunctionArray();
            LoadLibraryForEntryPointArray();
            LoadDefaultEntries();
        }
    }

    long CallEntryPoint(long id, long interfaceId)
    {
        Initialize();

        // assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
        enum SN::LibraryValues l = libraryForEntryPointArray[id];

        f_entrypoint f = libraryFunctionArray[l];
        if (!f)
        {
            HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);

            if (!hGetProcIDDLL) {
                return NULL;
            }

            // resolve function address here
            f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
            if (!f) {
                return NULL;
            }
            libraryFunctionArray[l] = f;
        }
        return f(id);
    }
}

Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.

#include "sn_pch.h"

Setup this library.

#define SN_APPLY_CURRENT_LIBRARY(L, A) \
    L(A, sn, "sn.dll")

An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.

#include "../inc/sn_factory.cpp"

Parsing huge logfiles in Node.js - read in line-by-line

I searched for a solution to parse very large files (gbs) line by line using a stream. All the third-party libraries and examples did not suit my needs since they processed the files not line by line (like 1 , 2 , 3 , 4 ..) or read the entire file to memory

The following solution can parse very large files, line by line using stream & pipe. For testing I used a 2.1 gb file with 17.000.000 records. Ram usage did not exceed 60 mb.

First, install the event-stream package:

npm install event-stream

Then:

var fs = require('fs')
    , es = require('event-stream');

var lineNr = 0;

var s = fs.createReadStream('very-large-file.csv')
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        lineNr += 1;

        // process line here and call s.resume() when rdy
        // function below was for logging memory usage
        logMemoryUsage(lineNr);

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(err){
        console.log('Error while reading file.', err);
    })
    .on('end', function(){
        console.log('Read entire file.')
    })
);

enter image description here

Please let me know how it goes!

Instagram how to get my user id from username?

You need to use Instagrams API to convert your username to id.

If I remember correctly you use users/search to find the username and get the id from there

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Using GSON to parse a JSON array

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

How to upgrade docker container after its image changed

After evaluating the answers and studying the topic I'd like to summarize.

The Docker way to upgrade containers seems to be the following:

Application containers should not store application data. This way you can replace app container with its newer version at any time by executing something like this:

docker pull mysql
docker stop my-mysql-container
docker rm my-mysql-container
docker run --name=my-mysql-container --restart=always \
  -e MYSQL_ROOT_PASSWORD=mypwd -v /my/data/dir:/var/lib/mysql -d mysql

You can store data either on host (in directory mounted as volume) or in special data-only container(s). Read more about it

Upgrading applications (eg. with yum/apt-get upgrade) within containers is considered to be an anti-pattern. Application containers are supposed to be immutable, which shall guarantee reproducible behavior. Some official application images (mysql:5.6 in particular) are not even designed to self-update (apt-get upgrade won't work).

I'd like to thank everybody who gave their answers, so we could see all different approaches.

How to create multiple class objects with a loop in python?

Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:

class MyClass:
   def __init__(self, name):
       self.name = name
       self.checkme = 'awesome {}'.format(self.name)
...

instanceNames = ['red', 'green', 'blue']

# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}

Then you just call the holder key and you will have all the properties and methods of your class available for you.

holder['red'].checkme

output:

'awesome red'

How to sort a data frame by alphabetic order of a character variable in R?

The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Error when creating a new text file with python?

import sys

def write():
    print('Creating new text file') 

    name = raw_input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'a')   # Trying to create a new file or open one
        file.close()

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

write()

this will work promise :)

Select from multiple tables without a join?

Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

View not attached to window manager crash

See how the Code is working here:

After calling the Async task, the async task runs in the background. that is desirable. Now, this Async task has a progress dialog which is attached to the Activity, if you ask how to see the code:

pDialog = new ProgressDialog(CLASS.this);

You are passing the Class.this as context to the argument. So the Progress dialog is still attached to the activity.

Now consider the scenario: If we try to finish the activity using the finish() method, while the async task is in progress, is the point where you are trying to access the Resource attached to the activity ie the progress bar when the activity is no more there.

Hence you get:

java.lang.IllegalArgumentException: View not attached to the window manager

Solution to this:

1) Make sure that the Dialog box is dismissed or canceled before the activity finishes.

2) Finish the activity, only after the dialog box is dismissed, that is the async task is over.

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 rename a pane in tmux?

Also when scripting, you can specify a name when creating the window with -n <window name>. For example:

# variable to store the session name
SESSION="my_session"

# set up session
tmux -2 new-session -d -s $SESSION

# create window; split into panes
tmux new-window -t $SESSION:0 -n 'My Window with a Name'

How to make HTML code inactive with comments

To comment block with nested comments: substitute inner (block) comments from "--" to "++"

<!-- *********************************************************************
     * IMPORTANT: To uncomment section
     *            sub inner comments "++" -> "--" & remove this comment
     *********************************************************************
<head>
   <title>My document's title</title> <++! My document's title ++>
   <link rel=stylesheet href="mydoc.css" type="text/css">
</head>

<body>
<++! My document's important HTML stuff ++>
...
...
...
</body>

*********************************************************************
* IMPORTANT: To uncomment section
*            sub inner comments "++" -> "--" & remove this comment
*********************************************************************
-->

Thus, the outer most comment ignores all "invalid" inner (block) comments.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Filtering Sharepoint Lists on a "Now" or "Today"

If you want to filter only items that are less than 7 days old then you just use

Filter

  • Created

  • is greater than or equal to

  • [Today]-7

Note - the screenshot is incorrect.

New items - created in last 7 days

[Today] is fully supported in view filters in 2007 and onwards (just keep the spaces out!) and you only need to muck around with calculated columns in 2003.

CSS: create white glow around image

Use simple CSS3 (not supported in IE<9)

img
{
    box-shadow: 0px 0px 5px #fff;
}

This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)

If you're worried about the users that don't have the latest versions of their browsers, use this:

img
{
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;
}

For IE you can use a glow filter (not sure which browsers support it)

img
{
    filter:progid:DXImageTransform.Microsoft.Glow(Color=white,Strength=5);
}

Play with the settings to see what suits you :)

How to locate the Path of the current project directory in Java (IDE)?

This is the new way to do it:

Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);

Or even better:

Path root = Paths.get(".").normalize().toAbsolutePath();

But I would take it one step further:

public String getUsersProjectRootDirectory() {
    String envRootDir = System.getProperty("user.dir");
    Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
    if ( rootDir.startsWith(envRootDir) ) {
        return rootDir;
    } else {
        throw new RuntimeException("Root dir not found in user directory.");
    }
}

Cannot import XSSF in Apache POI

I had the same problem, so I dug through the poi-3.17.jar file and there was no xssf package inside.

I then went through the other files and found xssf int the poi-ooxml-3.17.jar

So it seems the solutions is to add

poi-ooxml-3.17.jar

to your project, as that seems to make it work (for me at least)

Getting strings recognized as variable names in R

Without any example data, it really is difficult to know exactly what you are wanting. For instance, I can't at all divine what your object set (or is it sets) looks like.

That said, does the following help at all?

set1 <- data.frame(x = 4:6, y = 6:4, z = c(1, 3, 5))

plot(1:10, type="n")
XX <- "set1"
with(eval(as.symbol(XX)), symbols(x, y, circles = z, add=TRUE))

EDIT:

Now that I see your real task, here is a one-liner that'll do everything you want without requiring any for() loops:

with(dat, symbols(sq, cu, circles = num,
                  bg = c("red", "blue")[(num>5) + 1]))

The one bit of code that may feel odd is the bit specifying the background color. Try out these two lines to see how it works:

c(TRUE, FALSE) + 1
# [1] 2 1
c("red", "blue")[c(F, F, T, T) + 1]
# [1] "red"  "red"  "blue" "blue"

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Instead of below code:

$(this).attr("src").replace(urlRelative, urlAbsolute);

Use this:

$(this).attr("src",urlAbsolute);

How to get text from EditText?

If you are doing it before the setContentView() method call, then the values will be null.

This will result in null:

super.onCreate(savedInstanceState);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

setContentView(R.layout.main_contacts);

while this will work fine:

super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

How to concatenate characters in java?

public class initials {

public static void main (String [] args) {

    char initialA = 'M';
    char initialB = 'P';
    char initialC = 'T';

    System.out.println("" + initialA + initialB + initialC );


}   

}

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

animating addClass/removeClass with jQuery

Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :-

addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other.

$(this).addClass('abc',1000);

See jsfiddle:- http://jsfiddle.net/6hvZT/1/

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

C#: Printing all properties of an object

Any other solution/library is in the end going to use reflection to introspect the type...

Jquery to get the id of selected value from dropdown

If you are trying to get the id, then please update your code like

  html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';

To retrieve id,

$('option:selected').attr("id")

To retrieve Value

$('option:selected').val()

in Javascript

var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;

Deserialize JSON with C#

Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.

var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();

New warnings in iOS 9: "all bitcode will be dropped"

Your library was compiled without bitcode, but the bitcode option is enabled in your project settings. Say NO to Enable Bitcode in your target Build Settings and the Library Build Settings to remove the warnings.

For those wondering if enabling bitcode is required:

For iOS apps, bitcode is the default, but optional. For watchOS and tvOS apps, bitcode is required. If you provide bitcode, all apps and frameworks in the app bundle (all targets in the project) need to include bitcode.

https://help.apple.com/xcode/mac/current/#/devbbdc5ce4f

How do I install a custom font on an HTML site

there is a simple way to do this: in the html file add:

<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />

Note: you put the name of .ttf file you have. then go to to your css file and add:

h1 {
    color: blue;
    font-family: vermin vibes;
}

Note: you put the font family name of the font you have.

Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.

How to add image to canvas

You need to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0);
  }
}

i.e. draw the image in the onload callback of the image.

How do I hide certain files from the sidebar in Visual Studio Code?

You can configure patterns to hide files and folders from the explorer and searches.

  1. Open VS User Settings (Main menu: File > Preferences > Settings). This will open the setting screen.
  2. Search for files:exclude in the search at the top.
  3. Configure the User Setting with new glob patterns as needed. In this case add this pattern node_modules/ then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.

When you are done it should look something like this: enter image description here

If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:

"files.exclude": {
    "node_modules/": true
}

To hide all files that start with ._ such as ._.DS_Store files found on OSX:

"files.exclude": {
    "**/._*": true
}

You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings). Workspace settings will create a .vscode/settings.json file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

OK, the answer is easy, but read on:

col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px

The pixel numbers are the breakpoints, so for example col-xs is targeting the element when the window is smaller than 768px(likely mobile devices)...

I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6 to show you how the grid system work in the page, look at how lg, md and xs are responsive to the window size:

Bootstrap grid system, col-*-6

How to force Chrome's script debugger to reload javascript?

For Google chrome it is not Ctrl+F5. It's Shift+F5 to clear the current cache! It works for me !

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

Trying to get property of non-object - Laravel 5

I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:

First, as suggested by Jimmy Zoto, my code in blade from

$article->poster->name 

to

$article->poster['name']

Next is to add a second parameter in my belongsTo, from

return $this->belongsTo('App\User');

to

return $this->belongsTo('App\User', 'user_id');

in which user_id is my foreign key in the news table.

How do I determine if a port is open on a Windows server?

Use this if you want to see all the used and listening ports on a Windows server:

netstat -an |find /i "listening"

See all open, listening, established ports:

netstat -a

Node: log in a file instead of the console

You can now use Caterpillar which is a streams based logging system, allowing you to log to it, then pipe the output off to different transforms and locations.

Outputting to a file is as easy as:

var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');

Complete example on the Caterpillar Website

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Updated for 2019: As previously suggested, in the latest Eclipse, go to "Install New Software" in the Help Menu and click the "add" button with this URL http://download.eclipse.org/tools/pdt/updates/latest/ that should show the latest release of PHP Development Tools (PDT). You might need to search for "php" or "pdt". For Nightly releases you can use http://download.eclipse.org/tools/pdt/updates/latest-nightly/.

IE7 Z-Index Layering Issues

If you wanna create dropdown menu and having a problem with z-index, you can solve it by creating z-indexes of same value (z-index:999; for example).. Just put z-index in parent and child div's and that will solve problem. I solve the problem with that. If i put different z-indexes, sure, it will show my child div over my parent div, but, once i want to move my mouse from menu tab to the sub-menu div (dropdown list), it dissapear... then i put z-indexes of same value and solve the problem..

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

How to write multiple conditions in Makefile.am with "else if"

As you've discovered, you can't do that. You can do:

libtest_LIBS = 

...

if HAVE_CLIENT
libtest_LIBS += libclient.la
endif

if HAVE_SERVER
libtest_LIBS += libserver.la
endif

HTTP Ajax Request via HTTPS Page

Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you (that is if the site is using CORS as well)


XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

onmessage = evt => {
  const port = evt.ports[0]

  fetch(...evt.data).then(res => {
    // the response is not clonable
    // so we make a new plain object
    const obj = {
      bodyUsed: false,
      headers: [...res.headers],
      ok: res.ok,
      redirected: res.redurected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      url: res.url
    }

    port.postMessage(obj)

    // Pipe the request to the port (MessageChannel)
    const reader = res.body.getReader()
    const pump = () => reader.read()
    .then(({value, done}) => done 
      ? port.postMessage(done)
      : (port.postMessage(value), pump())
    )

    // start the pipe
    pump()
  })
}

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

window.popup = window.open(http://.../proxy.html)

create your utility function

function xfetch(...args) {
  // tell the proxy to make the request
  const ms = new MessageChannel
  popup.postMessage(args, '*', [ms.port1])

  // Resolves when the headers comes
  return new Promise((rs, rj) => {

    // First message will resolve the Response Object
    ms.port2.onmessage = ({data}) => {
      const stream = new ReadableStream({
        start(controller) {

          // Change the onmessage to pipe the remaning request
          ms.port2.onmessage = evt => {
            if (evt.data === true) // Done?
              controller.close()
            else // enqueue the buffer to the stream
              controller.enqueue(evt.data)
          }
        }
      })

      // Construct a new response with the 
      // response headers and a stream
      rs(new Response(stream, data))
    }
  })
}

And make the request like you normally do with the fetch api

xfetch('http://httpbin.org/get')
  .then(res => res.text())
  .then(console.log)

How do I get an animated gif to work in WPF?

Check my code, I hope this helped you :)

         public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)
                    {
    int ab=0;
                        var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        var getFrames = gif.Frames;
                        BitmapFrame[] frames = getFrames.ToArray();
                        await Task.Run(() =>
                        {


                            while (ab < getFrames.Count())
                            {
                                Thread.Sleep(speed);
try
{
                                Dispatcher.Invoke(() =>
                                {
                                    gifImage.Source = frames[ab];
                                });
                                if (ab == getFrames.Count - 1&&_Repeat)
                                {
                                    ab = 0;

                                }
                                ab++;
            }
 catch
{
}

                            }
                        });
                    }

or

     public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)
            {
 int ab = 0;   
                var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                var getFrames = gif.Frames;
                BitmapFrame[] frames = getFrames.ToArray();
                await Task.Run(() =>
                {


                    while (ab < getFrames.Count())
                    {
                        Thread.Sleep(speed);
    try
    {


                     Dispatcher.Invoke(() =>
                        {
                            gifImage.Source = frames[ab];
                        });
                        if (ab == getFrames.Count - 1&&_Repeat)
                        {
                            ab = 0;

                        }
                        ab++;
    }
     catch{} 



                    }
                });
            }

Jupyter notebook not running code. Stuck on In [*]

pip install prompt -toolkit~2.0.9 pip install --upgrade ipython conda update jupyter_core jupyter_client

How can I exit from a javascript function?

you can use

return false; or return; within your condition.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}

Update Top 1 record in table sql server

When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause that is specified in a subselect statement.

TOP cannot be used in an UPDATE and DELETE statements on partitioned views.

TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

No, You cannot do that. Use the following line of code instead:

IEnumerable<int> usersIds = new List<int>() {1, 2, 3}.AsEnumerable();

I hope it helps.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

VBoxManage: error: Failed to create the host-only adapter

Got the error in Mac after the update to Mojave. Probably you have an older version of virtual box.

Update to a recent version of virtualbox. (5.2 at the time of wrting this post)

Edit: adding @lsimonetti's comment.

In addition to that upgrade to Virtualbox 5.2, you need Vagrant >= 2.0.1

Wait for shell command to complete

Save the bat file on "C:\WINDOWS\system32" and use below code it is working

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

How to restore/reset npm configuration to default values?

npm config edit

Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.

npm config list will display the list of available now.

How do you get a string from a MemoryStream?

You can also use

Encoding.ASCII.GetString(ms.ToArray());

I don't think this is less efficient, but I couldn't swear to it. It also lets you choose a different encoding, whereas using a StreamReader you'd have to specify that as a parameter.

Shortcut to exit scale mode in VirtualBox

Steps:

  • host + f, to switch to full screen mode, if not yet,
  • host + c, to switch to/out of scaled mode,
  • host + f, to switch back normal size, if need,

Tip:

  • host key, default to right ctrl, the control button on right part of your keyboard,
  • host + c seems only work in fullscreen mode,

error: Your local changes to the following files would be overwritten by checkout

Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).

Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not pushed); or - use stash:

git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop

git stash save will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.

How to change working directory in Jupyter Notebook?

I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path

  1. After find the .jupyter folder, check there has “jupyter_notebook_config” file or not. If it is not there then run below command enter image description here After run the command it will create "jupyter_notebook_config.py"

if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor

  1. Open “jupyter_notebook_config.py” file from the the “.jypyter” folder.
  2. After open the file need to update the directory is use for notebooks and kernel. There are so many line in config file so find “#c.NotebookApp.notebook_dir” and update the path enter image description here After: enter image description here Save the file
  3. Now try to create or read some file from the location you set

How do you properly return multiple values from a Promise?

you can only pass one value, but it can be an array with multiples values within, as example:

function step1(){
  let server = "myserver.com";
  let data = "so much data, very impresive";
  return Promise.resolve([server, data]);
}

on the other side, you can use the destructuring expression for ES2015 to get the individual values.

function step2([server, data]){
  console.log(server); // print "myserver.com"
  console.log(data);   // print "so much data, very impresive"
  return Promise.resolve("done");
}

to call both promise, chaining them:

step1()
.then(step2)
.then((msg)=>{
  console.log(msg); // print "done"
})

In Visual Studio C++, what are the memory allocation representations?

This link has more information:

https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values

* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory

How to disable spring security for particular url

As @M.Deinum already wrote the answer.

I tried with api /api/v1/signup. it will bypass the filter/custom filter but an additional request invoked by the browser for /favicon.ico, so, I add this also in web.ignoring() and it works for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup", "/favicon.ico");
}

Maybe this is not required for the above question.

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

How to print a dictionary line by line in Python?

pprint.pprint() is a good tool for this job:

>>> import pprint
>>> cars = {'A':{'speed':70,
...         'color':2},
...         'B':{'speed':60,
...         'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
       'speed': 70},
 'B': {'color': 3,
       'speed': 60}}

Float and double datatype in Java

This will give error:

public class MyClass {
    public static void main(String args[]) {
        float a = 0.5;
    }
}

/MyClass.java:3: error: incompatible types: possible lossy conversion from double to float float a = 0.5;

This will work perfectly fine

public class MyClass {
    public static void main(String args[]) {
        double a = 0.5;
    }
}

This will also work perfectly fine

public class MyClass {
    public static void main(String args[]) {
        float a = (float)0.5;
    }
}

Reason : Java by default stores real numbers as double to ensure higher precision.

Double takes more space but more precise during computation and float takes less space but less precise.

Set up Python 3 build system with Sublime Text 3

And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:

From this:

{
    "cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

To this:

{
    "cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

You can modify depending on where your python is installed your python.

How to get random value out of an array?

I'm basing my answer off of @ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:

function &random_value(&$array, $default=null)
{
    $k = mt_rand(0, count($array) - 1);
    if (isset($array[$k])) {
        return $array[$k];
    } else {
        return $default;
    }
}

For more context, see my question over at Passing/Returning references to object + changing object is not working

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

How to check list A contains any value from list B?

You can check if a list is inside of another list with this

var list1 = new List<int> { 1, 2, 3, 4, 6 };
var list2 = new List<int> { 2, 3 };
bool a = list1.Any(c => list2.Contains(c));

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

Can we pass an array as parameter in any function in PHP?

even more cool, you can pass a variable count of parameters to a function like this:

function sendmail(...$users){
   foreach($users as $user){

   }
}

sendmail('user1','user2','user3');

JavaScript check if variable exists (is defined/initialized)

The most robust 'is it defined' check is with typeof

if (typeof elem === 'undefined')

If you are just checking for a defined variable to assign a default, for an easy to read one liner you can often do this:

elem = elem || defaultElem;

It's often fine to use, see: Idiomatic way to set default value in javascript

There is also this one liner using the typeof keyword:

elem = (typeof elem === 'undefined') ? defaultElem : elem;

How to fix Error: laravel.log could not be opened?

Maximum people's are suggesting to change file permission 777 or 775, which I believe not an appropriate approach to solve this problem. You just need to change the ownership of storage and bootstrap folder.

In below Image you can see all my files/folder are under the root user(except storage and bootstrap, because I changed the ownership ),but I logged in as a administrator(before changing ownership) that's why it always giving permission denied. So I need to change the ownership of this two folder to administrator

So how I did this, go to your project directory and run below commands. sudo chown -R yourusername:www-data storage, sudo chmod -R ug+w storage, sudo chown -R yourusername:www-data bootstrap, sudo chmod -R ug+w bootstrap

How to get the absolute path to the public_html folder?

You can also use dirname in dirname to get to where you want to be.

Example of usage:

For Joomla, modules will always be installed in /public_html/modules/mod_modulename/

So, from within a file within the module's folder, to get to the Joomla install-root on any server , I could use: $path = dirname(dirname(dirname(__FILE__)));

The same goes for Wordpress, where plugins are always in wp-content/plugins/

Hope this helps someone.

Checking whether a variable is an integer or not

If you need to do this, do

isinstance(<var>, int)

unless you are in Python 2.x in which case you want

isinstance(<var>, (int, long))

Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do:

class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True

This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.

BUT

The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't:

try:
    x += 1
except TypeError:
    ...

This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.

How to Test Facebook Connect Locally

You don't have to do anything difficult!

Facebook ? Settings ? Basic:
write "localhost" in the "App Domains" field then click on "+Add Platform" choose "Web Site".

After that, in the "Site Url" field write your localhost url
(e.g.: http://localhost:1337/something).

This will allow you to test your facebook plugins locally.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

Catch a thread's exception in the caller thread in Python

One method I am fond of is based on the observer pattern. I define a signal class which my thread uses to emit exceptions to listeners. It can also be used to return values from threads. Example:

import threading

class Signal:
    def __init__(self):
        self._subscribers = list()

    def emit(self, *args, **kwargs):
        for func in self._subscribers:
            func(*args, **kwargs)

    def connect(self, func):
        self._subscribers.append(func)

    def disconnect(self, func):
        try:
            self._subscribers.remove(func)
        except ValueError:
            raise ValueError('Function {0} not removed from {1}'.format(func, self))


class WorkerThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(WorkerThread, self).__init__(*args, **kwargs)
        self.Exception = Signal()
        self.Result = Signal()

    def run(self):
        if self._Thread__target is not None:
            try:
                self._return_value = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
            except Exception as e:
                self.Exception.emit(e)
            else:
                self.Result.emit(self._return_value)

if __name__ == '__main__':
    import time

    def handle_exception(exc):
        print exc.message

    def handle_result(res):
        print res

    def a():
        time.sleep(1)
        raise IOError('a failed')

    def b():
        time.sleep(2)
        return 'b returns'

    t = WorkerThread(target=a)
    t2 = WorkerThread(target=b)
    t.Exception.connect(handle_exception)
    t2.Result.connect(handle_result)
    t.start()
    t2.start()

    print 'Threads started'

    t.join()
    t2.join()
    print 'Done'

I do not have enough experience of working with threads to claim that this is a completely safe method. But it has worked for me and I like the flexibility.

Adding Table rows Dynamically in Android

Create an init() function and point the table layout. Then create the needed rows and columns.

   public void init() {
            TableLayout stk = (TableLayout) findViewById(R.id.table_main);
            TableRow tbrow0 = new TableRow(this);
            TextView tv0 = new TextView(this);
            tv0.setText(" Sl.No ");
            tv0.setTextColor(Color.WHITE);
            tbrow0.addView(tv0);
            TextView tv1 = new TextView(this);
            tv1.setText(" Product ");
            tv1.setTextColor(Color.WHITE);
            tbrow0.addView(tv1);
            TextView tv2 = new TextView(this);
            tv2.setText(" Unit Price ");
            tv2.setTextColor(Color.WHITE);
            tbrow0.addView(tv2);
            TextView tv3 = new TextView(this);
            tv3.setText(" Stock Remaining ");
            tv3.setTextColor(Color.WHITE);
            tbrow0.addView(tv3);
            stk.addView(tbrow0);
            for (int i = 0; i < 25; i++) {
                TableRow tbrow = new TableRow(this);
                TextView t1v = new TextView(this);
                t1v.setText("" + i);
                t1v.setTextColor(Color.WHITE);
                t1v.setGravity(Gravity.CENTER);
                tbrow.addView(t1v);
                TextView t2v = new TextView(this);
                t2v.setText("Product " + i);
                t2v.setTextColor(Color.WHITE);
                t2v.setGravity(Gravity.CENTER);
                tbrow.addView(t2v);
                TextView t3v = new TextView(this);
                t3v.setText("Rs." + i);
                t3v.setTextColor(Color.WHITE);
                t3v.setGravity(Gravity.CENTER);
                tbrow.addView(t3v);
                TextView t4v = new TextView(this);
                t4v.setText("" + i * 15 / 32 * 10);
                t4v.setTextColor(Color.WHITE);
                t4v.setGravity(Gravity.CENTER);
                tbrow.addView(t4v);
                stk.addView(tbrow);
            }

        }

Call init function in your onCreate method:

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

        init();
    }

Layout file like:

 <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#3d455b"
        android:layout_alignParentLeft="true" >

        <HorizontalScrollView
            android:id="@+id/hscrll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:id="@+id/RelativeLayout1"
                android:layout_width="fill_parent"
                android:layout_gravity="center"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TableLayout
                    android:id="@+id/table_main"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true" >
                </TableLayout>
            </RelativeLayout>
        </HorizontalScrollView>
    </ScrollView>

Will look like:

enter image description here

Difference between jar and war in Java

A war file is a special jar file that is used to package a web application to make it easy to deploy it on an application server. The content of the war file must follow a defined structure.

PHP, Get tomorrows date from date

By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );

echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );

Should do it

git is not installed or not in the PATH

while @vitocorleone is technically correct. If you have already installed, there is no need to reinstall. You just need to add it to your path. You will find yourself doing this for many of the tools for the mean stack so you should get used to doing it. You don't want to have to be in the folder that holds the executable to run it.

  • Control Panel --> System and Security --> System
  • click on Advanced System Settings on the left.
  • make sure you are on the advanced tab
  • click the Environment Variables button on the bottom
  • under system variables on the bottom find the Path variable
  • at the end of the line type (assuming this is where you installed it)

    ;C:\Program Files (x86)\git\cmd

  • click ok, ok, and ok to save

This essentially tells the OS.. if you don't find this executable in the folder I am typing in, look in Path to fide where it is.

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Does Java support default parameter values?

NO, But we have alternative in the form of function overloading.

called when no parameter passed

void operation(){

int a = 0;
int b = 0;

} 

called when "a" parameter was passed

void operation(int a){

int b = 0;
//code

} 

called when parameter b passed

void operation(int a , int b){
//code
} 

jquery/javascript convert date string to date

Use moment js for any date operation.

https://momentjs.com/

_x000D_
_x000D_
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

How to add Headers on RESTful call using Jersey Client API

Try this!

Client client = ClientBuilder.newClient();

String jsonStr = client
            .target("http:....")
            .request(MediaType.APPLICATION_JSON)

            .header("WM_SVC.NAME", "RegistryService")
            .header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")

            .get(String.class);

P.S You can add any number of headers like this!

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

"Debug only" code that should run only when "turned on"

An instance variable would probably be the way to do what you want. You could make it static to persist the same value for the life of the program (or thread depending on your static memory model), or make it an ordinary instance var to control it over the life of an object instance. If that instance is a singleton, they'll behave the same way.

#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif

void foo()
{   
  // ...
#if DEBUG
  if (s_bDoDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }
#endif
 // ...
}

Just to be complete, pragmas (preprocessor directives) are considered a bit of a kludge to use to control program flow. .NET has a built-in answer for half of this problem, using the "Conditional" attribute.

private /*static*/ bool doDebugOnlyCode = false; 
[Conditional("DEBUG")]
void foo()
{   
  // ...    
  if (doDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }    
  // ...
}

No pragmas, much cleaner. The downside is that Conditional can only be applied to methods, so you'll have to deal with a boolean variable that doesn't do anything in a release build. As the variable exists solely to be toggled from the VS execution host, and in a release build its value doesn't matter, it's pretty harmless.

Insert some string into given string at given index in Python

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

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

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

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

    """

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

Gradle, Android and the ANDROID_HOME SDK location

I have the same problem, seems the sample code can not find the android environment, instead to try to fix that I just remove the sample code from settings.gradle and then the installation goes fine.

after that just import the project in eclipse and that's all :)

How to get last N records with activerecord?

Updated Answer (2020)

You can get last N records simply by using last method:

Record.last(N)

Example:

User.last(5)

Returns 5 users in descending order by their id.

Deprecated (Old Answer)

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
        puts result.pop
end

The cast to value type 'Int32' failed because the materialized value is null

You are using aggregate function which not getting the items to perform action , you must verify linq query is giving some result as below:

var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Arduino Tools > Serial Port greyed out

So I did with sudo usermod -a -G dialout <my-username>.

You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.

How to handle button clicks using the XML onClick within Fragments

I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.

public class StartFragment extends Fragment implements OnClickListener{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_start, container, false);

        Button b = (Button) v.findViewById(R.id.StartButton);
        b.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.StartButton:

            ...

            break;
        }
    }
}

Difference between the Apache HTTP Server and Apache Tomcat?

Apache is an HTTP web server which serve as HTTP.

Apache Tomcat is a java servlet container. It features same as web server but is customized to execute java servlet and JSP pages.

How to check the Angular version?

ng --version command returns the details of the version of Angular CLI installed

How to get phpmyadmin username and password

Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.

Python SQLite: database is locked

in my case ,the error happened when a lot of concurrent process trying to read/write to the same table. I used retry to workaround the issue

def _retry_if_exception(exception):
    return isinstance(exception, Exception)

@retry(retry_on_exception=_retry_if_exception,
       wait_random_min=1000,
       wait_random_max=5000,
       stop_max_attempt_number=5)
def execute(cmd, commit=True):
   c.execute(cmd)
   c.conn.commit()

Best way to specify whitespace in a String.Split operation

If you just call:

string[] ssize = myStr.Split(null); //Or myStr.Split()

or:

string[] ssize = myStr.Split(new char[0]);

then white-space is assumed to be the splitting character. From the string.Split(char[]) method's documentation page.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Always, always, always read the documentation!

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

Java constant examples (Create a java file having only constants)

Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

public final class Constants {

    private Constants() {
            // restrict instantiation
    }

    public static final double PI = 3.14159;
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

Usage :

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;

public class Calculations {

        public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

See wiki link : http://en.wikipedia.org/wiki/Constant_interface

Compare and contrast REST and SOAP web services?

In day to day, practical programming terms, the biggest difference is in the fact that with SOAP you are working with static and strongly defined data exchange formats where as with REST and JSON data exchange formatting is very loose by comparison. For example with SOAP you can validate that exchanged data matches an XSD schema. The XSD therefore serves as a 'contract' on how the client and the server are to understand how the data being exchanged must be structured.

JSON data is typically not passed around according to a strongly defined format (unless you're using a framework that supports it .. e.g. http://msdn.microsoft.com/en-us/library/jj870778.aspx or implementing json-schema).

In-fact, some (many/most) would argue that the "dynamic" secret sauce of JSON goes against the philosophy/culture of constraining it by data contracts (Should JSON RESTful web services use data contract)

People used to working in dynamic loosely typed languages tend to feel more comfortable with the looseness of JSON while developers from strongly typed languages prefer XML.

http://www.mnot.net/blog/2012/04/13/json_or_xml_just_decide

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

Validate date in dd/mm/yyyy format using JQuery Validate

This validates dd/mm/yyy dates. Edit your jquery.validate.js and add these.

Reference(Regex): Regex to validate date format dd/mm/yyyy

dateBR: function( value, element ) {
    return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(value);
}

messages: {
    dateBR: "Invalid date."
}

classRuleSettings: {
    dateBR: {dateBR: true}
}

Usage:

$( "#myForm" ).validate({
    rules: {
        field: {
            dateBR: true
        }
    }
});

Why Doesn't C# Allow Static Methods to Implement an Interface?

Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.

Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.

For example:

Repository GetRepository<T>()
{
  //need to call T.IsQueryable, but can't!!!
  //need to call T.RowCount
  //need to call T.DoSomeStaticMath(int param)
}

...
var r = GetRepository<Customer>()

Unfortunately, I can come up only with "ugly" alternatives:

  • Use reflection Ugly and beats the idea of interfaces and polymorphism.

  • Create completely separate factory class

    This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.

  • Instantiate and then call the desired interface method

    This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.

Example:

public class Customer 
{
  //create new customer
  public Customer(Transaction t) { ... }

  //open existing customer
  public Customer(Transaction t, int id) { ... }

  void SomeOtherMethod() 
  { 
    //do work...
  }
}

in order to use instantination for solving the static interface problem we need to do the following thing:

public class Customer: IDoSomeStaticMath
{
  //create new customer
  public Customer(Transaction t) { ... }

  //open existing customer
  public Customer(Transaction t, int id) { ... }

  //dummy instance
  public Customer() { IsDummy = true; }

  int DoSomeStaticMath(int a) { }

  void SomeOtherMethod() 
  { 
    if(!IsDummy) 
    {
      //do work...
    }
  }
}

This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

After all else failed...

My solution was to change the layout file from

= stylesheet_link_tag "reset-min", 'application'

to

= stylesheet_link_tag 'application'

And it worked! (You can put the reset file inside the manifest.)

Is there a quick change tabs function in Visual Studio Code?

Use Sublime Text Keymaps. So much more intuitive.

?k?m

Import Sublime Text Keymaps:

Name: Sublime Text Keymap and Settings Importer
Id: ms-vscode.sublime-keybindings
Description: Import Sublime Text settings and keybindings into VS Code.
Version: 4.0.3
Publisher: Microsoft
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

DataGrid get selected rows' column values

UPDATED

To get the selected rows try:

IList rows = dg.SelectedItems;

You should then be able to get to the column value from a row item.

OR

DataRowView row = (DataRowView)dg.SelectedItems[0];

Then:

row["ColumnName"];

Hiding table data using <div style="display:none">

<style type="text/css">
.hidden { display:none; }
</style>

<table>
<tr><th>Test Table</th><tr>
<tr class="hidden"><td>123456789</td></tr>
<tr class="hidden"><td>123456789</td></tr>
<tr class="hidden"><td>123456789</td></tr>
</table>

And instead of:

<div style="display:none;">
<table>...</table>
</div>

you had better use: ...

Ajax post request in laravel 5 return error 500 (Internal Server Error)

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array

Listing all the folders subfolders and files in a directory using php

Here is A simple function with scandir& array_filter that do the job. filter needed files using regex. I removed . .. and hidden files like .htaccess, you can also customise output using <ul> and colors and also customise errors in case no scan or empty dirs!.

function getAllContentOfLocation($loc)
{   
    $scandir = scandir($loc);

    $scandir = array_filter($scandir, function($element){

        return !preg_match('/^\./', $element);

    });

    if(empty($scandir)) echo '<li style="color:red">Empty Dir</li>';

    foreach($scandir as $file){

        $baseLink = $loc . DIRECTORY_SEPARATOR . $file;

        echo '<ol>';
        if(is_dir($baseLink))
        {
            echo '<li style="font-weight:bold;color:blue">'.$file.'</li>';
            getAllContentOfLocation($baseLink);

        }else{
            echo '<li>'.$file.'</li>';
        }
        echo '</ol>';
    }
}
//Call function and set location that you want to scan 
getAllContentOfLocation('../app');

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

How to change users in TortoiseSVN

If you want to remove only one saved password, e.g. for "user1":

  • Go to the saved password directory (*c:\Users\USERNAME\AppData\Roaming\Subversion\auth\svn.simple\*)
  • You will find several files in this folder (named with hash value)
  • Find the file which contains the username "user1", which you want to change (open it with Notepad).
  • Remove the file.
  • Next time you will connect to your SVN server, Tortoise will prompt you for new username and password.

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

List(of String) or Array or ArrayList

look to the List AddRange method here

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

Python logging: use milliseconds in time format

Adding msecs was the better option, Thanks. Here is my amendment using this with Python 3.5.3 in Blender

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")

Java 8 LocalDate Jackson format

The simplest solution (which supports deserialization and serialization as well) is

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate dateOfBirth;

While using the following dependencies in your project.

Maven

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.7</version>
</dependency>
<dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-jsr310</artifactId>
   <version>2.9.7</version>
</dependency>

Gradle

compile "com.fasterxml.jackson.core:jackson-databind:2.9.7"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.7"

No additional implementation of a ContextResolver, Serializer or Deserializer is required.

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

Is there a way to split a widescreen monitor in to two or more virtual monitors?

There may be other potential solutions out there (I am still looking) but thus far in my search for the same functionality, I have only found http://www.maxivista.com/ . As far as I can tell through, it only supports a dual monitor, not multiple.

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Inspired by [@JulieLerman 's DDD MSDN Mag Article 2013][1]

    public class ShippingContext : BaseContext<ShippingContext>
{
  public DbSet<Shipment> Shipments { get; set; }
  public DbSet<Shipper> Shippers { get; set; }
  public DbSet<OrderShippingDetail> Order { get; set; } //Orders table
  public DbSet<ItemToBeShipped> ItemsToBeShipped { get; set; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Ignore<LineItem>();
    modelBuilder.Ignore<Order>();
    modelBuilder.Configurations.Add(new ShippingAddressMap());
  }
}

public class BaseContext<TContext>
  DbContext where TContext : DbContext
{
  static BaseContext()
  {
    Database.SetInitializer<TContext>(null);
  }
  protected BaseContext() : base("DPSalesDatabase")
  {}
}   

"If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database. However, this context must not inherit from BaseContext." JL

How to set height property for SPAN

Use

.title{
  display: inline-block;
  height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

$(document).ready not Working

Instead of using this:

$(document).ready(function() { /* your code */ });

Use this:

jQuery(function($) { /* your code */ })(jQuery);

It is more concise and does the same thing, it also doesn't depend on the $ variable to be the jQuery object.

How to use a WSDL file to create a WCF service (not make a call)

Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.

svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)

This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.

Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.

Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.

jQuery: more than one handler for same event

There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.

Crude, maybe, but it definitely should work.

Dump a mysql database to a plaintext (CSV) backup from the command line

You can use below script to get the output to csv files. One file per table with headers.

for tn in `mysql --batch --skip-page --skip-column-name --raw -uuser -ppassword -e"show tables from mydb"`
do 
mysql -uuser -ppassword mydb -B -e "select * from \`$tn\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $tn.csv
done

user is your user name, password is the password if you don't want to keep typing the password for each table and mydb is the database name.

Explanation of the script: The first expression in sed, will replace the tabs with "," so you have fields enclosed in double quotes and separated by commas. The second one insert double quote in the beginning and the third one insert double quote at the end. And the final one takes care of the \n.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

no target device found android studio 2.1.1

go to "Run>edit configuration>" and select "Open select deployment target dialog" from deployment target option then run your app it will show you a dialog box you can choose your target device from there, enjoy it.

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

'DataFrame' object has no attribute 'sort'

sort() was deprecated for DataFrames in favor of either:

sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

Calling an executable program using awk

I was able to have this done via below method

cat ../logs/em2.log.1 |grep -i 192.168.21.15 |awk '{system(`date`); print $1}'

awk has a function called system it enables you to execute any linux bash command within the output of awk.

Disposing WPF User Controls

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
    {
        // Dispose of any Disposable items here
    }

Timeout a command in bash without unnecessary delay

I prefer "timelimit", which has a package at least in debian.

http://devel.ringlet.net/sysutils/timelimit/

It is a bit nicer than the coreutils "timeout" because it prints something when killing the process, and it also sends SIGKILL after some time by default.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

You can recreate your server repository and push from your local branch master to the server master.

On your remote server:

mkdir myrepo.git
cd myrepo.git
git init --bare

OK, from your local branch:

git push origin master:master

Running Bash commands in Python

Call it with subprocess

import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")

The error you are getting seems to be because there is no swap module on the server, you should install swap on the server then run the script again

Removing packages installed with go get

#!/bin/bash

goclean() {
 local pkg=$1; shift || return 1
 local ost
 local cnt
 local scr

 # Clean removes object files from package source directories (ignore error)
 go clean -i $pkg &>/dev/null

 # Set local variables
 [[ "$(uname -m)" == "x86_64" ]] \
 && ost="$(uname)";ost="${ost,,}_amd64" \
 && cnt="${pkg//[^\/]}"

 # Delete the source directory and compiled package directory(ies)
 if (("${#cnt}" == "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
 elif (("${#cnt}" > "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
 fi

 # Reload the current shell
 source ~/.bashrc
}

Usage:

# Either launch a new terminal and copy `goclean` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

goclean github.com/your-username/your-repository

What is the maximum characters for the NVARCHAR(MAX)?

By default, nvarchar(MAX) values are stored exactly the same as nvarchar(4000) values would be, unless the actual length exceed 4000 characters; in that case, the in-row data is replaced by a pointer to one or more seperate pages where the data is stored.

If you anticipate data possibly exceeding 4000 character, nvarchar(MAX) is definitely the recommended choice.

Source: https://social.msdn.microsoft.com/Forums/en-US/databasedesign/thread/d5e0c6e5-8e44-4ad5-9591-20dc0ac7a870/

How to implement 2D vector array?

If you know the (maximum) number of rows and columns beforehand, you can use resize() to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column].

How to change Navigation Bar color in iOS 7?

Add only This code in your ViewContorller or in your AppDelegate

if([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
{
    //This is For iOS6
    [self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
else
{
    //This is For iOS7
    [self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}

what is the use of $this->uri->segment(3) in codeigniter pagination

CodeIgniter User Guide says:

$this->uri->segment(n)

Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up

The segment numbers would be this:

1. news
2. local
3. metro
4. crime_is_up

So segment refers to your url structure segment. By the above example, $this->uri->segment(3) would be 'metro', while $this->uri->segment(4) would be 'crime_is_up'.

How to make inline plots in Jupyter Notebook larger?

To adjust the size of one figure:

import matplotlib.pyplot as plt

fig=plt.figure(figsize=(15, 15))

To change the default settings, and therefore all your plots:

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = [15, 15]

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

If your computer is a 64bit, all you need to do is uninstall your Java x86 version and install a 64bit version. I had the same problem and this worked. Nothing further needs to be done.

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant