Programs & Examples On #Cgdb

cgdb is a lightweight curses (terminal-based) interface to the GNU Debugger (GDB). In addition to the standard gdb console, cgdb provides a split screen view that displays the source code as it executes. The keyboard interface is modeled after vim, so vim users should feel at home using cgdb.

Unit testing with Spring Security

You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).

cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.

It could work like following:

public class MyUserDetails implements UserDetails {
    // this is your custom UserDetails implementation to serve as a principal
    // implement the Spring methods and add your own methods as appropriate
}

public class MyUserHolder {
    public static MyUserDetails getUserDetails() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        if (a == null) {
            return null;
        } else {
            return (MyUserDetails) a.getPrincipal();
        }
    }
}

public class MyUserAwareController {        
    MyUserDetails currentUser;

    public void setCurrentUser(MyUserDetails currentUser) { 
        this.currentUser = currentUser;
    }

    // controller code
}

Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:

<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
    <aop:scoped-proxy/>
</bean>

<bean id="controller" class="MyUserAwareController">
    <property name="currentUser" ref="userDetails"/>
    <!-- other props -->
</bean>

Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:

protected void setUp() {
    // existing init code

    MyUserDetails user = new MyUserDetails();
    // set up user as you wish
    controller.setCurrentUser(user);
}

Hope this helps!

How can I make Visual Studio wrap lines at 80 characters?

I don't think you can make VS wrap at 80 columns (I'd find that terribly annoying) but you can insert a visual guideline at 80 columns so you know when is a good time to insert a newline.

Details on inserting a guideline at 80 characters for 3 different versions of visual studio.

JPA Query.getResultList() - use in a generic way

If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:

Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual", 
        MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);

The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.

@Entity
class MyTest {
    @Id String name;
    int age;
}

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Reverse a changelist submission

You cannot undo a successful changelist submission, but you can reverse previously submitted changes in two ways:

Rollback restores a file or set of files back to a specified changelist, date or revision. Any changes made after that point in time are not retained. Back out removes specific changes made at a given changelist, date or revision but allows a user to keep changes made in subsequent revisions.

For details please refer to https://www.perforce.com/perforce/r13.1/manuals/p4v/Working_with_changelists.html

Create a text file for download on-the-fly

No need to store it anywhere. Just output the content with the appropriate content type.

<?php
    header('Content-type: text/plain');
?>Hello, world.

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"');

Block Comments in a Shell Script

if you can dodge the single quotes:

__='
blah blah comment.
'

SQL Server 2008 can't login with newly created user

SQL Server was not configured to allow mixed authentication.

Here are steps to fix:

  1. Right-click on SQL Server instance at root of Object Explorer, click on Properties
  2. Select Security from the left pane.
  3. Select the SQL Server and Windows Authentication mode radio button, and click OK.

    enter image description here

  4. Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.

Swift: print() vs println() vs NSLog()

There's another method called dump() which can also be used for logging:

func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

Dumps an object’s contents using its mirror to standard output.

From Swift Standard Library Functions

CSS technique for a horizontal line with words in the middle

I have tried most of the ways suggested but ends with some problems like full width, or Not suitable for dynamic content. Finally i modified a code, and works perfectly. This example code will draw those lines before and after, and it is flexible in content change. Center aligned too.

HTML

        <div style="text-align:center"> 
            <h1>
                <span >S</span>
            </h1> 
        </div> 

        <div style="text-align:center"> 
            <h1>
                <span >Long text</span>
            </h1> 
        </div> 

CSS

      h1 {
            display: inline-block;
            position: relative;
            text-align: center;
        }

        h1 span {
            background: #fff;
            padding: 0 10px;
            position: relative;
            z-index: 1;
        }

        h1:before {
            background: #ddd;
            content: "";
            height: 1px;
            position: absolute;
            top: 50%;
            width: calc(100% + 50px);//Support in modern browsers
            left: -25px;
        }

        h1:before {
            left: ;
        }

Result: https://jsfiddle.net/fasilkk/vowqfnb9/

Mobile Redirect using htaccess

Thanks Tim Stone, naunu, and Kevin Bond, those answers really helped me. Here is my adaption of your code. I added the functionality to be redirected back to the desktop site from m.example.com in case the user does not visit the site with a mobile device. Additionally I added an environment variable to preserve http/https requests:

# Set an environment variable for http/https.
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=ps:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=ps:http]

# Check if m=1 is set and set cookie 'm' equal to 1.
RewriteCond %{QUERY_STRING} (^|&)m=1(&|$)
RewriteRule ^ - [CO=m:1:example.com]

# Check if m=0 is set and set cookie 'm' equal to 0.
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
RewriteRule ^ - [CO=m:0:example.com]

# Cookie can't be set and read in the same request so check.
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
RewriteRule ^ - [S=1]

# Check if this looks like a mobile device.
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
RewriteCond %{HTTP:Profile} !^$
# Check if we're not already on the mobile site.
RewriteCond %{HTTP_HOST} !^m\.
# Check if cookie is not set to force desktop site.
RewriteCond %{HTTP_COOKIE} !^.*m=0.*$ [NC]
# Now redirect to the mobile site preserving http or https.
RewriteRule ^ %{ENV:ps}://m.example.com%{REQUEST_URI} [R,L]

# Check if this looks like a desktop device.
RewriteCond %{HTTP_USER_AGENT} "!(android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile)" [NC]
# Check if we're on the mobile site.
RewriteCond %{HTTP_HOST} ^m\.
# Check if cookie is not set to force mobile site.
RewriteCond %{HTTP_COOKIE} !^.*m=1.*$ [NC]
# Now redirect to the mobile site preserving http or https.
RewriteRule ^ %{ENV:ps}://example.com%{REQUEST_URI} [R,L]

This seems to work fine except one thing: When I'm on the desktop site with a desktop device and I visit m.example.com/?m=1, I'm redirected to example.com. When I try again, I "stay" at m.example.com. It seems as if the cookie isn't set and/or read correctly the first time.

Maybe there is a better way to determine if the device is a desktop device, I just negated the device detection from above.

And I'm wondering if this way all mobile devices are detected. In Tim Stone's and naunu's code that part is much larger.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

JavaScript - Hide a Div at startup (load)

Using CSS you can just set display:none for the element in a CSS file or in a style attribute

#div { display:none; }
<div id="div"></div>



<div style="display:none"></div>

or having the js just after the div might be fast enough too, but not as clean

C++ where to initialize static const

Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:

#include <string>

class foo {
public:
   foo();
   foo( int );
private:
   inline static const std::string s { "foo" };
};

"Object doesn't support this property or method" error in IE11

Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.

Use <META http-equiv="X-UA-Compatible" content="IE=9"> ideally in the masterpage so all pages in your site get the workaround.

Avoiding NullPointerException in Java

All in all to avoid statement

if (object != null) {
    ....
}
  1. since java 7 you can use Objects methods:

    Objects.isNull(object)

    Objects.nonNull(object)

    Objects.requireNonNull(object)

    Objects.equals(object1, object2)

  2. since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

  1. rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

    Preconditions.checkNotNull(object);

  2. In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

  1. When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)

Programmatically saving image to Django ImageField

Another possible way to do that:

from django.core.files import File

with open('path_to_file', 'r') as f:   # use 'rb' mode for python3
    data = File(f)
    model.image.save('filename', data, True)

nvm is not compatible with the npm config "prefix" option:

This may be a conflict with your local installation of Node (if you had it installed via another way than NVM in the past). You should delete this instance of node:

  1. remove node_modules sudo rm -rf /usr/local/lib/node_modules
  2. remove node sudo rm /usr/local/bin/node
  3. remove node link cd /usr/local/bin && ls -l | grep "../lib/node_modules/" | awk '{print $9}'| xargs rm

After you cant install nvm

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

What is the most effective way for float and double comparison?

I found that the Google C++ Testing Framework contains a nice cross-platform template-based implementation of AlmostEqual2sComplement which works on both doubles and floats. Given that it is released under the BSD license, using it in your own code should be no problem, as long as you retain the license. I extracted the below code from http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-internal.h and added the license on top.

Be sure to #define GTEST_OS_WINDOWS to some value (or to change the code where it's used to something that fits your codebase - it's BSD licensed after all).

Usage example:

double left  = // something
double right = // something
const FloatingPoint<double> lhs(left), rhs(right);

if (lhs.AlmostEquals(rhs)) {
  //they're equal!
}

Here's the code:

// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee)
//
// The Google C++ Testing Framework (Google Test)


// This template class serves as a compile-time function from size to
// type.  It maps a size in bytes to a primitive type with that
// size. e.g.
//
//   TypeWithSize<4>::UInt
//
// is typedef-ed to be unsigned int (unsigned integer made up of 4
// bytes).
//
// Such functionality should belong to STL, but I cannot find it
// there.
//
// Google Test uses this class in the implementation of floating-point
// comparison.
//
// For now it only handles UInt (unsigned int) as that's all Google Test
// needs.  Other types can be easily added in the future if need
// arises.
template <size_t size>
class TypeWithSize {
 public:
  // This prevents the user from using TypeWithSize<N> with incorrect
  // values of N.
  typedef void UInt;
};

// The specialization for size 4.
template <>
class TypeWithSize<4> {
 public:
  // unsigned int has size 4 in both gcc and MSVC.
  //
  // As base/basictypes.h doesn't compile on Windows, we cannot use
  // uint32, uint64, and etc here.
  typedef int Int;
  typedef unsigned int UInt;
};

// The specialization for size 8.
template <>
class TypeWithSize<8> {
 public:
#if GTEST_OS_WINDOWS
  typedef __int64 Int;
  typedef unsigned __int64 UInt;
#else
  typedef long long Int;  // NOLINT
  typedef unsigned long long UInt;  // NOLINT
#endif  // GTEST_OS_WINDOWS
};


// This template class represents an IEEE floating-point number
// (either single-precision or double-precision, depending on the
// template parameters).
//
// The purpose of this class is to do more sophisticated number
// comparison.  (Due to round-off error, etc, it's very unlikely that
// two floating-points will be equal exactly.  Hence a naive
// comparison by the == operation often doesn't work.)
//
// Format of IEEE floating-point:
//
//   The most-significant bit being the leftmost, an IEEE
//   floating-point looks like
//
//     sign_bit exponent_bits fraction_bits
//
//   Here, sign_bit is a single bit that designates the sign of the
//   number.
//
//   For float, there are 8 exponent bits and 23 fraction bits.
//
//   For double, there are 11 exponent bits and 52 fraction bits.
//
//   More details can be found at
//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
//
// Template parameter:
//
//   RawType: the raw floating-point type (either float or double)
template <typename RawType>
class FloatingPoint {
 public:
  // Defines the unsigned integer type that has the same size as the
  // floating point number.
  typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;

