Programs & Examples On #Gdbm

GNU dbm is a key-value database. It provides primitives for storing key/data pairs, searching and retrieving the data by its key and deleting a key along with its data.

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Change default text in input type="file"?

My solution...

HTML :

<input type="file" id="uploadImages" style="display:none;" multiple>

<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">

Jquery:

$('#callUploadImages').click(function(){

    $('#uploadImages').click();
});

$('#uploadImages').change(function(){

    var uploadImages = $(this);
    $('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});

This is just evil :D

MSOnline can't be imported on PowerShell (Connect-MsolService error)

I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;

I also use the newer command:

Connect-SPOService

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

I'd do it like this:

<select onchange="jsFunction()">
  <option value="" disabled selected style="display:none;">Label</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

If you want you could have the same label as the first option, which in this case is 1. Even better: put a label in there for the choices in the box.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

How to load my app from Eclipse to my Android phone instead of AVD

Yes! You can Debug Android Application While you are developing them follow these steps.. Make sure that you have PC suite of the mobile manufacturer. For Example:if you are using samsung you should have samsung kies

1.Enable USB debugging on your device:Settings > Applications > Development > USB debugging 2.Enable Unknownresources:Settings>Unknowresoures
3.Connect your device to PC
4.Select your Application Right click it: RunAS>Run configurations>Choose Device>Target Select your device Run.

You can also without using debugging cable.For that you need to install Airdroid in your device.After installing enter the link in your browser and Drag and Drop .apk file.

Happy Coding!

How to list all methods for an object in Ruby?

Suppose User has_many Posts:

u = User.first
u.posts.methods
u.posts.methods - Object.methods

How do you dynamically allocate a matrix?

I have this grid class that can be used as a simple matrix if you don't need any mathematical operators.

/**
 * Represents a grid of values.
 * Indices are zero-based.
 */
template<class T>
class GenericGrid
{
    public:
        GenericGrid(size_t numRows, size_t numColumns);

        GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue);

        const T & get(size_t row, size_t col) const;

        T & get(size_t row, size_t col);

        void set(size_t row, size_t col, const T & inT);

        size_t numRows() const;

        size_t numColumns() const;

    private:
        size_t mNumRows;
        size_t mNumColumns;
        std::vector<T> mData;
};


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns);
}


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns, inInitialValue);
}


template<class T>
const T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx) const
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx)
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
void GenericGrid<T>::set(size_t rowIdx, size_t colIdx, const T & inT)
{
    mData[rowIdx*mNumColumns + colIdx] = inT;
}


template<class T>
size_t GenericGrid<T>::numRows() const
{
    return mNumRows;
}


template<class T>
size_t GenericGrid<T>::numColumns() const
{
    return mNumColumns;
}

window.location.reload with clear cache

I wrote this javascript script and included it in the header (before anything loads). It seems to work. If the page was loaded more than one hour ago or the situation is undefined it will reload everything from server. The time of one hour = 3600000 milliseconds can be changed in the following line: if(alter > 3600000)

With regards, Birke

<script type="text/javascript">
//<![CDATA[
function zeit()
{
    if(document.cookie)
    {
        a = document.cookie;
        cookiewert = "";
        while(a.length > 0)
        {
            cookiename = a.substring(0,a.indexOf('='));
            if(cookiename == "zeitstempel")
            {
                cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';'));
                break;
            }
            a = a.substring(a.indexOf(cookiewert)+cookiewert.length+1,a.length);
        }
        if(cookiewert.length > 0)
        {
            alter = new Date().getTime() - cookiewert;

            if(alter > 3600000)
            {   
                document.cookie = "zeitstempel=" + new Date().getTime() + ";";
                location.reload(true);
            }
            else
            {
                return;
            }
        }
        else
        {
            document.cookie = "zeitstempel=" + new Date().getTime() + ";";
            location.reload(true);
        }
    }
    else
    {
        document.cookie = "zeitstempel=" + new Date().getTime() + ";";
        location.reload(true);
    }
}
zeit();
//]]>
</script>

What's the best visual merge tool for Git?

If you use visual studio, Team Explorer built-in tool is a very nice tool to resolve git merge conflicts.

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

Module AppRegistry is not registered callable module (calling runApplication)

I have solved it, just closing the current Metro Bundler and restarting by type comment below.

npm start -- --reset-cache

Can you overload controller methods in ASP.NET MVC?

I have faced same issue in my application too. Without Modifiyig any Method information, I have provided [ActionName("SomeMeaningfulName")] on Action head. issue resolved

[ActionName("_EmployeeDetailsByModel")]
        public PartialViewResult _EmployeeDetails(Employee model)
        {
            // Some Operation                
                return PartialView(model);
            }
        }

[ActionName("_EmployeeDetailsByModelWithPagination")]
        public PartialViewResult _EmployeeDetails(Employee model,int Page,int PageSize)
        {

                // Some Operation
                return PartialView(model);

        }

What is the difference between background and background-color

I've found that you cannot set a gradient with background-color.

This works:

background:linear-gradient(to right, rgba(255,0,0,0), rgba(255,255,255,1));

This doesn't:

background-color:linear-gradient(to right, rgba(255,0,0,0), rgba(255,255,255,1));

Gitignore not working

Also, comments have to be on their own line. They can't be put after an entry. So this won't work:

/node_modules  # DON'T COMMENT HERE (since nullifies entire line)

But this will work:

# fine to comment here
/node_modules

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Make one div visible and another invisible

I don't think that you really want an iframe, do you?

Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?

For your white box / extra space issue, try

style="display: none;"

instead of

style="visibility: hidden;"

use current date as default value for a column

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page in column properties set Default value or binding to : 'getdate()'

Get class name of object as string in Swift

I've been looking for this answer off and on for a while. I use GKStateMachine and like to observe state changes and wanted an easy way to see just the class name. I'm not sure if it's just iOS 10 or Swift 2.3, but in that environment, the following does exactly what I want:

let state:GKState?
print("Class Name: \(String(state.classForCoder)")

// Output:    
// Class Name: GKState

How to display svg icons(.svg files) in UI using React Component?

You can also import .svg, .jpg, .png, .ttf, etc. files like:

  ReactDOM.render(
      <img src={require("./svg/kiwi.svg")}/>,
      document.getElementById('root')
  );

global variable for all controller and views

I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders. Here is what i did:

  1. Created the Provider SettingsServiceProvider
    php artisan make:provider SettingsServiceProvider
  1. Created the Model i needed (GlobalSettings)
    php artisan make:model GlobalSettings
  1. Edited the generated register method in \App\Providers\SettingsServiceProvider. As you can see, I retrieve my settings using the eloquent model for it with Setting::all().
 

    public function register()
    {
        $this->app->singleton('App\GlobalSettings', function ($app) {
            return new GlobalSettings(Setting::all());
        });
    }

 
  1. Defined some useful parameters and methods (including the constructor with the needed Collection parameter) in GlobalSettings
 

    class GlobalSettings extends Model
    {
        protected $settings;
        protected $keyValuePair;

        public function __construct(Collection $settings)
        {
            $this->settings = $settings;
            foreach ($settings as $setting){
                $this->keyValuePair[$setting->key] = $setting->value;
            }
        }

        public function has(string $key){ /* check key exists */ }
        public function contains(string $key){ /* check value exists */ }
        public function get(string $key){ /* get by key */ }
    }

 
  1. At last I registered the provider in config/app.php
 

    'providers' => [
        // [...]

        App\Providers\SettingsServiceProvider::class
    ]

 
  1. After clearing the config cache with php artisan config:cache you can use your singleton as follows.
 

    $foo = app(App\GlobalSettings::class);
    echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";

 

You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.

This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.


I forgot to include the boot method of SettingsServiceProvider, to make the settings variable global available in views, so here you go:

 

    public function boot(GlobalSettings $settinsInstance)
    {
        View::share('globalsettings', $settinsInstance);
    }

 

Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings instance as parameter, so it can be injected by Laravel.

In blade template:

 

    {{ $globalsettings->get("company") }}

 

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Use this command

gcc -dM -E - < /dev/null

to get this

    #define _LP64 1
#define _STDC_PREDEF_H 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
#define __BIGGEST_ALIGNMENT__ 16
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __CHAR16_TYPE__ short unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __CHAR_BIT__ 8
#define __DBL_DECIMAL_DIG__ 17
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __DBL_DIG__ 15
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define __DBL_HAS_DENORM__ 1
#define __DBL_HAS_INFINITY__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __DBL_MANT_DIG__ 53
#define __DBL_MAX_10_EXP__ 308
#define __DBL_MAX_EXP__ 1024
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __DBL_MIN_10_EXP__ (-307)
#define __DBL_MIN_EXP__ (-1021)
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __DEC128_EPSILON__ 1E-33DL
#define __DEC128_MANT_DIG__ 34
#define __DEC128_MAX_EXP__ 6145
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __DEC128_MIN_EXP__ (-6142)
#define __DEC128_MIN__ 1E-6143DL
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __DEC32_EPSILON__ 1E-6DF
#define __DEC32_MANT_DIG__ 7
#define __DEC32_MAX_EXP__ 97
#define __DEC32_MAX__ 9.999999E96DF
#define __DEC32_MIN_EXP__ (-94)
#define __DEC32_MIN__ 1E-95DF
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __DEC64_EPSILON__ 1E-15DD
#define __DEC64_MANT_DIG__ 16
#define __DEC64_MAX_EXP__ 385
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __DEC64_MIN_EXP__ (-382)
#define __DEC64_MIN__ 1E-383DD
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DECIMAL_BID_FORMAT__ 1
#define __DECIMAL_DIG__ 21
#define __DEC_EVAL_METHOD__ 2
#define __ELF__ 1
#define __FINITE_MATH_ONLY__ 0
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DECIMAL_DIG__ 9
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __FLT_DIG__ 6
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __FLT_EVAL_METHOD__ 0
#define __FLT_HAS_DENORM__ 1
#define __FLT_HAS_INFINITY__ 1
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MANT_DIG__ 24
#define __FLT_MAX_10_EXP__ 38
#define __FLT_MAX_EXP__ 128
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __FLT_MIN_10_EXP__ (-37)
#define __FLT_MIN_EXP__ (-125)
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __FLT_RADIX__ 2
#define __FXSR__ 1
#define __GCC_ASM_FLAG_OUTPUTS__ 1
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __GCC_HAVE_DWARF2_CFI_ASM 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_IEC_559 2
#define __GCC_IEC_559_COMPLEX 2
#define __GNUC_MINOR__ 3
#define __GNUC_PATCHLEVEL__ 0
#define __GNUC_STDC_INLINE__ 1
#define __GNUC__ 6
#define __GXX_ABI_VERSION 1010
#define __INT16_C(c) c
#define __INT16_MAX__ 0x7fff
#define __INT16_TYPE__ short int
#define __INT32_C(c) c
#define __INT32_MAX__ 0x7fffffff
#define __INT32_TYPE__ int
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
#define __INT8_C(c) c
#define __INT8_MAX__ 0x7f
#define __INT8_TYPE__ signed char
#define __INTMAX_C(c) c ## L
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INTMAX_TYPE__ long int
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_FAST64_TYPE__ long int
#define __INT_FAST8_MAX__ 0x7f
#define __INT_FAST8_TYPE__ signed char
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST8_TYPE__ signed char
#define __INT_MAX__ 0x7fffffff
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __LDBL_DIG__ 18
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __LDBL_HAS_DENORM__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __LDBL_HAS_QUIET_NAN__ 1
#define __LDBL_MANT_DIG__ 64
#define __LDBL_MAX_10_EXP__ 4932
#define __LDBL_MAX_EXP__ 16384
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __LDBL_MIN_10_EXP__ (-4931)
#define __LDBL_MIN_EXP__ (-16381)
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL
#define __LONG_MAX__ 0x7fffffffffffffffL
#define __LP64__ 1
#define __MMX__ 1
#define __NO_INLINE__ 1
#define __ORDER_BIG_ENDIAN__ 4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 3412
#define __PIC__ 2
#define __PIE__ 2
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __PTRDIFF_MAX__ 0x7fffffffffffffffL
#define __PTRDIFF_TYPE__ long int
#define __REGISTER_PREFIX__ 
#define __SCHAR_MAX__ 0x7f
#define __SEG_FS 1
#define __SEG_GS 1
#define __SHRT_MAX__ 0x7fff
#define __SIG_ATOMIC_MAX__ 0x7fffffff
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __SIG_ATOMIC_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __SIZEOF_FLOAT128__ 16
#define __SIZEOF_FLOAT80__ 16
#define __SIZEOF_FLOAT__ 4
#define __SIZEOF_INT128__ 16
#define __SIZEOF_INT__ 4
#define __SIZEOF_LONG_DOUBLE__ 16
#define __SIZEOF_LONG_LONG__ 8
#define __SIZEOF_LONG__ 8
#define __SIZEOF_POINTER__ 8
#define __SIZEOF_PTRDIFF_T__ 8
#define __SIZEOF_SHORT__ 2
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WCHAR_T__ 4
#define __SIZEOF_WINT_T__ 4
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __SIZE_TYPE__ long unsigned int
#define __SSE2_MATH__ 1
#define __SSE2__ 1
#define __SSE_MATH__ 1
#define __SSE__ 1
#define __SSP_STRONG__ 3
#define __STDC_HOSTED__ 1
#define __STDC_IEC_559_COMPLEX__ 1
#define __STDC_IEC_559__ 1
#define __STDC_ISO_10646__ 201605L
#define __STDC_NO_THREADS__ 1
#define __STDC_UTF_16__ 1
#define __STDC_UTF_32__ 1
#define __STDC_VERSION__ 201112L
#define __STDC__ 1
#define __UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define __UINT16_TYPE__ short unsigned int
#define __UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define __UINT32_TYPE__ unsigned int
#define __UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define __UINT64_TYPE__ long unsigned int
#define __UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define __UINT8_TYPE__ unsigned char
#define __UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define __UINTMAX_TYPE__ long unsigned int
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define __UINTPTR_TYPE__ long unsigned int
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST64_TYPE__ long unsigned int
#define __UINT_FAST8_MAX__ 0xff
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_LEAST16_MAX__ 0xffff
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __UINT_LEAST8_MAX__ 0xff
#define __UINT_LEAST8_TYPE__ unsigned char
#define __USER_LABEL_PREFIX__ 
#define __VERSION__ "6.3.0 20170406"
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_TYPE__ int
#define __WINT_MAX__ 0xffffffffU
#define __WINT_MIN__ 0U
#define __WINT_TYPE__ unsigned int
#define __amd64 1
#define __amd64__ 1
#define __code_model_small__ 1
#define __gnu_linux__ 1
#define __has_include(STR) __has_include__(STR)
#define __has_include_next(STR) __has_include_next__(STR)
#define __k8 1
#define __k8__ 1
#define __linux 1
#define __linux__ 1
#define __pic__ 2
#define __pie__ 2
#define __unix 1
#define __unix__ 1
#define __x86_64 1
#define __x86_64__ 1
#define linux 1
#define unix 1

What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Simple is that

Like:

DECLARE @DUENO BIGINT
SET @DUENO=5

SELECT 'ND'+STUFF('000000',6-LEN(RTRIM(@DueNo))+1,LEN(RTRIM(@DueNo)),RTRIM(@DueNo)) DUENO

How can I get the current network interface throughput statistics on Linux/UNIX?

I like iptraf but you probably have to install it and it seems to not being maintained actively anymore.

Why is there no SortedList in Java?