  // Constants.

  // # of bits in a number.
  static const size_t kBitCount = 8*sizeof(RawType);

  // # of fraction bits in a number.
  static const size_t kFractionBitCount =
    std::numeric_limits<RawType>::digits - 1;

  // # of exponent bits in a number.
  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;

  // The mask for the sign bit.
  static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);

  // The mask for the fraction bits.
  static const Bits kFractionBitMask =
    ~static_cast<Bits>(0) >> (kExponentBitCount + 1);

  // The mask for the exponent bits.
  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);

  // How many ULP's (Units in the Last Place) we want to tolerate when
  // comparing two numbers.  The larger the value, the more error we
  // allow.  A 0 value means that two numbers must be exactly the same
  // to be considered equal.
  //
  // The maximum error of a single floating-point operation is 0.5
  // units in the last place.  On Intel CPU's, all floating-point
  // calculations are done with 80-bit precision, while double has 64
  // bits.  Therefore, 4 should be enough for ordinary use.
  //
  // See the following article for more details on ULP:
  // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
  static const size_t kMaxUlps = 4;

  // Constructs a FloatingPoint from a raw floating-point number.
  //
  // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  // around may change its bits, although the new value is guaranteed
  // to be also a NAN.  Therefore, don't expect this constructor to
  // preserve the bits in x when x is a NAN.
  explicit FloatingPoint(const RawType& x) { u_.value_ = x; }

  // Static methods

  // Reinterprets a bit pattern as a floating-point number.
  //
  // This function is needed to test the AlmostEquals() method.
  static RawType ReinterpretBits(const Bits bits) {
    FloatingPoint fp(0);
    fp.u_.bits_ = bits;
    return fp.u_.value_;
  }

  // Returns the floating-point number that represent positive infinity.
  static RawType Infinity() {
    return ReinterpretBits(kExponentBitMask);
  }

  // Non-static methods

  // Returns the bits that represents this number.
  const Bits &bits() const { return u_.bits_; }

  // Returns the exponent bits of this number.
  Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }

  // Returns the fraction bits of this number.
  Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }

  // Returns the sign bit of this number.
  Bits sign_bit() const { return kSignBitMask & u_.bits_; }

  // Returns true iff this is NAN (not a number).
  bool is_nan() const {
    // It's a NAN if the exponent bits are all ones and the fraction
    // bits are not entirely zeros.
    return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  }

  // Returns true iff this number is at most kMaxUlps ULP's away from
  // rhs.  In particular, this function:
  //
  //   - returns false if either number is (or both are) NAN.
  //   - treats really large numbers as almost equal to infinity.
  //   - thinks +0.0 and -0.0 are 0 DLP's apart.
  bool AlmostEquals(const FloatingPoint& rhs) const {
    // The IEEE standard says that any comparison operation involving
    // a NAN must return false.
    if (is_nan() || rhs.is_nan()) return false;

    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
        <= kMaxUlps;
  }

 private:
  // The data type used to store the actual floating-point number.
  union FloatingPointUnion {
    RawType value_;  // The raw floating-point number.
    Bits bits_;      // The bits that represent the number.
  };

  // Converts an integer from the sign-and-magnitude representation to
  // the biased representation.  More precisely, let N be 2 to the
  // power of (kBitCount - 1), an integer x is represented by the
  // unsigned number x + N.
  //
  // For instance,
  //
  //   -N + 1 (the most negative number representable using
  //          sign-and-magnitude) is represented by 1;
  //   0      is represented by N; and
  //   N - 1  (the biggest number representable using
  //          sign-and-magnitude) is represented by 2N - 1.
  //
  // Read http://en.wikipedia.org/wiki/Signed_number_representations
  // for more details on signed number representations.
  static Bits SignAndMagnitudeToBiased(const Bits &sam) {
    if (kSignBitMask & sam) {
      // sam represents a negative number.
      return ~sam + 1;
    } else {
      // sam represents a positive number.
      return kSignBitMask | sam;
    }
  }

  // Given two numbers in the sign-and-magnitude representation,
  // returns the distance between them as an unsigned number.
  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
                                                     const Bits &sam2) {
    const Bits biased1 = SignAndMagnitudeToBiased(sam1);
    const Bits biased2 = SignAndMagnitudeToBiased(sam2);
    return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  }

  FloatingPointUnion u_;
};

EDIT: This post is 4 years old. It's probably still valid, and the code is nice, but some people found improvements. Best go get the latest version of AlmostEquals right from the Google Test source code, and not the one I pasted up here.

EXTRACT() Hour in 24 Hour format

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

Format timedelta to string

from django.utils.translation import ngettext

def localize_timedelta(delta):
    ret = []
    num_years = int(delta.days / 365)
    if num_years > 0:
        delta -= timedelta(days=num_years * 365)
        ret.append(ngettext('%d year', '%d years', num_years) % num_years)

    if delta.days > 0:
        ret.append(ngettext('%d day', '%d days', delta.days) % delta.days)

    num_hours = int(delta.seconds / 3600)
    if num_hours > 0:
        delta -= timedelta(hours=num_hours)
        ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours)

    num_minutes = int(delta.seconds / 60)
    if num_minutes > 0:
        ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes)

    return ' '.join(ret)

This will produce:

>>> from datetime import timedelta
>>> localize_timedelta(timedelta(days=3660, minutes=500))
'10 years 10 days 8 hours 20 minutes'

Replace string within file contents

Something like

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

Select all 'tr' except the first one

Sorry I know this is old but why not style all tr elements the way you want all except the first and the use the psuedo class :first-child where you revoke what you specified for all tr elements.

Better descriped by this example:

http://jsfiddle.net/DWTr7/1/

tr {
    border-top: 1px solid;
}
tr:first-child {
    border-top: none;   
}

/Patrik

React Router Pass Param to Component

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

Using .htaccess to make all .html pages to run as .php files?

You need to add the following line into your Apache config file:

AddType application/x-httpd-php .htm .html

You also need two other things:

  1. Allow Overridding

    In your_site.conf file (e.g. under /etc/apache2/mods-available in my case), add the following lines:

    <Directory "<path_to_your_html_dir(in my case: /var/www/html)>">
        AllowOverride All
    </Directory>
    
  2. Enable Rewrite Mod

    Run this command on your machine:

    sudo a2enmod rewrite 
    

    After any of those steps, you should restart apache:

    sudo service apache2 restart
    

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

The issue is because your data source is not setup properly, to do that please verify your data source connection, in order to do that first navigate to Report Service Configuration Manager through

clicking on the start -> Start All -> Microsoft SQL Server ->Configuration Tool -> “Report Service Configuration Manager”

The open Report Manager URL and then navigate to the Data Source folder, see in the picture below

Then Create a Data Source or configure the one that is already there by right click on your database source and select "Manage" as is shown below

Now on the properties tab, on your left menu, fill out the data source with your connection string and username and password, after that click on test connection, and if the connection was successful, then click "Apply"

Navigate to the folder that contains your report in this case "SurveyLevelReport"

And Finally set your Report to the Data Source that you set up previously, and click Apply

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

This error occur when you try to load a component dynamically and:

  1. The component you want to load is not routing module
  2. The component is no in module entryComponents.

in routingModule

const routes: Routes = [{ path: 'confirm-component', component: ConfirmComponent,data: {}}]

or in module

entryComponents: [
ConfirmComponent
} 

To fix this error you can add a router to the component or add it to entryComponents of module.

  1. Add a router to component.drawback of this approach is your component will be accessible with that url.
  2. Add it to entryComponents. in this case your component will not have any url attached to and it will not be accessible with url.

Order by multiple columns with Doctrine

The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:

   # Inside a Repository method:
   $myResults = $this->createQueryBuilder('a')
       ->addOrderBy('a.column1', 'ASC')
       ->addOrderBy('a.column2', 'ASC')
       ->addOrderBy('a.column3', 'DESC')
   ;

   # Or, using a OrderBy object:
   $orderBy = new OrderBy('a.column1', 'ASC');
   $orderBy->add('a.column2', 'ASC');
   $orderBy->add('a.column3', 'DESC');

   $myResults = $this->createQueryBuilder('a')
       ->orderBy($orderBy)
   ;

Why is setState in reactjs Async instead of Sync?

setState is asynchronous. You can see in this documentation by Reactjs

React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.

However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.

The reason is this would break the consistency between props and state, causing issues that are very hard to debug.

You can still perform functions if it is dependent on the change of the state value:

Option 1: Using callback function with setState

this.setState({
   value: newValue
},()=>{
   // It is an callback function.
   // Here you can access the update value
   console.log(this.state.value)
})

Option 2: using componentDidUpdate This function will be called whenever the state of that particular class changes.

componentDidUpdate(prevProps, prevState){
    //Here you can check if value of your desired variable is same or not.
    if(this.state.value !== prevState.value){
        // this part will execute if your desired variable updates
    }
}

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

MongoDB - admin user not authorized

It's a simple question.

  1. It's important that you must switch the target db NOT admin.

use yourDB

  1. check your db authentication by

show users

  1. If you get a {} empty object that is the question. You just need to type

db.createUser( { user: "yourUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] } )

or

db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])

Get JSF managed bean by name in any Servlet related class

Have you tried an approach like on this link? I'm not sure if createValueBinding() is still available but code like this should be accessible from a plain old Servlet. This does require to bean to already exist.

http://www.coderanch.com/t/211706/JSF/java/access-managed-bean-JSF-from

 FacesContext context = FacesContext.getCurrentInstance();  
 Application app = context.getApplication();
 // May be deprecated
 ValueBinding binding = app.createValueBinding("#{" + expr + "}"); 
 Object value = binding.getValue(context);

How do you get the process ID of a program in Unix or Linux using Python?

Try pgrep. Its output format is much simpler and therefore easier to parse.

How to copy sheets to another workbook using vba?

You could saveAs xlsx. Then you will loose the macros and generate a new workbook with a little less work.

ThisWorkbook.saveas Filename:=NewFileNameWithPath, Format:=xlOpenXMLWorkbook

HttpContext.Current.Session is null when routing requests

The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

I've used this function to solve:

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

What is the official "preferred" way to install pip and virtualenv systemwide?

I use get-pip and virtualenv-burrito to install all this. Not sure if python-setuptools is required.

# might be optional. I install as part of my standard ubuntu setup script
sudo apt-get -y install python-setuptools

# install pip (using get-pip.py from pip contrib)
curl -O https://raw.github.com/pypa/pip/develop/contrib/get-pip.py && sudo python get-pip.py

# one-line virtualenv and virtualenvwrapper using virtualenv-burrito
curl -s https://raw.github.com/brainsik/virtualenv-burrito/master/virtualenv-burrito.sh | bash

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

Facebook how to check if user has liked page and show content?

There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.

Change is fairly simple:-

sessions has to be replaced by authResponse and uid by userID

Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.

Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634

Here is the code posted above with changes which worked for me.

$(document).ready(function(){
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; //coca cola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
            var the_query = FB.Data.query(fql_query);

            the_query.wait(function(rows) {

                if (rows.length == 1 && rows[0].uid == user_id) {
                    $("#container_like").show();

                    //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

                } else {
                    $("#container_notlike").show();
                    //and here you could get the content for a non liker in ajax...
                }
            });
        } else {
            // user is not logged in
        }
    });

});

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Accurate way to measure execution times of php scripts

You can use REQUEST_TIME from the $_SERVER superglobal array. From the documentation:

REQUEST_TIME
The timestamp of the start of the request. (Available since PHP 5.1.0.)

REQUEST_TIME_FLOAT
The timestamp of the start of the request, with microsecond precision. (Available since PHP 5.4.0.)

This way you don't need to save a timestamp at the beginning of your script. You can simply do:

<?php
// Do stuff
usleep(mt_rand(100, 10000));

// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did stuff in $time seconds\n";
?>

Here, $time would contain the time elapsed since the start of the script in seconds, with microseconds precision (eg. 1.341 for 1 second and 341 microseconds)


More info:

PHP documentation: $_SERVER variables and microtime function

Difference between "process.stdout.write" and "console.log" in node.js?

Looking at the Node docs apparently console.log is just process.stdout.write with a line-break at the end:

console.log = function (d) {
  process.stdout.write(d + '\n');
};

Source: http://nodejs.org/docs/v0.3.1/api/process.html#process.stdout

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

send checkbox value in PHP form

Here's how it should look like in order to return a simple Yes when it's checked.

<input type="checkbox" id="newsletter" name="newsletter" value="Yes" checked>
<label for="newsletter">i want to sign up for newsletter</label>

I also added the text as a label, it means you can click the text as well to check the box. Small but, personally I hate when sites make me aim my mouse at this tiny little check box.

When the form is submitted if the check box is checked $_POST['newsletter'] will equal Yes. Just how you are checking to see if $_POST['name'],$_POST['email'], and $_POST['tel'] are empty you could do the same.

Here is an example of how you would add this into your email on the php side:

Underneath your existing code:

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];

Add:

$newsletter = $_POST['newsletter'];
if ($newsletter != 'Yes') {
    $newsletter = 'No';
}

If the check box is checked it will add Yes in your email if it was not checked it will add No.

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .

Are you sure this code

$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");

is in the 'scripts' folder and your main code file is on the same level as the script folder?

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

Determine if Python is running inside virtualenv

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.

Check if textbox has empty value

$('input:text').filter(function() { return this.value.length > 0; });

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

A good rule of thumb is "open DLLs, closed EXEs", that is:

  • EXE targets the OS, by specifying x86 or x64.
  • DLLs are left open (i.e., AnyCPU) so they can be instantiated within a 32-bit or a 64-bit process.

When you build an EXE as AnyCPU, all you're doing is deferring the decision on what process bitness to use to the OS, which will JIT the EXE to its liking. That is, an x64 OS will create a 64-bit process, an x86 OS will create an 32-bit process.

Building DLLs as AnyCPU makes them compatible to either process.

For more on the subtleties of assembly loading, see here. The executive summary reads something like:

  • AnyCPU – loads as x64 or x86 assembly, depending on the invoking process
  • x86 – loads as x86 assembly; will not load from an x64 process
  • x64 – loads as x64 assembly; will not load from an x86 process

How do JavaScript closures work?

MDN explains it best I think:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

A closure always has an outer function and an inner function. The inner function is where all the work happens, and the outer function is just the environment that preserves the scope where the inner function was created. In this way, the inner function of a closure 'remembers' the environment/scope in which it was created. The most classic example is a counter function:

var closure = function() {
  var count = 0;
  return function() {
    count++;
    console.log(count);
  };
};

var counter = closure();

counter() // returns 1
counter() // returns 2
counter() // returns 3

In the above code, count is preserved by the outer function (environment function), so that every time you call counter(), the inner function (work function) can increment it.

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

How to get scrollbar position with Javascript?

document.getScroll = function() {
    if (window.pageYOffset != undefined) {
        return [pageXOffset, pageYOffset];
    } else {
        var sx, sy, d = document,
            r = d.documentElement,
            b = d.body;
        sx = r.scrollLeft || b.scrollLeft || 0;
        sy = r.scrollTop || b.scrollTop || 0;
        return [sx, sy];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

How to change default text color using custom theme?

In your Manifest you need to reference the name of the style that has the text color item inside it. Right now you are just referencing an empty style. So in your theme.xml do only this style:

<style name="Theme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
</style>

And keep you reference to in the Manifest the same (android:theme="@style/Theme")

EDIT:

theme.xml:

<style name="MyTheme" parent="@android:style/TextAppearance">
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12dp</item>
</style>

Manifest:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/MyTheme">

Notice I combine the text color and size into the same style. Also, I changed the name of the theme to MyTheme and am now referencing that in the Manifest. And I changed to @android:style/TextAppearance for the parent value.

List<String> to ArrayList<String> conversion issue

Arrays.asList does not return instance of java.util.ArrayListbut it returns instance of java.util.Arrays.ArrayList.

You will need to convert to ArrayList if you want to access ArrayList specific information

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Oracle "Partition By" Keyword

the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id

select client_id, operation_date,
       row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;

this query will return the number of operations done by the client_id

How to Populate a DataTable from a Stored Procedure

Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:

using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();

            da.Fill(dt);
        }
    }
}

Time complexity of accessing a Python dict

You are not correct. dict access is unlikely to be your problem here. It is almost certainly O(1), unless you have some very weird inputs or a very bad hashing function. Paste some sample code from your application for a better diagnosis.

redistributable offline .NET Framework 3.5 installer for Windows 8

Try this command:

Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess

I: partition of your Windows DVD.

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

jQuery move to anchor location on page load

Did you tried JQuery's scrollTo method? http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

$("#header").scrollToMe();

SQL Count for each date

When you cast a DateTime to an int it "truncates" at noon, you might want to strip the day out like so

cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Change Your Web.Config file as below

 <system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV"/>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How can I run multiple curl requests processed sequentially?

Another crucial method not mentioned here is using the same TCP connection for multiple HTTP requests, and exactly one curl command for this.

This is very useful to save network bandwidth, client and server resources, and overall the need of using multiple curl commands, as curl by default closes the connection when end of command is reached.

Keeping the connection open and reusing it is very common for standard clients running a web-app.

Starting curl version 7.36.0, the --next or -: command-line option allows to chain multiple requests, and usable both in command-line and scripting.

For example:

  • Sending multiple requests on the same TCP connection:

curl http://example.com/?update_=1 -: http://example.com/foo

  • Sending multiple different HTTP requests on the same connection:

curl http://example.com/?update_=1 -: -d "I am posting this string" http://example.com/?update_=2

  • Sending multiple HTTP requests with different curl options for each request:

curl -o 'my_output_file' http://example.com/?update_=1 -: -d "my_data" -s -m 10 http://example.com/foo -: -o /dev/null http://example.com/random

From the curl manpage:

-:, --next

Tells curl to use a separate operation for the following URL and associated options. This allows you to send several URL requests, each with their own specific options, for example, such as different user names or custom requests for each.

-:, --next will reset all local options and only global ones will have their values survive over to the operation following the -:, --next instruction. Global options include -v, --verbose, --trace, --trace-ascii and --fail-early.

For example, you can do both a GET and a POST in a single command line:

curl www1.example.com --next -d postthis www2.example.com

Added in 7.36.0.

Combine two (or more) PDF's

I've done this with PDFBox. I suppose it works similarly to iTextSharp.

'Syntax Error: invalid syntax' for no apparent reason

For problems where it seems to be an error on a line you think is correct, you can often remove/comment the line where the error appears to be and, if the error moves to the next line, there are two possibilities.

Either both lines have a problem or the previous line has a problem which is being carried forward. The most likely case is the second option (even more so if you remove another line and it moves again).

For example, the following Python program twisty_passages.py:

xyzzy = (1 +
plugh = 7

generates the error:

  File "twisty_passages.py", line 2
    plugh = 7
          ^
SyntaxError: invalid syntax

despite the problem clearly being on line 1.


In your particular case, that is the problem. The parentheses in the line before your error line is unmatched, as per the following snippet:

# open parentheses: 1  2             3
#                   v  v             v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
#                               ^             ^
# close parentheses:            1             2

Depending on what you're trying to achieve, the solution may be as simple as just adding another closing parenthesis at the end, to close off the sqrt function.

I can't say for certain since I don't recognise the expression off the top of my head. Hardly surprising if (assuming PSAT is the enzyme, and the use of the typeMolecule identifier) it's to do with molecular biology - I seem to recall failing Biology consistently in my youth :-)

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

Simplest Way to Test ODBC on WIndows

One way to create a quick test query in Windows via an ODBC connection is using the DQY format.

To achieve this, create a DQY file (e.g. test.dqy) containing the magic first two lines (XLODBC and 1) as below, followed by your ODBC connection string on the third line and your query on the fourth line (all on one line), e.g.:

XLODBC
1
Driver={Microsoft ODBC for Oracle};server=DB;uid=scott;pwd=tiger;
SELECT COUNT(1) n FROM emp

Then, if you open the file by double-clicking it, it will open in Excel and populate the worksheet with the results of the query.

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

flutter run: No connected devices

I encounter the same problem as you did. It turns out that your device is not connected with your computer.

Note:

  • If you are using XCode, if both your computer and the device are using the same WIFI, you don't have to connect the device with the computer.
  • For Android, or iOS running under terminal command, if you are using command line to run this, you have to make sure they are connected via cables. Sharing the same WIFI does not work. Make sure your device is really connected.
  • Make sure you allowed USB Debugging on your android device.

If this still does not work, try to fire below command, where you can get richer info and details:

flutter run --verbose

Detecting installed programs via registry

You could use MSI API to enumerate everything installed by Windows Installer but that won't list all the software available on a machine. Without knowing more about what you need I think the concept of "installed" is a little vague. There are many ways to deploy software to a system ranging from big complicated installers to ZIP files and everything in between.

JavaScript regex for alphanumeric string with length of 3-5 chars

First this script test the strings N having chars from 3 to 5.

For multi language (arabic, Ukrainian) you Must use this

var regex = /^([a-zA-Z0-9_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]+){3,5}$/;  regex.test('?????');

Other wise the below is for English Alphannumeric only

/^([a-zA-Z0-9_-]){3,5}$/

P.S the above dose not accept special characters

one final thing the above dose not take space as test it will fail if there is space if you want space then add after the 0-9\s

\s

And if you want to check lenght of all string add dot .

var regex = /^([a-zA-Z0-9\s@,!=%$#&_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]).{1,30}$/;

How to convert a const char * to std::string

There is a constructor accepting two pointer parameters, so the code is simply

 std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));

this is also going to be as efficient as std::string cppstr(cstr) if the length is smaller than max_length.

How to convert a multipart file to File?

Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());