I think all the above do not answer this question due to following reasons,

  1. Since same functionality can be achieved by using other collections such as TreeSet, Collections, PriorityQueue..etc (but this is an alternative which will also impose their constraints i.e. Set will remove duplicate elements. Simply saying even if it does not impose any constraint, it does not answer the question why SortedList was not created by java community)
  2. Since List elements do not implements compare/equals methods (This holds true for Set & Map also where in general items do not implement Comparable interface but when we need these items to be in sorted order & want to use TreeSet/TreeMap,items should implement Comparable interface)
  3. Since List uses indexing & due to sorting it won't work (This can be easily handled introducing intermediate interface/abstract class)

but none has told the exact reason behind it & as I believe these kind of questions can be best answered by java community itself as it will have only one & specific answer but let me try my best to answer this as following,

As we know sorting is an expensive operation and there is a basic difference between List & Set/Map that List can have duplicates but Set/Map can not. This is the core reason why we have got a default implementation for Set/Map in form of TreeSet/TreeMap. Internally this is a Red Black Tree with every operation (insert/delete/search) having the complexity of O(log N) where due to duplicates List could not fit in this data storage structure.

Now the question arises we could also choose a default sorting method for List also like MergeSort which is used by Collections.sort(list) method with the complexity of O(N log N). Community did not do this deliberately since we do have multiple choices for sorting algorithms for non distinct elements like QuickSort, ShellSort, RadixSort...etc. In future there can be more. Also sometimes same sorting algorithm performs differently depending on the data to be sorted. Therefore they wanted to keep this option open and left this on us to choose. This was not the case with Set/Map since O(log N) is the best sorting complexity.

How do I align a label and a textarea?

Align the text area box to the label, not the label to the text area,

label {
    width: 180px;
    display: inline-block;
}

textarea{
    vertical-align: middle;
}

<label for="myfield">Label text</label><textarea id="myfield" rows="5" cols="30"></textarea>

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Javascript/Jquery Convert string to array

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

var traingIds = ${triningIdArray};

not

var traingIds = "${triningIdArray}";

std::string to float or double

   double myAtof ( string &num){
      double tmp;
      sscanf ( num.c_str(), "%lf" , &tmp);
      return tmp;
   }

git push rejected

When doing a push, try specifying the refspec for the upstream master:

git push upstream upstreammaster:master

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to force a WPF binding to refresh?

if you use mvvm and your itemssource is located in your vm. just call INotifyPropertyChanged for your collection property when you want to refresh.

OnPropertyChanged("YourCollectionProperty");

Interfaces with static fields in java for sharing 'constants'

I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.

Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.

If a client wants to compare cars prior to buying he can have a method like this:

public List<Decision> compareCars(List<I_Somecar> pCars);

An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.

X-Frame-Options Allow-From multiple domains

Strictly speaking no, you cant.

You can however specify X-Frame-Options: mysite.com and therefore allow subdomain1.mysite.com and subdomain2.mysite.com. But yes, that's still one domain. There happens to be some workaround for this, but I think it's easiest to read that directly at the RFC specs: https://tools.ietf.org/html/rfc7034

It's also worth to point out that the Content-Security-Policy (CSP) header's frame-ancestor directive obsoletes X-Frame-Options. Read more here.

Creating Roles in Asp.net Identity MVC 5

the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.

string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

                IdentityResult roleResult;
                foreach(var roleName in roleNames)
                {
                    if(!RoleManager.RoleExists(roleName))
                    {
                        roleResult = RoleManager.Create(new IdentityRole(roleName));
                    }
                }
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                UserManager.AddToRole("user", "role1");
                UserManager.AddToRole("user", "role2");
                context.SaveChanges();

What is Persistence Context?

A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. a database). In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.

Although Hibernate-related (a JPA provider), I think these links are useful:

http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch03.html

http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/architecture.html

In Java EE, a persistence context is normally accessed via an EntityManager.

http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html

The various states an entity can have and the transitions between these are described below:

http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/objectstate.html

http://gerrydevstory.com/wp-content/uploads/2012/05/jpa-state-transtition.png

Get all column names of a DataTable into string array using (LINQ/Predicate)

Try this (LINQ method syntax):

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();  

or in LINQ Query syntax:

string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
                        select dc.ColumnName).ToArray();

Cast is required, because Columns is of type DataColumnCollection which is a IEnumerable, not IEnumerable<DataColumn>. The other parts should be obvious.

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

How to get file_get_contents() to work with HTTPS?

Just add two lines in your php.ini file.

extension=php_openssl.dll

allow_url_include = On

its working for me.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:

var someval = document.getElementById('something')
if (someval && someval.value <> '') {

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

In my case URI, as it was defined on FB, was fine, but I was using Spring Security and it was adding ;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD to my URI so, it caused the mismatching.

https://m.facebook.com/v2.5/dialog/oauth?client_id=your-fb-id-code&response_type=code&redirect_uri=https://localizator.org/auth/facebook;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD&scope=email&state=b180578a-007b-48bc-bd81-4b08c6989e18

In order to avoid the URL rewriting I added disable-url-rewriting="true" to Spring Security config, in this way:

<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true"
      disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"/> 

And it fixed my problem.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
        HttpServletResponse response, @RequestParam("uuid") String uuid,
        @RequestParam("type") DocType type,
        @RequestParam("file") MultipartFile uploadfile)

Url would look like

http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT

I am passing two params (uuid and type) along with file upload. Hope this will help who don't have the complex json data to send.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message is pretty straightforward: getComputedStyle expects an Element as its first argument, and something else was passed to it.

If what you are really asking for is help with debugging your skin, you should make more of an effort to isolate the error.

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

How to tag an older commit in Git?

This is an old question, and the answers already given all work, but there's also a new option which can be considered.

If you're using SourceTree to manage your git repositories, you can right-click on any commit and add a tag to it. With another mouseclick you can also send the tag straight to the branch on origin.

How to stop line breaking in vim

Use :set nowrap .. works like a charm!

Google Maps JavaScript API RefererNotAllowedMapError

Removing the restrictions (to None) worked for me.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Use this style to change only the nested lists:

ol {
    counter-reset: item;
}

ol > li {
    counter-increment: item;
}

ol ol > li {
    display: block;
}

ol ol > li:before {
    content: counters(item, ".") ". ";
    margin-left: -20px;
}

How do I bind to list of checkbox values with AngularJS?

Try my baby:

**

myApp.filter('inputSelected', function(){
  return function(formData){
    var keyArr = [];
    var word = [];
    Object.keys(formData).forEach(function(key){
    if (formData[key]){
        var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
      for (var char = 0; char<keyCap.length; char++ ) {
        if (keyCap[char] == keyCap[char].toUpperCase()){
          var spacedLetter = ' '+ keyCap[char];
          word.push(spacedLetter);
        }
        else {
          word.push(keyCap[char]);
        }
      }
    }
    keyArr.push(word.join(''))
    word = [];
    })
    return keyArr.toString();
  }
})

**

Then for any ng-model with checkboxes, it will return a string of all the input you selected:

<label for="Heard about ITN">How did you hear about ITN?: *</label><br>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox" >Brother or Sister</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox" >Friend or Acquaintance</label>


{{formData.heardAboutItn | inputSelected }}

//returns Brother or Sister, Friend or Acquaintance

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

i am using like this.. its easy to understand first argument is mapStateToProps and second argument is mapDispatchToProps in the end connect with function/class.

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

Matching special characters and letters in regex

Try this regex:

/^[\w&.-]+$/

Also you can use test.

if ( pattern.test( qry ) ) {
  // valid
}

How to search JSON data in MySQL?

If you have MySQL version >= 5.7, then you can try this:

SELECT JSON_EXTRACT(name, "$.id") AS name
FROM table
WHERE JSON_EXTRACT(name, "$.id") > 3

Output:

+-------------------------------+
| name                          | 
+-------------------------------+
| {"id": "4", "name": "Betty"}  | 
+-------------------------------+


Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

How to compare two tags with git?

If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

how to delete installed library form react native project

From react-native --help

uninstall [options] uninstall and unlink native dependencies

Ex: react-native uninstall react-native-vector-icons

It will uninstall and unlink its dependencies.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