Where multipartFile is your org.springframework.web.multipart.MultipartFile.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:

If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="@this" to your command components.

As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both @form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="@this" and render="@none" respectively.

Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)

Dependency injection with Jersey 2.0

If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:

guice-bridge-jit-injector

Running MSBuild fails to read SDKToolsPath

I agree with IanS's answer. No need to install new SDK. Just make sure the registry key values SDK35ToolsPath and SDK40ToolPath for MSBuild are pointing to correct registry key values.

In my case my project was targeted for .NET 3.5 and I had to set SDK35ToolsPath for key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0 to $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v6.0A\WinSDKNetFxTools@InstallationFolder). And everything worked.

Update int column in table with unique incrementing values

DECLARE @IncrementValue int
SET @IncrementValue = 0 
UPDATE Samples SET qty = @IncrementValue,@IncrementValue=@IncrementValue+1

JS search in object values

I needed to perform a search on a large object and return the addresses of the matches, not just the matched values themselves.

This function searches an object for a string (or alternatively, uses a callback function to perform custom logic) and keeps track of where the value was found within the object. It also avoids circular references.

_x000D_
_x000D_
//Search function_x000D_
var locateInObject = function(obj, key, find, result, currentLocation){_x000D_
  if(obj === null) return;_x000D_
  result = result||{done:[],found:{}};_x000D_
  if(typeof obj == 'object'){_x000D_
    result.done.push(obj);_x000D_
  }_x000D_
  currentLocation = currentLocation||key;_x000D_
  var keys = Object.keys(obj);_x000D_
  for(var k=0; k<keys.length; ++k){_x000D_
    var done = false;_x000D_
    for(var d=0; d<result.done.length; ++d){_x000D_
      if(result.done[d] === obj[keys[k]]){_x000D_
        done = true;_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
    if(!done){_x000D_
      var location = currentLocation+'.'+keys[k];_x000D_
      if(typeof obj[keys[k]] == 'object'){_x000D_
        locateInObject(obj[keys[k]], keys[k], find, result, location)_x000D_
      }else if((typeof find == 'string' && obj[keys[k]].toString().indexOf(find) > -1) || (typeof find == 'function' && find(obj[keys[k]], keys[k]))){_x000D_
        result.found[location] = obj[keys[k]];_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return result.found;_x000D_
}_x000D_
_x000D_
//Test data_x000D_
var test = {_x000D_
  key1: {_x000D_
    keyA: 123,_x000D_
    keyB: "string"_x000D_
  },_x000D_
  key2: {_x000D_
    keyC: [_x000D_
      {_x000D_
        keyI: "string123",_x000D_
        keyII: 2.3_x000D_
      },_x000D_
      "string"_x000D_
    ],_x000D_
    keyD: null_x000D_
  },_x000D_
  key3: [_x000D_
    1,_x000D_
    2,_x000D_
    123,_x000D_
    "testString"_x000D_
  ],_x000D_
  key4: "123string"_x000D_
}_x000D_
//Add a circular reference_x000D_
test.key5 = test;_x000D_
_x000D_
//Tests_x000D_
console.log(locateInObject(test, 'test', 'string'))_x000D_
console.log(locateInObject(test, 'test', '123'))_x000D_
console.log(locateInObject(test, 'test', function(val, key){ return key.match(/key\d/) && val.indexOf('string') > -1}))
_x000D_
_x000D_
_x000D_

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

Eclipse: All my projects disappeared from Project Explorer

I also had the same problem.

file>restart. Projects and modules appeared after restarting the eclipse, but faced new error; An internal error occurred during: "AppXray Indexing...". java.lang.NullPointerException.

So it's good to be on safe side, import the project again in a new workspace.

Beginner Python Practice?

The Python Challenge will not only let you exercise the Python you do know, it will also require you to learn about various popular third-party packages in order to solve some of the challenges.

Append values to a set in Python

For me, in Python 3, it's working simply in this way:

keep = keep.union((0,1,2,3,4,5,6,7,8,9,10))

I don't know if it may be correct...

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

Python - converting a string of numbers into a list of int

I guess the dirtiest solution is this:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))

Event when window.location.href changes

I use this script in my extension "Grab Any Media" and work fine ( like youtube case )

var oldHref = document.location.href;

window.onload = function() {

    var
         bodyList = document.querySelector("body")

        ,observer = new MutationObserver(function(mutations) {

            mutations.forEach(function(mutation) {

                if (oldHref != document.location.href) {

                    oldHref = document.location.href;

                    /* Changed ! your code here */

                }

            });

        });

    var config = {
        childList: true,
        subtree: true
    };

    observer.observe(bodyList, config);

};

How do I verify that a string only contains letters, numbers, underscores and dashes?

use a regex and see if it matches!

([a-z][A-Z][0-9]\_\-)*

How can I select the row with the highest ID in MySQL?

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery

SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

How to set a JVM TimeZone Properly

Two options that I don’t think were covered in the other answers:

Avoid the need

Whatever you do to set the JVM default time zone, it is very hard to make sure that no one else sets it differently. It can be set at any time without notice from another part of your program or from another program running in the same JVM. So in your time operations be explicit about which time zone you want, and you will always know what you get independently of the JVM setting. Example:

    System.out.println(ZonedDateTime.now(ZoneId.of("Asia/Dushanbe")));

Example output:

2018-10-11T14:59:16.742020+05:00[Asia/Dushanbe]

System.setProperty

For many purposes the following will not be the preferred way, and it can certainly be misused. For “throw away” programs I sometimes find it practical. You can also set a system property from within Java:

    System.setProperty("user.timezone", "Australia/Tasmania");
    System.out.println(ZonedDateTime.now());

This just printed:

2018-10-11T21:03:12.218959+11:00[Australia/Tasmania]

If you want validation of the string you are passing, use:

        System.setProperty("user.timezone", ZoneId.of("Australia/Tasmania").getId());

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

I found the InvokeRequired not reliable, so I simply use

if (!this.IsHandleCreated)
{
    this.CreateHandle();
}

Hide password with "•••••••" in a textField

You can achieve this directly in Xcode:

enter image description here

The very last checkbox, make sure secure is checked .

Or you can do it using code:

Identifies whether the text object should hide the text being entered.

Declaration

optional var secureTextEntry: Bool { get set }

Discussion

This property is set to false by default. Setting this property to true creates a password-style text object, which hides the text being entered.

example:

texfield.secureTextEntry = true

Viewing unpushed Git commits

Here's my portable solution (shell script which works on Windows too without additional install) which shows the differences from origin for all branches: git-fetch-log

An example output:

==== branch [behind 1]

> commit 652b883 (origin/branch)
| Author: BimbaLaszlo <[email protected]>
| Date:   2016-03-10 09:11:11 +0100
|
|     Commit on remote
|
o commit 2304667 (branch)
  Author: BimbaLaszlo <[email protected]>
  Date:   2015-08-28 13:21:13 +0200

      Commit on local

==== master [ahead 1]

< commit 280ccf8 (master)
| Author: BimbaLaszlo <[email protected]>
| Date:   2016-03-25 21:42:55 +0100
|
|     Commit on local
|
o commit 2369465 (origin/master, origin/HEAD)
  Author: BimbaLaszlo <[email protected]>
  Date:   2016-03-10 09:02:52 +0100

      Commit on remote

==== test [ahead 1, behind 1]

< commit 83a3161 (test)
| Author: BimbaLaszlo <[email protected]>
| Date:   2016-03-25 22:50:00 +0100
|
|     Diverged from remote
|
| > commit 4aafec7 (origin/test)
|/  Author: BimbaLaszlo <[email protected]>
|   Date:   2016-03-14 10:34:28 +0100
|
|       Pushed remote
|
o commit 0fccef3
  Author: BimbaLaszlo <[email protected]>
  Date:   2015-09-03 10:33:39 +0200

      Last common commit

Parameters passed for log, e.g. --oneline or --patch can be used.

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

Countdown timer using Moment js

You're not using react native or react so forgive me this isn't a solution for you. - since this is a 7 year old post I'm pretty sure you figured it out by now ;)

But I was looking for something similar for react-native and it led me to this SO question. Incase anyone else winds up down the same road I thought I'd share my use-moment-countdown hook for react or react native: https://github.com/BrooklinJazz/use-moment-countdown.

For example you can make a 10 minute timer like so:

import React from 'react'

import  { useCountdown } from 'use-moment-countdown'

const App = () => {
  const {start, time} = useCountdown({m: 10})
  return (
    <div onClick={start}>
      {time.format("hh:mm:ss")}
    </div>
  )
}

export default App

Changing route doesn't scroll to top in the new page

All of the answers above break expected browser behavior. What most people want is something that will scroll to the top if it's a "new" page, but return to the previous position if you're getting there through the Back (or Forward) button.

If you assume HTML5 mode, this turns out to be easy (although I'm sure some bright folks out there can figure out how to make this more elegant!):

// Called when browser back/forward used
window.onpopstate = function() { 
    $timeout.cancel(doc_scrolling); 
};

// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
    doc_scrolling = $timeout( scroll_top, 50 );

// Moves entire browser window to top
scroll_top = function() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}

The way it works is that the router assumes it is going to scroll to the top, but delays a bit to give the browser a chance to finish up. If the browser then notifies us that the change was due to a Back/Forward navigation, it cancels the timeout, and the scroll never occurs.

I used raw document commands to scroll because I want to move to the entire top of the window. If you just want your ui-view to scroll, then set autoscroll="my_var" where you control my_var using the techniques above. But I think most people will want to scroll the entire page if you are going to the page as "new".

The above uses ui-router, though you could use ng-route instead by swapping $routeChangeSuccess for$stateChangeSuccess.

Delete all items from a c++ std::vector

Adding to the above mentioned benefits of swap(). That clear() does not guarantee deallocation of memory. You can use swap() as follows:

std::vector<T>().swap(myvector);

Writing Python lists to columns in csv

I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(("list1", "list2"))
    rcount = 0
    for row in list1:
        wr.writerow((list1[rcount], list2[rcount]))
        rcount = rcount + 1
    myfile.close()

What characters are forbidden in Windows and Linux directory names?

In Unix shells, you can quote almost every character in single quotes '. Except the single quote itself, and you can't express control characters, because \ is not expanded. Accessing the single quote itself from within a quoted string is possible, because you can concatenate strings with single and double quotes, like 'I'"'"'m' which can be used to access a file called "I'm" (double quote also possible here).

So you should avoid all control characters, because they are too difficult to enter in the shell. The rest still is funny, especially files starting with a dash, because most commands read those as options unless you have two dashes -- before, or you specify them with ./, which also hides the starting -.

If you want to be nice, don't use any of the characters the shell and typical commands use as syntactical elements, sometimes position dependent, so e.g. you can still use -, but not as first character; same with ., you can use it as first character only when you mean it ("hidden file"). When you are mean, your file names are VT100 escape sequences ;-), so that an ls garbles the output.

How can I align text directly beneath an image?

Your HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

How to send POST request in JSON using HTTPClient in Android?

Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.

Http http = HttpFactory.create(context);
http.get("http://example.com/users")
    .handler(new ResponseHandler<User[]>() {
        @Override
        public void success(User[] users, HttpResponse response) {
        }
    }).execute();

.htaccess redirect http to https

This is the best for www and for HTTPS, for proxy and no proxy users.

RewriteEngine On

### WWW & HTTPS

# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### WWW & HTTPS

htaccess redirect to https://www

There are a lot of solutions out there. Here is a link to the apache wiki which deals with this issue directly.

http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

How to restrict user to type 10 digit numbers in input element?

HTML

<input type="text" id="youridher" size="10">

Use JQuery,

SIZE = 10
$(document).ready(function() {
      $("#youridher").bind('keyup', function() { 
            if($("#youridher").val().length <= SIZE && PHONE_REGEX) {
                return true;
            }
            else {
                return false;
            }  
      });
});

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

PERMISSIONS: I want to stress the importance of permissions for "sqlplus".

  1. For any "Other" UNIX user other than the Owner/Group to be able to run sqlplus and access an ORACLE database , read/execute permissions are required (rx) for these 4 directories :

    $ORACLE_HOME/bin , $ORACLE_HOME/lib, $ORACLE_HOME/oracore, $ORACLE_HOME/sqlplus

  2. Environment. Set those properly:

    A. ORACLE_HOME (example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/)

    B. LD_LIBRARY_PATH (example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/lib)

    C. ORACLE_SID

    D. PATH

     export PATH="$ORACLE_HOME/bin:$PATH"
    

Maven skip tests

I had some inter-dependency with the tests in order to build the package.

The following command manage to override the need for the test artifact in order to complete the goal:

mvn -DskipTests=true  package

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I had this problem as well.

I got it working with this:

.ui-dialog{
    display:inline-block;
}

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Selenium C# WebDriver: Wait until element is present

You can find out something like this in C#.

This is what I used in JUnit - Selenium

WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

Do import related packages.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.

Refresh Fragment at reload

// Reload current fragment
Fragment frag = new Order();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_home, frag).commit();

pandas dataframe columns scaling with sklearn

As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el)) method will produce the following warning:

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.