Is there a Subversion command to reset the working copy?

Delete the working copy from the OS and check it out again is simplest, but obviously not a single command.

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Why use static_cast<int>(x) instead of (int)x?

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.

A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).

A reinterpret_cast<>() (or a const_cast<>()) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is".

The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.

Let's assume these:

class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;

CMyBase  *pSomething; // filled somewhere

Now, these two are compiled the same way:

CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked

pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
                                     // Safe; as long as we checked
                                     // but harder to read

However, let's see this almost identical code:

CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert

pOther = (CMyOtherStuff*)(pSomething);            // No compiler error.
                                                  // Same as reinterpret_cast<>
                                                  // and it's wrong!!!

As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.

The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<".

pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
      // No compiler error.
      // but the presence of a reinterpret_cast<> is 
      // like a Siren with Red Flashing Lights in your code.
      // The mere typing of it should cause you to feel VERY uncomfortable.

That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.

How to style SVG <g> element?

You cannot add style to an SVG <g> element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green" on the <g> means an automatic fill="green" on its child <rect> (as long as it has no own fill specification).

Your only option is to add a new <rect> to the SVG and place it accordingly to match the <g> children's dimensions.

When do you use the "this" keyword?

I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.

How can I use ":" as an AWK field separator?

-F is an argument to awk itself:

$echo "1: " | awk -F":" '/1/ {print $1}'
1

@Transactional(propagation=Propagation.REQUIRED)

To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED, ISOLATION etc. you'll have to understand the basics of transaction management itself.

Read Trasaction management for more on explanation.

Shuffling a list of objects

#!/usr/bin/python3

import random

s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)

# print: [2, 4, 1, 3, 0]

How to connect to LocalDb

To locate a DB from SQL Server management studio can be done through browse - in the connect to database screen

enter image description here

Also make sure a local database is installed during installation:

enter image description here

how to display employee names starting with a and then b in sql

If you're asking about alphabetical order the syntax is:

SELECT * FROM table ORDER BY column

the best example I can give without knowing your table and field names:

SELECT * FROM employees ORDER BY name

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Cannot lower case button text in android studio

There is a property in <Button> that is android:textAllCaps="false" that make characters in which you want in your own Small and caps. By Default its became True so write this code and make textAllCaps=false then you can write text on button in small and Caps letter as per your requirement. Complete code for a Button which allow use to write letters as per our requirement.

 <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btnLogin"
            android:text="Login for Chat"
            android:textAllCaps="false"/>

How do I get this javascript to run every second?

window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

Adding dictionaries together, Python

If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items())

dic2 = dict(dic0, **dic1)

Or if you're happy to use one of the existing dicts:

dic0.update(dic1)

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

How to grep Git commit diffs or contents for a certain word?

If you want search for sensitive data in order to remove it from your git history (which is the reason why I landed here), there are tools for that. Github as a dedicated help page for that issue.

Here is the gist of the article:

The BFG Repo-Cleaner is a faster, simpler alternative to git filter-branch for removing unwanted data. For example, to remove your file with sensitive data and leave your latest commit untouched), run:

bfg --delete-files YOUR-FILE-WITH-SENSITIVE-DATA

To replace all text listed in passwords.txt wherever it can be found in your repository's history, run:

bfg --replace-text passwords.txt

See the BFG Repo-Cleaner's documentation for full usage and download instructions.

From inside of a Docker container, how do I connect to the localhost of the machine?

Edit: I ended up prototyping out the concept on GitHub. Check out: https://github.com/sivabudh/system-in-a-box


First, my answer is geared towards 2 groups of people: those who use a Mac, and those who use Linux.

The host network mode doesn't work on a Mac. You have to use an IP alias, see: https://stackoverflow.com/a/43541681/2713729

What is a host network mode? See: https://docs.docker.com/engine/reference/run/#/network-settings

Secondly, for those of you who are using Linux (my direct experience was with Ubuntu 14.04 LTS and I'm upgrading to 16.04 LTS in production soon), yes, you can make the service running inside a Docker container connect to localhost services running on the Docker host (eg. your laptop).

How?

The key is when you run the Docker container, you have to run it with the host mode. The command looks like this:

docker run --network="host" -id <Docker image ID>

When you do an ifconfig (you will need to apt-get install net-tools your container for ifconfig to be callable) inside your container, you will see that the network interfaces are the same as the one on Docker host (eg. your laptop).

It's important to note that I'm a Mac user, but I run Ubuntu under Parallels, so using a Mac is not a disadvantage. ;-)

And this is how you connect NGINX container to the MySQL running on a localhost.

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

center a row using Bootstrap 3

Instead of trying to center div's, just add this to your local css.

.col-md-offset-15 {
    margin-left: 12.4999999%;
}

which is roughly  offset-1 and half of offset-1. (8.333% + 4.166%) = 12.4999%

This worked for me.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can style li elements differently based on their class, their id or their ancestor elements:

li { /* styles all li elements*/
    list-style-type: none;
}

#ParentListID li { /* styles the li elements that have an ancestor element
                      of id="ParentListID" */
    list-style-type: bullet;
}

li.className { /* styles li elements of class="className" */
    list-style-type: bullet;
}

Or, to use the ancestor elements:

#navigationContainerID li { /* specifically styles the li elements with an ancestor of
                               id="navigationContainerID" */
    list-style-type: none;
}

li { /* then styles all other li elements that don't have that ancestor element */
    list-style-type: bullet;
}

Pandas How to filter a Series

In [5]:

import pandas as pd

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

s = pd.Series(test)
s = s[s != 1]
s
Out[0]:
383    3.000000
737    9.000000
833    8.166667
dtype: float64

Calling Non-Static Method In Static Method In Java

You could create an instance of the class you want to call the method on, e.g.

new Foo().nonStaticMethod();

How to create a private class method?

As of ruby 2.3.0

class Check
  def self.first_method
    second_method
  end

  private
  def self.second_method
    puts "well I executed"
  end
end

Check.first_method
#=> well I executed

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

PostgreSQL: export resulting data from SQL query to Excel/CSV

In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:

COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;

Note: The folder must be writable.

Use of Greater Than Symbol in XML

You can try to use CDATA to put all your symbols that don't work.

An example of something that will work in XML:

<![CDATA[
function matchwo(a,b) {
    if (a < b && a < 0) {
        return 1;
   } else {
       return 0;
   }
}
]]>

And of course you can use &lt; and &gt;.

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

Serving static web resources in Spring Boot & Spring Security application

Here is the ultimate solution, after 20+ hours of research.

Step 1. Add 'MvcConfig.java' to your project.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }
}

Step 2. Add configure(WebSecurity web) override to your SecurityConfig class

@Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**");
    }

Step 3. Place all static resources in webapp/resources/..

Read files from a Folder present in project

This was helpful for me, if you use the

var dir = Directory.GetCurrentDirectory()

the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName

then print the dir value and verify the path is giving you

Start service in Android

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

node.js require all files in a folder?

I have a folder /fields full of files with a single class each, ex:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

Drop this in fields/index.js to export each class:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!__hasProp.call(include, func)) continue;
      _results.push(exports[func] = include[func]);
    }
    return _results;
  }
};

fs.readdirSync('./fields/').forEach(collectExports);

This makes the modules act more like they would in Python:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

How can I include null values in a MIN or MAX?

The effect you want is to treat the NULL as the largest possible date then replace it with NULL again upon completion:

SELECT RecordId, MIN(StartDate), NULLIF(MAX(COALESCE(EndDate,'9999-12-31')),'9999-12-31') 
  FROM tmp GROUP BY RecordId

Per your fiddle this will return the exact results you specify under all conditions.

Changing file permission in Python

No need to remember flags. Remember that you can always do:

subprocess.call(["chmod", "a-w", "file/path])

Not portable but easy to write and remember:

  • u - user
  • g - group
  • o - other
  • a - all
  • + or - (add or remove permission)
  • r - read
  • w - write
  • x - execute

Refer man chmod for additional options and more detailed explanation.

How do I grep for all non-ASCII characters?

In perl

perl -ane '{ if(m/[[:^ascii:]]/) { print  } }' fileName > newFile

How to prevent "The play() request was interrupted by a call to pause()" error?

I've fixed it with some code bellow:

When you want play, use the following:

var video_play = $('#video-play');
video_play.on('canplay', function() {
 video_play.trigger('play');
});

Similarly, when you want pause:

var video_play = $('#video-play');
video_play.trigger('pause');

video_play.on('canplay', function() {
  video_play.trigger('pause');
});

Reading an Excel file in PHP

You have 2 choices as far as I know:

  1. Spreadsheet_Excel_Reader, which knows the Office 2003 binary format
  2. PHPExcel, which knows both Office 2003 as well as Excel 2007 (XML). (Follow the link, and you'll see they upgraded this library to PHPSpreadSheet)

PHPExcel uses Spreadsheet_Excel_Reader for the Office 2003 format.

Update: I once had to read some Excel files but I used the Office 2003 XML format in order to read them and told the people that were using the application to save and upload only that type of Excel file.

How to create a HashMap with two keys (Key-Pair, Value)?

You could create your key object something like this:

public class MapKey {

public  Object key1;
public Object key2;

public Object getKey1() {
    return key1;
}

public void setKey1(Object key1) {
    this.key1 = key1;
}

public Object getKey2() {
    return key2;
}

public void setKey2(Object key2) {
    this.key2 = key2;
}

public boolean equals(Object keyObject){

    if(keyObject==null)
        return false;

    if (keyObject.getClass()!= MapKey.class)
        return false;

    MapKey key = (MapKey)keyObject;

    if(key.key1!=null && this.key1==null)
        return false;

    if(key.key2 !=null && this.key2==null)
        return false;

    if(this.key1==null && key.key1 !=null)
        return false;

    if(this.key2==null && key.key2 !=null)
        return false;

    if(this.key1==null && key.key1==null && this.key2 !=null && key.key2 !=null)
        return this.key2.equals(key.key2);

    if(this.key2==null && key.key2==null && this.key1 !=null && key.key1 !=null)
        return this.key1.equals(key.key1);

    return (this.key1.equals(key.key1) && this.key2.equals(key2));
}

public int hashCode(){
    int key1HashCode=key1.hashCode();
    int key2HashCode=key2.hashCode();
    return key1HashCode >> 3 + key2HashCode << 5;
}

}

The advantage of this is: It will always make sure you are covering all the scenario's of Equals as well.

NOTE: Your key1 and key2 should be immutable. Only then will you be able to construct a stable key Object.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.

$(document).ready(function() is not working

You only get this error if jQuery is not correctly loaded, you can check with firebug what url its trying to load so you can see if your relative path is wrong.

Also, on a separate note, you can use $(function(){ as a shorthand to $(document).ready(function(){

Error: 'int' object is not subscriptable - Python

name1 = input("What's your name? ")
age1 = int(input ("how old are you? "))
twentyone = str(21 - int(age1))

if age1<21:
    print ("Hi, " + name1+ " you will be 21 in: " + twentyone + " years.")

else:
    print("You are over the age of 21")

Create a root password for PHPMyAdmin

To create root password in PHPMyAdmin in UI easy way, you can follow simple steps below:

  • Access phpMyAdmin with root account (no password) -> User accounts.

enter image description here

Click on root > Edit privileges

enter image description here

Then click on Change password

enter image description here

Enter your desired password -> Go

enter image description here

Logout and log-in again with new password

How do I get the current mouse screen coordinates in WPF?

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

TimeSpan(50); //ticks

Jupyter/IPython Notebooks: Shortcut for "run all"?

As of 5.5 you can run Kernel > Restart and Run All

How I could add dir to $PATH in Makefile?

By design make parser executes lines in a separate shell invocations, that's why changing variable (e.g. PATH) in one line, the change may not be applied for the next lines (see this post).

One way to workaround this problem, is to convert multiple commands into a single line (separated by ;), or use One Shell special target (.ONESHELL, as of GNU Make 3.82).

Alternatively you can provide PATH variable at the time when shell is invoked. For example:

PATH  := $(PATH):$(PWD)/bin:/my/other/path
SHELL := env PATH=$(PATH) /bin/bash

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

This function found here, works fine for me

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

List of IP addresses/hostnames from local network in Python

I have done following code to get the IP of MAC known device. This can be modified accordingly to obtain all IPs with some string manipulation. Hope this will help you.

#running windows cmd line  statement and put output into a string
cmd_out = os.popen("arp -a").read()
line_arr = cmd_out.split('\n')
line_count = len(line_arr)


#search in all lines for ip
for i in range(0, line_count):
    y = line_arr[i]
    z = y.find(mac_address)

    #if mac address is found then get the ip using regex matching
    if z > 0:
        ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

How can I draw vertical text with CSS cross-browser?

If CSS writing-mode: sideways-lr is what you prefer, and you happen to run into chromium/chrome based browser. You may try

{
  writing-mode: vertical-rl; 
  transform: rotate(180deg);
}

so all modern browsers support it now.

reference: https://bugs.chromium.org/p/chromium/issues/detail?id=680331#c4

How to call a php script/function on a html button click

the_function() {

$.ajax({url:"demo_test.php",success:function(result){

   alert(result); // will alert 1

 }});

}

// demo_test.php

<?php echo 1; ?>

Notes

  1. Include jquery library for using the jquery Ajax
  2. Keep the demo_test.php file in the same folder where your javascript file resides

How to include !important in jquery

If you really need to override css that has !important rules in it, for instance, in a case I ran into recently, overriding a wordpress theme required !important scss rules to break the theme, but since I was transpiling my code with webpack and (I assume this is why --)my css came along in the chain after the transpiled javascript, you can add a separate class rule in your stylesheet that overrides the first !important rule in the cascade, and toggle the heavier-weighted class rather than adjusting css dynamically. Just a thought.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

moving changed files to another branch for check-in

Sadly this happens to me quite regularly as well and I use git stash if I realized my mistake before git commit and use git cherry-pick otherwise, both commands are explained pretty well in other answers

I want to add a clarification for git checkout targetBranch: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally

@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch

However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch (clean and throwaway changes) or git stage + git checkout targetBranch (clean and save changes), simply running git checkout targetBranch will give an error:

error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting

nginx 502 bad gateway

If you're on Ubuntu, and all of the above has failed you, AppArmor is most likely to blame.

Here is a good guide how to fix it: https://www.digitalocean.com/community/tutorials/how-to-create-an-apparmor-profile-for-nginx-on-ubuntu-14-04

Long story short:

vi /etc/apparmor.d/nginx

Or

sudo aa-complain nginx
sudo service nginx restart

See everything working nicely... then

sudo aa-logprof

I still had problems with Nginx not being able to read error.log, even though it had all the permissions possible, including in Apparomor. I'm guessing it's got something to do with the order of the entries, or some interaction with Passenger or PHP-Fpm... I've run out of time to troubleshoot this and have gone back to Apache for now. (Apache performs much better too FYI.)

AppArmor just lets Nginx do whatever it wants if you just remove the profile:

 rm /etc/apparmor.d/nginx
 service apparmor reload

Shockingly, but hardly surprising, a lot of posts on fixing Nginx errors resorts to completely disabling SELinux or removing AppArmor. That's a bad idea because you lose protection from a whole lot of software. Just removing the Nginx profile is a better way to troubleshoot your config files. Once you know that the problem isn't in your Nginx config files, you can take the time to create a proper AppArmor profile.

Without an AppArmor profile, especially if you run something like Passenger too, I give your server about a month to get backdoored.

Remove all html tags from php string

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

Or if you have a content coming from the database;

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

How to run Gulp tasks sequentially one after the other

By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean, where you don't want to depend, but you need them to run before everything else.

I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this:

var runSequence = require('run-sequence');

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.

Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want.

However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.

Eclipse: Java was started but returned error code=13

This is caused when java is updated. You have to delete in environement path : C:**ProgramData\Oracle\Java\javapath**

col align right

How about this? Bootstrap 4

<div class="row justify-content-end">
    <div class="col-3">
        The content is positioned as if there was
        "col-9" classed div appending this one.
    </div>
</div>

ActiveRecord OR query

Rails 5 comes with an or method. (link to documentation)

This method accepts an ActiveRecord::Relation object. eg:

User.where(first_name: 'James').or(User.where(last_name: 'Scott'))

How to change cursor from pointer to finger using jQuery?

Update! New & improved! Find plugin @ GitHub!


On another note, while that method is simple, I've created a jQuery plug (found at this jsFiddle, just copy and past code between comment lines) that makes changing the cursor on any element as simple as $("element").cursor("pointer").

But that's not all! Act now and you'll get the hand functions position & ishover for no extra charge! That's right, 2 very handy cursor functions ... FREE!

They work as simple as seen in the demo:

$("h3").cursor("isHover"); // if hovering over an h3 element, will return true, 
    // else false
// also handy as
$("h2, h3").cursor("isHover"); // unless your h3 is inside an h2, this will be 
    // false as it checks to see if cursor is hovered over both elements, not just the last!
//  And to make this deal even sweeter - use the following to get a jQuery object
//       of ALL elements the cursor is currently hovered over on demand!
$.cursor("isHover");

Also:

$.cursor("position"); // will return the current cursor position as { x: i, y: i }
    // at anytime you call it!

Supplies are limited, so Act Now!

make div's height expand with its content

Use the span tag with display:inline-block css attached to it. You can then use CSS and manipulate it like a div in lots of ways but if you don't include a width or height it expands and retracts based on its content.

Hope that helps.

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

What's the difference between StaticResource and DynamicResource in WPF?

  1. StaticResource uses first value. DynamicResource uses last value.
  2. DynamicResource can be used for nested styling, StaticResource cannot.

Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type Grid}">
        <Style.Resources>
            <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
                <Setter Property="Background" Value="Pink"/>
            </Style>
        </Style.Resources>
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
        <Setter Property="Background" Value="LightGreen"/>
    </Style>
</ResourceDictionary>

In view:

<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ConflictingStyleWindow" Height="100" Width="100">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Style="{DynamicResource ConflictButton}" Content="Test"/>
    </Grid>
</Window>

StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.

StaticResource StaticResource

DynamicResource DynamicResource

Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.

StaticResource will throw an error when the root-level style (LightGreen) is removed.

How to scale an Image in ImageView to keep the aspect ratio

Yo don't need any java code. You just have to :

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />

The key is in the match parent for width and height

How do I escape the wildcard/asterisk character in bash?

SHORT ANSWER

Like others have said - you should always quote the variables to prevent strange behaviour. So use echo "$foo" in instead of just echo $foo.

LONG ANSWER

I do think this example warrants further explanation because there is more going on than it might seem on the face of it.

I can see where your confusion comes in because after you ran your first example you probably thought to yourself that the shell is obviously doing:

  1. Parameter expansion
  2. Filename expansion

So from your first example:

me$ FOO="BAR * BAR"
me$ echo $FOO

After parameter expansion is equivalent to:

me$ echo BAR * BAR

And after filename expansion is equivalent to:

me$ echo BAR file1 file2 file3 file4 BAR

And if you just type echo BAR * BAR into the command line you will see that they are equivalent.

So you probably thought to yourself "if I escape the *, I can prevent the filename expansion"

So from your second example:

me$ FOO="BAR \* BAR"
me$ echo $FOO

After parameter expansion should be equivalent to:

me$ echo BAR \* BAR

And after filename expansion should be equivalent to:

me$ echo BAR \* BAR

And if you try typing "echo BAR \* BAR" directly into the command line it will indeed print "BAR * BAR" because the filename expansion is prevented by the escape.

So why did using $foo not work?

It's because there is a third expansion that takes place - Quote Removal. From the bash manual quote removal is:

After the preceding expansions, all unquoted occurrences of the characters ‘\’, ‘'’, and ‘"’ that did not result from one of the above expansions are removed.

So what happens is when you type the command directly into the command line, the escape character is not the result of a previous expansion so BASH removes it before sending it to the echo command, but in the 2nd example, the "\*" was the result of a previous Parameter expansion, so it is NOT removed. As a result, echo receives "\*" and that's what it prints.

Note the difference between the first example - "*" is not included in the characters that will be removed by Quote Removal.

I hope this makes sense. In the end the conclusion in the same - just use quotes. I just thought I'd explain why escaping, which logically should work if only Parameter and Filename expansion are at play, didn't work.

For a full explanation of BASH expansions, refer to:

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions

How do I make a transparent canvas in html5?

Canvases are transparent by default.

Try setting a page background image, and then put a canvas over it. If nothing is drawn on the canvas, you can fully see the page background.

Think of a canvas as like painting on a glass plate.

Function names in C++: Capitalize or not?

It all depends on your definition of correct. There are many ways in which you can evaluate your coding style. Readability is an important one (for me). That is why I would use the my_function way of writing function names and variable names.

How to allow only integers in a textbox?

Another solution is to use a RangeValidator where you set Type="Integer" like this:

<asp:RangeValidator runat="server"
    id="valrNumberOfPreviousOwners"
    ControlToValidate="txtNumberOfPreviousOwners"
    Type="Integer"
    MinimumValue="0"
    MaximumValue="999"
    CssClass="input-error"
    ErrorMessage="Please enter a positive integer."
    Display="Dynamic">
</asp:RangeValidator>

You can set reasonable values for the MinimumValue and MaximumValue attributes too.

ListView with OnItemClickListener

In Java as other suggest

listitem.setClickable(false);

Or in xml:

android:clickable="false"

It works very fine

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

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

If you are trying to execute your program/application from the command prompt. Just make sure to restart your cmd after you have changed the JAVA_HOME var. Very simple but easily missed sometimes.

How to change the order of DataFrame columns?

Hackiest method in the book

df.insert(0, "test", df["mean"])
df = df.drop(columns=["mean"]).rename(columns={"test": "mean"})

Laravel 5 - redirect to HTTPS

Alternatively, If you are using Apache then you can use .htaccess file to enforce your URLs to use https prefix. On Laravel 5.4, I added the following lines to my .htaccess file and it worked for me.

RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How to asynchronously call a method in Java

This is not really related but if I was to asynchronously call a method e.g. matches(), I would use:

private final static ExecutorService service = Executors.newFixedThreadPool(10);
public static Future<Boolean> matches(final String x, final String y) {
    return service.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return x.matches(y);
        }

    });
}

Then to call the asynchronous method I would use:

String x = "somethingelse";
try {
    System.out.println("Matches: "+matches(x, "something").get());
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

I have tested this and it works. Just thought it may help others if they just came for the "asynchronous method".

Clear all fields in a form upon going back with browser back button

If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.

$(window).load(function() {
    $('form').get(0).reset(); //clear form data on page load
});

Reading a single char in Java

Maybe you could try this code:

import java.io.*;
public class Test
{
public static void main(String[] args)
{
try
  {
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  String userInput = in.readLine();
  System.out.println("\n\nUser entered -> " + userInput);
  }
  catch(IOException e)
  {
  System.out.println("IOException has been caught");
  }
 }
}

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));



        }
    }

How to use workbook.saveas with automatic Overwrite

To split the difference of opinion

I prefer:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

Unfamiliar symbol in algorithm: what does ? mean?

yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".

http://en.wikipedia.org/wiki/Quantification

What is makeinfo, and how do I get it?

For Centos , I solve it by installing these packages.

yum install texi2html texinfo 

Dont worry if there is no entry for makeinfo. Just run

make all

You can do it similarly for ubuntu using sudo.

ImportError: No module named - Python

This is if you are building a package and you are finding error in imports. I learnt it the hard way.The answer isn't to add the package to python path or to do it programatically (what if your module gets installed and your command adds it again?) thats a bad way.

The right thing to do is: 1) Use virtualenv pyvenv-3.4 or something similar 2) Activate the development mode - $python setup.py develop

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