Converting your columns to numpy arrays should do the job (I prefer StandardScaler):

from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())

-- Edit Nov 2018 (Tested for pandas 0.23.4)--

As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix() returns FutureWarning. Therefore, it should be replaced by .values:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit_transform(dfTest[['A','B']].values)

-- Edit May 2019 (Tested for pandas 0.24.2)--

As joelostblom mentions in the comments, "Since 0.24.0, it is recommended to use .to_numpy() instead of .values."

Updated example:

import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
               'A':[14.00,90.20,90.95,96.27,91.21],
               'B':[103.02,107.26,110.35,114.23,114.68],
               'C':['big','small','big','small','small']
             })
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
      A         B      C
0 -1.995290 -1.571117    big
1  0.436356 -0.603995  small
2  0.460289  0.100818    big
3  0.630058  0.985826  small
4  0.468586  1.088469  small

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

How can I hide an HTML table row <tr> so that it takes up no space?

Can you include some code? I add style="display:none;" to my table rows all the time and it effectively hides the entire row.

Send json post using php

You can use CURL for this purpose see the example code:

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Years after everyone's answer, I too want to present how I did it for my project

    /// <summary>
    /// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="headers">If set to true the first row will be considered as headers</param>
    /// <returns></returns>
    public DataSet Import(string filename, bool headers = true)
    {
        var _xl = new Excel.Application();
        var wb = _xl.Workbooks.Open(filename);
        var sheets = wb.Sheets;
        DataSet dataSet = null;
        if (sheets != null && sheets.Count != 0)
        {
            dataSet = new DataSet();
            foreach (var item in sheets)
            {
                var sheet = (Excel.Worksheet)item;
                DataTable dt = null;
                if (sheet != null)
                {
                    dt = new DataTable();
                    var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                    var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[1, j + 1];
                        var column = new DataColumn(headers ? cell.Value : string.Empty);
                        dt.Columns.Add(column);
                    }

                    for (int i = 0; i < rowCount; i++)
                    {
                        var r = dt.NewRow();
                        for (int j = 0; j < ColumnCount; j++)
                        {
                            var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                            r[j] = cell.Value;
                        }
                        dt.Rows.Add(r);
                    }

                }
                dataSet.Tables.Add(dt);
            }
        }
        _xl.Quit();
        return dataSet;
    }

What does int argc, char *argv[] mean?

The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.

How to return 2 values from a Java method?

Here is the really simple and short solution with SimpleEntry:

AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);

String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();

Only uses Java built in functions and it comes with the type safty benefit.

Change / Add syntax highlighting for a language in Sublime 2/3

Use the PackageResourceViewer plugin installed via Package Control (as mentioned by MattDMo). This allows you to override the compressed resources by simply opening it in Sublime Text and saving the file. It automatically saves only the edited resources to %APPDATA%/Roaming/Sublime Text 3/Packages/ or ~/.config/sublime-text-3/Packages/.

Specific to the op, once the plugin is installed, execute the PackageResourceViewer: Open Resource command. Then select JavaScript followed by JavaScript.tmLanguage. This will open an xml file in the editor. You can edit any of the language definitions and save the file. This will write an override copy of the JavaScript.tmLanguage file in the user directory.

The same method can be used to edit the language definition of any language in the system.

Add a linebreak in an HTML text area

If it's not vb you can use &#013;&#010; (ascii codes for cr,lf)

How to embed an autoplaying YouTube video in an iframe?

To use javascript api,

<script type="text/javascript" src="swfobject.js"></script>
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>

  <script type="text/javascript">

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/OyHoZhLdgYw?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

  </script>

To play the youtube with the id:

swfobject.embedSWF

reference: https://developers.google.com/youtube/js_api_referencemagazine

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Java: export to an .jar file in eclipse

Go to file->export->JAR file, there you may select "Export generated class files and sources" and make sure that your project is selected, and all folder under there are also! Good luck!

JavaScript seconds to time string with format hh:mm:ss

secToHHMM(number: number) {
    debugger;
    let hours = Math.floor(number / 3600);
    let minutes = Math.floor((number - (hours * 3600)) / 60);
    let seconds = number - (hours * 3600) - (minutes * 60);
    let H, M, S;
    if (hours < 10) H = ("0" + hours);
    if (minutes < 10) M = ("0" + minutes);
    if (seconds < 10) S = ("0" + seconds);
    return (H || hours) + ':' + (M || minutes) + ':' + (S || seconds);
}

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

Brew doctor says: "Warning: /usr/local/include isn't writable."

You can alias the command to fix this problem in your .bash_profile and run it every time you encounter it:

At the end of the file ~/.bash_profile, add:

alias fix_brew='sudo chown -R $USER /usr/local/'

And now inside your terminal you can run:

$ fix_brew

How to pad a string to a fixed length with spaces in Python?

This is super simple with format:

>>> a = "John"
>>> "{:<15}".format(a)
'John           '

Show or hide element in React

There are several great answers already, but I don't think they've been explained very well and several of the methods given contain some gotchas that might trip people up. So I'm going to go over the three main ways (plus one off-topic option) to do this and explain the pros and cons. I'm mostly writing this because Option 1 was recommended a lot and there's a lot of potential issues with that option if not used correctly.

Option 1: Conditional Rendering in the parent.

I don't like this method unless you're only going to render the component one time and leave it there. The issue is it will cause react to create the component from scratch every time you toggle the visibility. Here's the example. LogoutButton or LoginButton are being conditionally rendered in the parent LoginControl. If you run this you'll notice the constructor is getting called on each button click. https://codepen.io/Kelnor/pen/LzPdpN?editors=1111

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;

    let button = null;
    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }
}

class LogoutButton extends React.Component{
  constructor(props, context){
    super(props, context)
    console.log('created logout button');
  }
  render(){
    return (
      <button onClick={this.props.onClick}>
        Logout
      </button>
    );
  }
}

class LoginButton extends React.Component{
  constructor(props, context){
    super(props, context)
    console.log('created login button');
  }
  render(){
    return (
      <button onClick={this.props.onClick}>
        Login
      </button>
    );
  }
}

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

Now React is pretty quick at creating components from scratch. However, it still has to call your code when creating it. So if your constructor, componentDidMount, render, etc code is expensive, then it'll significantly slow down showing the component. It also means you cannot use this with stateful components where you want the state to be preserved when hidden (and restored when displayed.) The one advantage is that the hidden component isn't created at all until it's selected. So hidden components won't delay your initial page load. There may also be cases where you WANT a stateful component to reset when toggled. In which case this is your best option.

Option 2: Conditional Rendering in the child