How to flush output of print function?

Since Python 3.3, you can force the normal print() function to flush without the need to use sys.stdout.flush(); just set the "flush" keyword argument to true. From the documentation:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Run PHP Task Asynchronously

Spawning new processes on the server using exec() or directly on another server using curl doesn't scale all that well at all, if we go for exec you are basically filling your server with long running processes which can be handled by other non web facing servers, and using curl ties up another server unless you build in some sort of load balancing.

I have used Gearman in a few situations and I find it better for this sort of use case. I can use a single job queue server to basically handle queuing of all the jobs needing to be done by the server and spin up worker servers, each of which can run as many instances of the worker process as needed, and scale up the number of worker servers as needed and spin them down when not needed. It also let's me shut down the worker processes entirely when needed and queues the jobs up until the workers come back online.

Effective swapping of elements of an array in Java

If you want to swap string. it's already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

How to install SignTool.exe for Windows 10

It's 2019 now :) For anyone wondering, here's where you'll find it:

C:\Program Files (x86)\Windows Kits\10\App Certification Kit

Screenshot:


enter image description here

Edit: Still in the same place in 2020.

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

Is there any simple way to convert .xls file to .csv file? (Excel)

Checkout the .SaveAs() method in Excel object.

wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)

Or following:

public static void SaveAs()
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];

    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];

    thisCell.Value2 = "This is a test.";

    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    wbWorkbook.Close(false, "", true);
}

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Bootstrap close responsive menu "on click"