This creates both components once. Then short circuits the rest of the render code if the component is hidden. You can also short circuit other logic in other methods using the visible prop. Notice the console.log in the codepen page. https://codepen.io/Kelnor/pen/YrKaWZ?editors=0011

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        <LoginButton isLoggedIn={isLoggedIn} onClick={this.handleLoginClick}/>
        <LogoutButton isLoggedIn={isLoggedIn} onClick={this.handleLogoutClick}/>
      </div>
    );
  }
}

class LogoutButton extends React.Component{
  constructor(props, context){
    super(props, context)
    console.log('created logout button');
  }
  render(){
    if(!this.props.isLoggedIn){
      return null;
    }
    return (
      <button onClick={this.props.onClick}>
        Logout
      </button>
    );
  }
}

class LoginButton extends React.Component{
  constructor(props, context){
    super(props, context)
    console.log('created login button');
  }
  render(){
    if(this.props.isLoggedIn){
      return null;
    }
    return (
      <button onClick={this.props.onClick}>
        Login
      </button>
    );
  }
}

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

Now, if the initialization logic is quick and the children are stateless, then you won't see a difference in performance or functionality. However, why make React create a brand new component every toggle anyway? If the initialization is expensive however, Option 1 will run it every time you toggle a component which will slow the page down when switching. Option 2 will run all of the component's inits on first page load. Slowing down that first load. Should note again. If you're just showing the component one time based on a condition and not toggling it, or you want it to reset when toggledm, then Option 1 is fine and probably the best option.

If slow page load is a problem however, it means you've got expensive code in a lifecycle method and that's generally not a good idea. You can, and probably should, solve the slow page load by moving the expensive code out of the lifecycle methods. Move it to an async function that's kicked off by ComponentDidMount and have the callback put it in a state variable with setState(). If the state variable is null and the component is visible then have the render function return a placeholder. Otherwise render the data. That way the page will load quickly and populate the tabs as they load. You can also move the logic into the parent and push the results to the children as props. That way you can prioritize which tabs get loaded first. Or cache the results and only run the logic the first time a component is shown.

Option 3: Class Hiding

Class hiding is probably the easiest to implement. As mentioned you just create a CSS class with display: none and assign the class based on prop. The downside is the entire code of every hidden component is called and all hidden components are attached to the DOM. (Option 1 doesn't create the hidden components at all. And Option 2 short circuits unnecessary code when the component is hidden and removes the component from the DOM completely.) It appears this is faster at toggling visibility according some tests done by commenters on other answers but I can't speak to that.

Option 4: One component but change Props. Or maybe no component at all and cache HTML.

This one won't work for every application and it's off topic because it's not about hiding components, but it might be a better solution for some use cases than hiding. Let's say you have tabs. It might be possible to write one React Component and just use the props to change what's displayed in the tab. You could also save the JSX to state variables and use a prop to decide which JSX to return in the render function. If the JSX has to be generated then do it and cache it in the parent and send the correct one as a prop. Or generate in the child and cache it in the child's state and use props to select the active one.

Import .bak file to a database in SQL server

You can use node package, if you often need to restore databases in development process.

Install:

npm install -g sql-bak-restore

Usage:

sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>

Arguments:

  • bakpath, relative or absolute path to file
  • dbName, to which database to restore (!! database with this name will be deleted if exists !!)
  • oldDbName, database name (if you don't know, specify something and run, you will see available databases after run.)
  • owner, userName to make and give him db_owner privileges (password "1")

!! sqlcmd command line utility should be in your PATH variable.

https://github.com/vladimirbuskin/sql-bak-restore/

Is there a way to check for both `null` and `undefined`?

if(data){}

it's mean !data

  • null
  • undefined
  • false
  • ....

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

Kafka consumer list

All the consumers per topic

(Replace --zookeeper with --bootstrap-server to get groups stored by newer Kafka clients)

Get all consumers-per-topic as a table of topictabconsumer:

for t in `kafka-consumer-groups.sh --zookeeper <HOST>:2181 --list 2>/dev/null`; do
    echo $t | xargs -I {} sh -c "kafka-consumer-groups.sh --zookeeper <HOST>:2181 --describe --group {} 2>/dev/null | grep ^{} | awk '{print \$2\"\t\"\$1}' "
done > topic-consumer.txt

Make this pairs unique:

cat topic-consumer.txt | sort -u > topic-consumer-u.txt

Get the desired one:

less topic-consumer-u.txt | grep -i <TOPIC>

How do I remove the horizontal scrollbar in a div?

Add this code to your CSS. It will disable the horizontal scrollbar.

html, body {
    max-width: 100%;
    overflow-x: hidden;
}

Could not load file or assembly '***.dll' or one of its dependencies

This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...

In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.

(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)

Restful API service

Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)

No you have to create a thread yourself, a Local service runs in the UI thread by default.

Exporting result of select statement to CSV format in DB2

According to the docs, you want to export of type del (the default delimiter looks like a comma, which is what you want). See the doc page for more information on the EXPORT command.

Python: Remove division decimal

>>> int(2.0)

You will get the answer as 2

How to test code dependent on environment variables using JUnit?

Well you can use the setup() method to declare the different values of your env. variables in constants. Then use these constants in the tests methods used to test the different scenario.

Limit Decimal Places in Android EditText

@Meh for u..

txtlist.setFilters(new InputFilter[] { new DigitsKeyListener( Boolean.FALSE,Boolean.TRUE) {

        int beforeDecimal = 7;
        int afterDecimal = 2;

        @Override
        public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {

            String etText = txtlist.getText().toString();
            String temp = txtlist.getText() + source.toString();
            if (temp.equals(".")) {
                return "0.";
            } else if (temp.toString().indexOf(".") == -1) {
                // no decimal point placed yet
                 if (temp.length() > beforeDecimal) {
                    return "";
                }
            } else {
                int dotPosition ;
                int cursorPositon = txtlistprice.getSelectionStart();
                if (etText.indexOf(".") == -1) {
                    dotPosition = temp.indexOf(".");
                }else{
                    dotPosition = etText.indexOf(".");
                }
                if(cursorPositon <= dotPosition){
                    String beforeDot = etText.substring(0, dotPosition);
                    if(beforeDot.length()<beforeDecimal){
                        return source;
                    }else{
                        if(source.toString().equalsIgnoreCase(".")){
                            return source;
                        }else{
                            return "";
                        }
                    }
                }else{
                    temp = temp.substring(temp.indexOf(".") + 1);
                    if (temp.length() > afterDecimal) {
                        return "";
                    }
                }
            }
            return super.filter(source, start, end, dest, dstart, dend);
        }
    } });

How to compare each item in a list with the rest, only once?

Your solution is correct, but your outer loop is still longer than needed. You don't need to compare the last element with anything else because it's been already compared with all the others in the previous iterations. Your inner loop still prevents that, but since we're talking about collision detection you can save the unnecessary check.

Using the same language you used to illustrate your algorithm, you'd come with something like this:

for (int i = 0, i < mylist.size() - 1; ++i)
    for (int j = i + 1, j < mylist.size(); --j)
        compare(mylist[i], mylist[j])

How to detect the physical connected state of a network cable/connector?

You can use ifconfig.

# ifconfig eth0 up
# ifconfig eth0

If the entry shows RUNNING, the interface is physically connected. This will be shown regardless if the interface is configured.

This is just another way to get the information in /sys/class/net/eth0/operstate.

Should I use the Reply-To header when sending emails as a service to others?

I tested dkarp's solution with gmail and it was filtered to spam. Use the Reply-To header instead (or in addition, although gmail apparently doesn't need it). Here's how linkedin does it:

Sender: [email protected]
From: John Doe via LinkedIn <[email protected]>
Reply-To: John Doe <[email protected]>
To: My Name <[email protected]>

Once I switched to this format, gmail is no longer filtering my messages as spam.

How to open mail app from Swift

For those of us still lagging behind on Swift 2.3 here is Gordon's answer in our syntax:

let email = "[email protected]"
if let url = NSURL(string: "mailto:\(email)") {
   UIApplication.sharedApplication().openURL(url)
}

Create ul and li elements in javascript.

Use the CSS property list-style-position to position the bullet:

list-style-position:inside /* or outside */;

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Pls, check if DataGridComboBoxColumn xaml below would work for you:

<DataGridComboBoxColumn 
    SelectedValueBinding="{Binding CompanyID}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="ID">

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid

Real differences between "java -server" and "java -client"?

Oracle’s online documentation provides some information for Java SE 7.

On the java – the Java application launcher page for Windows, the -client option is ignored in a 64-bit JDK:

Select the Java HotSpot Client VM. A 64-bit capable jdk currently ignores this option and instead uses the Java HotSpot Server VM.

However (to make things interesting), under -server it states:

Select the Java HotSpot Server VM. On a 64-bit capable jdk only the Java HotSpot Server VM is supported so the -server option is implicit. This is subject to change in a future release.

The Server-Class Machine Detection page gives information on which VM is selected by OS and architecture.

I don’t know how much of this applies to JDK 6.

JavaScript equivalent to printf/String.Format

We can use a simple lightweight String.Format string operation library for Typescript.

String.Format():

var id = image.GetId()
String.Format("image_{0}.jpg", id)
output: "image_2db5da20-1c5d-4f1a-8fd4-b41e34c8c5b5.jpg";

String Format for specifiers:

var value = String.Format("{0:L}", "APPLE"); //output "apple"

value = String.Format("{0:U}", "apple"); // output "APPLE"

value = String.Format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"


value = String.Format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"

value = String.Format("{0:n}", 1000000);
//output "1.000.000"

value = String.Format("{0:00}", 1);
//output "01"

String Format for Objects including specifiers:

var fruit = new Fruit();
fruit.type = "apple";
fruit.color = "RED";
fruit.shippingDate = new Date(2018, 1, 1);
fruit.amount = 10000;

String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
// output: the APPLE is red shipped on 2018-01-01 with an amount of 10.000

How can I change the color of pagination dots of UIPageControl?

Add the following code to DidFinishLauch in AppDelegate,

UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
pageControl.backgroundColor = [UIColor whiteColor];

Hope this will help.

How to ignore certain files in Git

1) Create a .gitignore file. To do that, you just create a .txt file and change the extension as follows:

Enter image description here

Then you have to change the name, writing the following line in a cmd window:

 rename git.txt .gitignore

Where git.txt is the name of the file you've just created.

Then you can open the file and write all the files you don’t want to add on the repository. For example, mine looks like this:

#OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Once you have this, you need to add it to your Git repository. You have to save the file where your repository is.

Then in Git Bash you have to write the following line:

git config --global core.excludesfile ~/.gitignore_global

If the repository already exists then you have to do the following:

  1. git rm -r --cached .
  2. git add .
  3. git commit -m ".gitignore is now working"

If the step 2 doesn’t work then you should write the whole route of the files that you would like to add.

Notepad++ Setting for Disabling Auto-open Previous Files

I read the answers. Then I noticed for me that the check box was already unchecked, but it still always reloaded the files. This is the Settings->Preferences->MISC->"Remember current session for next launch" check box on version 6.3.2. The following got rid of the problem:

1. Check the check box.
2. Exit the program.
3. Start the program again.
4. Uncheck the checkbox.

How is __eq__ handled in Python and in what order?

I'm writing an updated answer for Python 3 to this question.

How is __eq__ handled in Python and in what order?

a == b

It is generally understood, but not always the case, that a == b invokes a.__eq__(b), or type(a).__eq__(a, b).

Explicitly, the order of evaluation is:

  1. if b's type is a strict subclass (not the same type) of a's type and has an __eq__, call it and return the value if the comparison is implemented,
  2. else, if a has __eq__, call it and return it if the comparison is implemented,
  3. else, see if we didn't call b's __eq__ and it has it, then call and return it if the comparison is implemented,
  4. else, finally, do the comparison for identity, the same comparison as is.

We know if a comparison isn't implemented if the method returns NotImplemented.

(In Python 2, there was a __cmp__ method that was looked for, but it was deprecated and removed in Python 3.)

Let's test the first check's behavior for ourselves by letting B subclass A, which shows that the accepted answer is wrong on this count:

class A:
    value = 3
    def __eq__(self, other):
        print('A __eq__ called')
        return self.value == other.value

class B(A):
    value = 4
    def __eq__(self, other):
        print('B __eq__ called')
        return self.value == other.value

a, b = A(), B()
a == b

which only prints B __eq__ called before returning False.

How do we know this full algorithm?

The other answers here seem incomplete and out of date, so I'm going to update the information and show you how how you could look this up for yourself.

This is handled at the C level.

We need to look at two different bits of code here - the default __eq__ for objects of class object, and the code that looks up and calls the __eq__ method regardless of whether it uses the default __eq__ or a custom one.

Default __eq__

Looking __eq__ up in the relevant C api docs shows us that __eq__ is handled by tp_richcompare - which in the "object" type definition in cpython/Objects/typeobject.c is defined in object_richcompare for case Py_EQ:.

    case Py_EQ:
        /* Return NotImplemented instead of False, so if two
           objects are compared, both get a chance at the
           comparison.  See issue #1393. */
        res = (self == other) ? Py_True : Py_NotImplemented;
        Py_INCREF(res);
        break;

So here, if self == other we return True, else we return the NotImplemented object. This is the default behavior for any subclass of object that does not implement its own __eq__ method.

How __eq__ gets called

Then we find the C API docs, the PyObject_RichCompare function, which calls do_richcompare.

Then we see that the tp_richcompare function, created for the "object" C definition is called by do_richcompare, so let's look at that a little more closely.

The first check in this function is for the conditions the objects being compared:

  • are not the same type, but
  • the second's type is a subclass of the first's type, and
  • the second's type has an __eq__ method,

then call the other's method with the arguments swapped, returning the value if implemented. If that method isn't implemented, we continue...

    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        checked_reverse_op = 1;
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Next we see if we can lookup the __eq__ method from the first type and call it. As long as the result is not NotImplemented, that is, it is implemented, we return it.

    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
        res = (*f)(v, w, op);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Else if we didn't try the other type's method and it's there, we then try it, and if the comparison is implemented, we return it.

    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);
    }

Finally, we get a fallback in case it isn't implemented for either one's type.

The fallback checks for the identity of the object, that is, whether it is the same object at the same place in memory - this is the same check as for self is other:

    /* If neither object implements it, provide a sensible default
       for == and !=, but raise an exception for ordering. */
    switch (op) {
    case Py_EQ:
        res = (v == w) ? Py_True : Py_False;
        break;

Conclusion

In a comparison, we respect the subclass implementation of comparison first.

Then we attempt the comparison with the first object's implementation, then with the second's if it wasn't called.

Finally we use a test for identity for comparison for equality.

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

How to detect browser using angularjs?

Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.

So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).

However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.

I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059

Javascript one line If...else...else if statement

tl;dr

Yes, you can... If a then a, else if b then if c then c(b), else b, else null

a ? a : (b ? (c ? c(b) : b) : null)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

longer version

Ternary operator ?: used as inline if-else is right associative. In short this means that the rightmost ? gets fed first and it takes exactly one closest operand on the left and two, with a :, on the right.

Practically speaking, consider the following statement (same as above):

a ? a : b ? c ? c(b) : b : null

The rightmost ? gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?.

   a ? a : b ? c ? c(b) : b : null
                 ^                  <---- RTL
1.            |1-?-2----:-3|
             ^ <-
2.        |1-?|--2---------|:-3---|
     ^ <-
3.|1-?-2-:|--3--------------------|

result: a ? a : (b ? (c ? c(b) : b) : null)