This worked for me. I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default. 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class.

$('#ChangeToggle').on('click', function (e) {

        if ($('.navbar-collapse').hasClass('in')) {
            $('.navbar-collapse').removeClass('in');
            e.stopPropagation();
        } else {
            $('.navbar-collapse').addClass('in');
            $('.navbar-collapse').collapse();
        }

    });

Create GUI using Eclipse (Java)

There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..

WindowBuilder Pro GUI Designer - eclipse marketplace

WindowBuilder Pro GUI Designer - Google code home page

and

Jigloo SWT/Swing GUI Builder - eclipse market place

Jigloo SWT/Swing GUI Builder - home page

The window builder is quite better tool..

But IMHO, GUIs created by those tools have really ugly and unmanageable code..

How to type ":" ("colon") in regexp?

use \\: instead of \:.. the \ has special meaning in java strings.

How do I revert all local changes in Git managed project to previous state?

Look into git-reflog. It will list all the states it remembers (default is 30 days), and you can simply checkout the one you want. For example:

$ git init > /dev/null
$ touch a
$ git add .
$ git commit -m"Add file a" > /dev/null
$ echo 'foo' >> a
$ git commit -a -m"Append foo to a" > /dev/null
$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
$ git reset --hard HEAD^^ > /dev/null
$ cat a
foo
b
c
$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
$ cat a
foo
b
c
d

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Short answer

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

Long answer

The reason that the "Z" is not included is because datetime.now() and even datetime.utcnow() return timezone naive datetimes, that is to say datetimes with no timezone information associated. To get a timezone aware datetime, you need to pass a timezone as an argument to datetime now. For example:

from datetime import datetime, timezone

datetime.utcnow()
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253)
# This is timezone naive

datetime.now(timezone.utc)
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253, tzinfo=datetime.timezone.utc)
# This is timezone aware

Once you have a timezone aware timestamp, isoformat will include a timezone designation. Thus, you can then get an ISO 8601 timestamp via:

datetime.now(timezone.utc).isoformat()
#> '2020-09-03T20:53:07.337670+00:00'

"+00:00" is a valid ISO 8601 timezone designation for UTC. If you want to have "Z" instead of "+00:00", you have to do the replacement yourself:

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
#> '2020-09-03T20:53:07.337670Z'

Convert XML to JSON (and back) using Javascript

The best way to do it using server side as client side doesn't work well in all scenarios. I was trying to build online json to xml and xml to json converter using javascript and I felt almost impossible as it was not working in all scenarios. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

How do you launch the JavaScript debugger in Google Chrome?

To open the dedicated ‘Console’ panel, either:

  • Use the keyboard shortcuts
    • On Windows and Linux: Ctrl + Shift + J
    • On Mac: Cmd + Option + J
  • Select the Chrome Menu icon, menu -> More Tools -> JavaScript Console. Or if the Chrome Developer Tools are already open, press the ‘Console’ tab.

Please refer here

How to restart service using command prompt?

To restart a running service:

net stop "service name" && net start "service name"

However, if you don't know if the service is running in the first place and want to restart or start it, use this:

net stop "service name" & net start "service name"

This works if the service is already running or not.

For reference, here is the documentation on conditional processing symbols.

How to open a new form from another form

You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.

It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.

Fastest way to compute entropy in Python

Uniformly distributed data (high entropy):

s=range(0,256)

Shannon entropy calculation step by step:

import collections
import math

# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]

# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]

# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy 
8.0

One-liner (assuming import collections):

def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])

A proper function:

import collections
import math

def H(s):
    probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
    e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]    
    return sum(e_x)

Test cases - English text taken from CyberChef entropy estimator:

>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104

How to concatenate two layers in keras?

Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

Result:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

What is the best way to determine a session variable is null or empty in C#?

Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.

public class SessionProxy
{
    private HttpSessionState session; // use dependency injection for testability
    public SessionProxy( HttpSessionState session )
    {
       this.session = session;  //might need to throw an exception here if session is null
    }

    public DateTime LastUpdate
    {
       get { return this.session["LastUpdate"] != null
                         ? (DateTime)this.session["LastUpdate"] 
                         : DateTime.MinValue; }
       set { this.session["LastUpdate"] = value; }
    }

    public string UserLastName
    {
       get { return (string)this.session["UserLastName"]; }
       set { this.session["UserLastName"] = value; }
    }
}

Only numbers. Input number in React

Define an input with an onChange() method like below (in my case, childState contains the state, passed down to this child component).

<input
   ...
   value={this.props.childState.volume}
   ...
   onChange={(e) => handleChangeInteger(e, {volume: e.target.value})}
/>

One approach I used was to install validatorJS (npm install validator --save)

I then defined a function handleChangeInteger, which takes an object that will be used to change your state, in this case, {volume: e.target.value}. Note: I needed the OR condition to allow my input to be blank, otherwise it would not let the user backspace (delete) the last integer if they wanted the field blank.

const handleChangeInteger = (e, obj_to_return) => {
  if (validator.isInt(e.target.value) || e.target.value == '') {
    this.props.childSetState(obj_to_return)
  }
}

The user will now not be allowed to type anything other than backspace, 0-9, or e (this is a number..) in the input field.

I referenced this post to create my solution: https://stackoverflow.com/a/45676912/6169225

Difference between const reference and normal parameter

The difference is more prominent when you are passing a big struct/class.

struct MyData {
    int a,b,c,d,e,f,g,h;
    long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);

when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

in both cases, the original data cannot be modified from inside the function.

EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

R dates "origin" must be supplied

by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".

(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)

Is there a RegExp.escape function in JavaScript?

In jQuery UI's autocomplete widget (version 1.9.1) they use a slightly different regular expression (line 6753), here's the regular expression combined with bobince's approach.

RegExp.escape = function( value ) {
     return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}

How to implement drop down list in flutter?

Use this code.

class PlayerPreferences extends StatefulWidget {
  final int numPlayers;
  PlayerPreferences({this.numPlayers});

  @override
  _PlayerPreferencesState createState() => _PlayerPreferencesState();
}

class _PlayerPreferencesState extends State<PlayerPreferences> {
  int dropDownValue = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton(
        value: dropDownValue,
        onChanged: (int newVal){
          setState(() {
            dropDownValue = newVal;
          });
        },
        items: [
          DropdownMenuItem(
            value: 0,
            child: Text('Yellow'),
          ),
          DropdownMenuItem(
            value: 1,
            child: Text('Red'),
          ),
          DropdownMenuItem(
            value: 2,
            child: Text('Blue'),
          ),
          DropdownMenuItem(
            value: 3,
            child: Text('Green'),
          ),
        ],
      ),
    );
  }
}