This is how computers read it:

  1. Term a is read.
    Node: a
  2. Nonterminal ? is read.
    Node: a ?
  3. Term a is read.
    Node: a ? a
  4. Nonterminal : is read.
    Node: a ? a :
  5. Term b is read.
    Node: a ? a : b
  6. Nonterminal ? is read, triggering the right-associativity rule. Associativity decides:
    node: a ? a : (b ?
  7. Term c is read.
    Node: a ? a : (b ? c
  8. Nonterminal ? is read, re-applying the right-associativity rule.
    Node: a ? a : (b ? (c ?
  9. Term c(b) is read.
    Node: a ? a : (b ? (c ? c(b)
  10. Nonterminal : is read.
    Node: a ? a : (b ? (c ? c(b) :
  11. Term b is read.
    Node: a ? a : (b ? (c ? c(b) : b
  12. Nonterminal : is read. The ternary operator ?: from previous scope is satisfied and the scope is closed.
    Node: a ? a : (b ? (c ? c(b) : b) :
  13. Term null is read.
    Node: a ? a : (b ? (c ? c(b) : b) : null
  14. No tokens to read. Close remaining open parenthesis.
    #Result is: a ? a : (b ? (c ? c(b) : b) : null)

Better readability

The ugly oneliner from above could (and should) be rewritten for readability as:
(Note that the indentation does not implicitly define correct closures as brackets () do.)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

for example

return a + some_lengthy_variable_name > another_variable
        ? "yep"
        : "nop"

More reading

Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity


Bonus: Logical operators

var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!

a
  && a
  || b
      && c
        && c(b) // if this returns false, || b is processed
        || b
      || null

Using logical operators as in this example is ugly and wrong, but this is where they shine...

"Null coalescence"

This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.

function f(mayBeNullOrFalsy) {
  var cantBeNull = mayBeNullOrFalsy || 42                    // "default" value
  var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42  // ugly...
  ..
}

Short-circuit evaluation

false && (anything) // is short-circuit evaluated to false.
true || (anything)  // is short-circuit evaluated to true.

Logical operators
Null coalescence
Short-circuit evaluation


Bonus2: new in JS

Proper "Nullish coalescing"

developer.mozilla.org~Nullish_coalescing_operator

function f(mayBeNullOrUndefined, another) {
  var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
  another ??= 37 // nullish coalescing self-assignment
  another = another ?? 37 // same effect
  ..
}

Optional chaining

Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

// before
var street = user.address && user.address.street
// after
var street = user.address?.street

// combined with Nullish coalescing
// before
var street = user.address
  ? user.address.street
  : "N/A"

// after
var street = user.address?.street ?? "N/A"

// arrays
obj.someArray?.[index]

// functions
obj.someMethod?.(args)

Using CSS to affect div style inside iframe

You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.

Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.

I use the Prototype framework to make it easier:

frame1.$('mydiv').style.border = '1px solid #000000'

or

frame1.$('mydiv').addClassName('withborder')

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']

Passing arguments to an interactive program non-interactively

For more complex tasks there is expect ( http://en.wikipedia.org/wiki/Expect ). It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.

This also works in cases like ssh that prohibits piping passwords to it.

Hibernate Auto Increment ID

In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.

I have found that this works...as an example.

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;

For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .

In my case i do an HTML POST with JSON like so...

{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

What is a plain English explanation of "Big O" notation?

I've more simpler way to understand the time complexity he most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N

for ( i = 0; i < N; i++ )
  statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) 
{
for ( j = 0; j < N; j++ )
  statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) 
{
 mid = ( low + high ) / 2;
 if ( target < list[mid] )
 high = mid - 1;
 else if ( target > list[mid] )
  low = mid + 1;
else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note: None of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course.

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

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

This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view. Sample pseudo code which could help coding the actual.

var tabelDetails =(from li in dc.My_table
    join m in dc.Table_One on li.ID equals m.ID
    join c in dc.Table_two on li.OtherID equals c.ID
    where //Condition
group new { m, li, c } by new
{
    m.ID,
    m.Name
} into g
select new
{
    g.Key.ID,
    Name = g.Key.FullName,
    sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
    pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
    staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),   
    leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),  
    rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),  
    Total = g.Count()  //Row wise Total
}).OrderBy(t => t.Name).ToList();

tabelDetails.Insert(tabelDetails.Count(), new  //This data will be the last row of the grid
{
    Name = "Total",  //Column wise total
    sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
    pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
    staticBonus = tabelDetails.Sum(s => s.staticBonus),
    leftBonus = tabelDetails.Sum(s => s.leftBonus),
    rightBonus = tabelDetails.Sum(s => s.rightBonus ),
    Total = tabelDetails.Sum(s => s.Total)
});

How can I display just a portion of an image in HTML/CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.

Understanding React-Redux and mapStateToProps()

This react & redux example is based off Mohamed Mellouki's example. But validates using prettify and linting rules. Note that we define our props and dispatch methods using PropTypes so that our compiler doesn't scream at us. This example also included some lines of code that had been missing in Mohamed's example. To use connect you will need to import it from react-redux. This example also binds the method filterItems this will prevent scope problems in the component. This source code has been auto formatted using JavaScript Prettify.

import React, { Component } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class ItemsContainer extends Component {
  constructor(props) {
    super(props);
    const { items, filters } = props;
    this.state = {
      items,
      filteredItems: filterItems(items, filters),
    };
    this.filterItems = this.filterItems.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const { itmes } = this.state;
    const { filters } = nextProps;
    this.setState({ filteredItems: filterItems(items, filters) });
  }

  filterItems = (items, filters) => {
    /* return filtered list */
  };

  render() {
    return <View>/*display the filtered items */</View>;
  }
}

/*
define dispatch methods in propTypes so that they are validated.
*/
ItemsContainer.propTypes = {
  items: PropTypes.array.isRequired,
  filters: PropTypes.array.isRequired,
  onMyAction: PropTypes.func.isRequired,
};

/*
map state to props
*/
const mapStateToProps = state => ({
  items: state.App.Items.List,
  filters: state.App.Items.Filters,
});

/*
connect dispatch to props so that you can call the methods from the active props scope.
The defined method `onMyAction` can be called in the scope of the componets props.
*/
const mapDispatchToProps = dispatch => ({
  onMyAction: value => {
    dispatch(() => console.log(`${value}`));
  },
});

/* clean way of setting up the connect. */
export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);

This example code is a good template for a starting place for your component.

How to get the list of properties of a class?

That's my solution

public class MyObject
{
    public string value1 { get; set; }
    public string value2 { get; set; }

    public PropertyInfo[] GetProperties()
    {
        try
        {
            return this.GetType().GetProperties();
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public PropertyInfo GetByParameterName(string ParameterName)
    {
        try
        {
            return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
    {
        try
        {
            obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
            return obj;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

SpringApplication.run main method

One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.

@SpringBootApplication
public class ChildApplication extends ParentApplication{
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}

How do I programmatically click on an element in JavaScript?

Here's a cross browser working function (usable for other than click handlers too):

function eventFire(el, etype){
    if (el.fireEvent) {
      el.fireEvent('on' + etype);
    } else {
      var evObj = document.createEvent('Events');
      evObj.initEvent(etype, true, false);
      el.dispatchEvent(evObj);
    }
}

OR is not supported with CASE Statement in SQL Server

That format requires you to use either:

CASE ebv.db_no 
  WHEN 22978 THEN 'WECS 9500' 
  WHEN 23218 THEN 'WECS 9500'  
  WHEN 23219 THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

Otherwise, use:

CASE  
  WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

JSON.net: how to deserialize without using the default constructor?

Based on some of the answers here, I have written a CustomConstructorResolver for use in a current project, and I thought it might help somebody else.

It supports the following resolution mechanisms, all configurable:

  • Select a single private constructor so you can define one private constructor without having to mark it with an attribute.
  • Select the most specific private constructor so you can have multiple overloads, still without having to use attributes.
  • Select the constructor marked with an attribute of a specific name - like the default resolver, but without a dependency on the Json.Net package because you need to reference Newtonsoft.Json.JsonConstructorAttribute.
public class CustomConstructorResolver : DefaultContractResolver
{
    public string ConstructorAttributeName { get; set; } = "JsonConstructorAttribute";
    public bool IgnoreAttributeConstructor { get; set; } = false;
    public bool IgnoreSinglePrivateConstructor { get; set; } = false;
    public bool IgnoreMostSpecificConstructor { get; set; } = false;

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var contract = base.CreateObjectContract(objectType);

        // Use default contract for non-object types.
        if (objectType.IsPrimitive || objectType.IsEnum) return contract;

        // Look for constructor with attribute first, then single private, then most specific.
        var overrideConstructor = 
               (this.IgnoreAttributeConstructor ? null : GetAttributeConstructor(objectType)) 
            ?? (this.IgnoreSinglePrivateConstructor ? null : GetSinglePrivateConstructor(objectType)) 
            ?? (this.IgnoreMostSpecificConstructor ? null : GetMostSpecificConstructor(objectType));

        // Set override constructor if found, otherwise use default contract.
        if (overrideConstructor != null)
        {
            SetOverrideCreator(contract, overrideConstructor);
        }

        return contract;
    }

    private void SetOverrideCreator(JsonObjectContract contract, ConstructorInfo attributeConstructor)
    {
        contract.OverrideCreator = CreateParameterizedConstructor(attributeConstructor);
        contract.CreatorParameters.Clear();
        foreach (var constructorParameter in base.CreateConstructorParameters(attributeConstructor, contract.Properties))
        {
            contract.CreatorParameters.Add(constructorParameter);
        }
    }

    private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
    {
        var c = method as ConstructorInfo;
        if (c != null)
            return a => c.Invoke(a);
        return a => method.Invoke(null, a);
    }

    protected virtual ConstructorInfo GetAttributeConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(c => c.GetCustomAttributes().Any(a => a.GetType().Name == this.ConstructorAttributeName)).ToList();

        if (constructors.Count == 1) return constructors[0];
        if (constructors.Count > 1)
            throw new JsonException($"Multiple constructors with a {this.ConstructorAttributeName}.");

        return null;
    }

    protected virtual ConstructorInfo GetSinglePrivateConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

        return constructors.Length == 1 ? constructors[0] : null;
    }

    protected virtual ConstructorInfo GetMostSpecificConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .OrderBy(e => e.GetParameters().Length);

        var mostSpecific = constructors.LastOrDefault();
        return mostSpecific;
    }
}

Here is the complete version with XML documentation as a gist: https://gist.github.com/maverickelementalch/80f77f4b6bdce3b434b0f7a1d06baa95

Feedback appreciated.

Why do I need an IoC container as opposed to straightforward DI code?

Wow, can't believe that Joel would favor this:

var svc = new ShippingService(new ProductLocator(), 
   new PricingService(), new InventoryService(), 
   new TrackingRepository(new ConfigProvider()), 
   new Logger(new EmailLogger(new ConfigProvider())));

over this:

var svc = IoC.Resolve<IShippingService>();

Many folks don't realize that your dependencies chain can become nested, and it quickly becomes unwieldy to wire them up manually. Even with factories, the duplication of your code is just not worth it.

IoC containers can be complex, yes. But for this simple case I've shown it's incredibly easy.


Okay, let's justify this even more. Let's say you have some entities or model objects that you want to bind to a smart UI. This smart UI (we'll call it Shindows Morms) wants you to implement INotifyPropertyChanged so that it can do change tracking & update the UI accordingly.

"OK, that doesn't sound so hard" so you start writing.

You start with this:

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime CustomerSince { get; set; }
    public string Status { get; set; }
}

..and end up with this:

public class UglyCustomer : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            string oldValue = _firstName;
            _firstName = value;
            if(oldValue != value)
                OnPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            string oldValue = _lastName;
            _lastName = value;
            if(oldValue != value)
                OnPropertyChanged("LastName");
        }
    }

    private DateTime _customerSince;
    public DateTime CustomerSince
    {
        get { return _customerSince; }
        set
        {
            DateTime oldValue = _customerSince;
            _customerSince = value;
            if(oldValue != value)
                OnPropertyChanged("CustomerSince");
        }
    }

    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            string oldValue = _status;
            _status = value;
            if(oldValue != value)
                OnPropertyChanged("Status");
        }
    }

    protected virtual void OnPropertyChanged(string property)
    {
        var propertyChanged = PropertyChanged;

        if(propertyChanged != null)
            propertyChanged(this, new PropertyChangedEventArgs(property));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

That's disgusting plumbing code, and I maintain that if you're writing code like that by hand you're stealing from your client. There are better, smarter way of working.

Ever hear that term, work smarter, not harder?

Well imagine some smart guy on your team came up and said: "Here's an easier way"

If you make your properties virtual (calm down, it's not that big of a deal) then we can weave in that property behavior automatically. (This is called AOP, but don't worry about the name, focus on what it's going to do for you)

Depending on which IoC tool you're using, you could do something that looks like this:

var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());

Poof! All of that manual INotifyPropertyChanged BS is now automatically generated for you, on every virtual property setter of the object in question.

Is this magic? YES! If you can trust the fact that this code does its job, then you can safely skip all of that property wrapping mumbo-jumbo. You've got business problems to solve.

Some other interesting uses of an IoC tool to do AOP:

  • Declarative & nested database transactions
  • Declarative & nested Unit of work
  • Logging
  • Pre/Post conditions (Design by Contract)

Git mergetool generates unwanted .orig files

Besides the correct answers offered as long term solutions, you can use git to remove all unnecessary files once for you with the git clean -f command but use git clean --dry-run first to ensure nothing unintended would happen.

This has the benefit of using tested built in functionality of Git over scripts specific to your OS/shell to remove the files.

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

What is the difference between a definition and a declaration?

According to the GNU C library manual (http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)

In C, a declaration merely provides information that a function or variable exists and gives its type. For a function declaration, information about the types of its arguments might be provided as well. The purpose of declarations is to allow the compiler to correctly process references to the declared variables and functions. A definition, on the other hand, actually allocates storage for a variable or says what a function does.

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

How to use session in JSP pages to get information?

Use

<% String username = (String)request.getSession().getAttribute(...); %>

Note that your use of <%! ... %> is translated to class-level, but request is only available in the service() method of the translated servlet.

See how JSP code is translated to a servlet.

Response.Redirect with POST instead of Get?

HttpWebRequest is used for this.

On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.

You get the added advantage that you don't have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.

string url = "3rd Party Url";

StringBuilder postData = new StringBuilder();

postData.Append("first_name=" + HttpUtility.UrlEncode(txtFirstName.Text) + "&");
postData.Append("last_name=" + HttpUtility.UrlEncode(txtLastName.Text));

//ETC for all Form Elements

// Now to Send Data.
StreamWriter writer = null;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";                        
request.ContentLength = postData.ToString().Length;
try
{
    writer = new StreamWriter(request.GetRequestStream());
    writer.Write(postData.ToString());
}
finally
{
    if (writer != null)
        writer.Close();
}

Response.Redirect("NewPage");

However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.

Fluid width with equally spaced DIVs

The easiest way to do this now is with a flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The CSS is then simply:

#container {
    display: flex;
    justify-content: space-between;
}

demo: http://jsfiddle.net/QPrk3/

However, this is currently only supported by relatively recent browsers (http://caniuse.com/flexbox). Also, the spec for flexbox layout has changed a few times, so it's possible to cover more browsers by additionally including an older syntax:

http://css-tricks.com/old-flexbox-and-new-flexbox/

http://css-tricks.com/using-flexbox/

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

If you want to use parameters for a,b,c,d in Laravel 4

Model::where(function ($query) use ($a,$b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.