and in the main body we call as

class ModeSelection extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          child: PlayerPreferences(),
        ) ,
      ),
    );
  }
}

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

How do I do word Stemming or Lemmatization?

Martin Porter wrote Snowball (a language for stemming algorithms) and rewrote the "English Stemmer" in Snowball. There are is an English Stemmer for C and Java.

He explicitly states that the Porter Stemmer has been reimplemented only for historical reasons, so testing stemming correctness against the Porter Stemmer will get you results that you (should) already know.

From http://tartarus.org/~martin/PorterStemmer/index.html (emphasis mine)

The Porter stemmer should be regarded as ‘frozen’, that is, strictly defined, and not amenable to further modification. As a stemmer, it is slightly inferior to the Snowball English or Porter2 stemmer, which derives from it, and which is subjected to occasional improvements. For practical work, therefore, the new Snowball stemmer is recommended. The Porter stemmer is appropriate to IR research work involving stemming where the experiments need to be exactly repeatable.

Dr. Porter suggests to use the English or Porter2 stemmers instead of the Porter stemmer. The English stemmer is what's actually used in the demo site as @StompChicken has answered earlier.

Appending a line to a file only if it does not already exist

use awk

awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

How to hide the title bar for an Activity in XML with existing custom theme

To Hide both Title and Action bar I did this:

In activity tag of Manifest:

android:theme="@style/AppTheme.NoActionBar"

In Activity.java before setContentView:

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

i.e.,

//Remove title bar

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

//Remove notification bar

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

NOTE: You need to keep these lines before setContentView

How to delete an SVN project from SVN repository

I too felt like the accepted answer was a bit misleading as it could lead to a user inadvertently deleting multiple Projects. It is not accurate to state that the words Repository, Project and Directory are ambiguous within the context of SVN. They have specific meanings, even if the system itself doesn't enforce those meanings. The community and more importantly the SVN Clients have an agreed upon understanding of these terms which allow them to Tag, Branch and Merge.

Ideally this will help clear any confusion. As someone that has had to go from git to svn for a few projects, it can be frustrating until you learn that SVN branching and SVN projects are really talking about folder structures.

SVN Terminology

Repository

The database of commits and history for your folders and files. A repository can contain multiple 'projects' or no projects.

Project

A specific SVN folder structure which enables SVN tools to perform tagging, merging and branching. SVN does not inherently support branching. Branching was added later and is a result of a special folder structure as follows:

  • /project
    • /tags
    • /branches
    • /trunk

Note: Remember, an SVN 'Project' is a term used to define a specific folder strcuture within a Repository

Projects in a Repository

Repository Layout

As a repository is just a database of the files and directory commits, it can host multiple projects. When discussing Repositories and Projects be sure the correct term is being used.

Removing a Repository could mean removing multiple Projects!

Local SVN Directory (.svn directory at root)

When using a URL commits occur automatically.

  • svn co http://svn.server.local/svn/myrepo
  • cd myrepo

  • Remove a Project: svn rm skunkworks + svn commit

  • Remove a Directory: svn rm regulardir/subdir + svn commit
  • Remove a Project (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/app1
  • Remove a Directory (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/regulardir

Because an SVN Project is really a specific directory structure, removing a project is the same as removing a directory.

SVN Repository Management

There are several SVN servers available to host your repositories. The management of repositories themselves are typically done through the admin consoles of the servers. For example, Visual SVN allows you to create Repositories (databases), directories and Projects. But you cannot remove files, manage commits, rename folders, etc. from within the server console as those are SVN specific tasks. The SVN server typically manages the creation of a repository. Once a repository has been created and you have a new URL, the rest of your work is done through the svn command.

How to access the services from RESTful API in my angularjs page?

The $http service can be used for general purpose AJAX. If you have a proper RESTful API, you should take a look at ngResource.

You might also take a look at Restangular, which is a third party library to handle REST APIs easy.

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

Pointers in JavaScript?

JavaScript doesn't support passing primitive types by reference. There is a workaround, though.

Put all the variables you need to pass in an object. In this case, there's only one variable, x. Instead of passing the variable, pass the variable name as a string, which is "x".

_x000D_
_x000D_
var variables = {x:0};_x000D_
function a(x)_x000D_
{_x000D_
    variables[x]++;_x000D_
}_x000D_
a("x");_x000D_
alert(variables.x);
_x000D_
_x000D_
_x000D_

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

The apk must be signed with the same certificates as the previous version

My [silly] mistake was that i used app-debug.apk file instead of app-release.apk file. You need to to choose "release" in "Build Variants" frame when you generate signed APK. The app-release.apk file should be located under "app\release" folder in your project root.

How do I get the path of the current executed file in Python?

If the code is coming from a file, you can get its full name

sys._getframe().f_code.co_filename

You can also retrieve the function name as f_code.co_name

Sending email from Azure

I would never recommend SendGrid. I took up their free account offer and never managed to send a single email - all got blocked - I spent days trying to resolve it. When I enquired why they got blocked, they told me that free accounts share an ip address and if any account abuses that ip by sending spam - then everyone on the shared ip address gets blocked - totally useless. Also if you use them - do not store your email key in a git public repository as anyone can read the key from there (using a crawler) and use your chargeable account to send bulk emails.

A free email service which I've been using reliably with an Azure website is to use my Gmail (Google mail) account. That account has an option for using it with applications - once you enable that, then email can be sent from your azure website. Pasting in sample send code as the port to use (587) is not obvious.

  public static void SendMail(MailMessage Message)
    {
        SmtpClient client = new SmtpClient();
        client.Host = EnvironmentSecret.Instance.SmtpHost; // smtp.googlemail.com
        client.Port = 587;
        client.UseDefaultCredentials = false;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Credentials = new NetworkCredential(
            EnvironmentSecret.Instance.NetworkCredentialUserName,
            EnvironmentSecret.Instance.NetworkCredentialPassword);
        client.Send(Message);
    }

Android Fragment no view found for ID?

I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.

The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().

You didn't show us your onCreate() method, so perhaps this is the same problem.

Convert named list to vector with values only

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)

Index all *except* one item in python

>>> l = range(1,10)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:2] 
[1, 2]
>>> l[3:]
[4, 5, 6, 7, 8, 9]
>>> l[:2] + l[3:]
[1, 2, 4, 5, 6, 7, 8, 9]
>>> 

See also

Explain Python's slice notation

Load content with ajax in bootstrap modal

Here is how I solved the issue, might be useful to some:

Ajax modal doesn't seem to be available with boostrap 2.1.1

So I ended up coding it myself:

$('[data-toggle="modal"]').click(function(e) {
  e.preventDefault();
  var url = $(this).attr('href');
  //var modal_id = $(this).attr('data-target');
  $.get(url, function(data) {
      $(data).modal();
  });
});

Example of a link that calls a modal:

<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
    <img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>

I now send the whole modal markup through ajax.

Credits to drewjoh

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

REASON

This happens because for now they only ship 64bit JRE with Android Studio for Windows which produces glitches in 32 bit systems.

SOLUTION

  • do not use the embedded JDK: Go to File -> Project Structure dialog, uncheck "Use embedded JDK" and select the 32-bit JRE you've installed separately in your system
  • decrease the memory footprint for Gradle in gradle.properties(Project Properties), for eg set it to -Xmx768m.

For more details: https://code.google.com/p/android/issues/detail?id=219524

How to get all count of mongoose model?

You should give an object as argument

userModel.count({name: "sam"});

or

userModel.count({name: "sam"}).exec(); //if you are using promise

or

userModel.count({}); // if you want to get all counts irrespective of the fields

On the recent version of mongoose, count() is deprecated so use

userModel.countDocuments({name: "sam"});