Programs & Examples On #Digital signature

mathematical scheme for demonstrating the authenticity of a digital message or document (Wikipedia). A cryptographic toolkit is often used along with a public-private key pair to digitally sign a message and to verify a message.

app-release-unsigned.apk is not signed

My problem was solved by changing the build variant as suggested by Stéphane , if anyone was struggling to find the "Build variants" as I did here is a screenshot where you can find it .

enter image description here

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

To produce the same results:

MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");

AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);

byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

HMAC-SHA256 Algorithm for signature calculation

Here is my solution:

public String HMAC_SHA256(String secret, String message)
{
    String hash="";
    try{
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
    }catch (Exception e)
    {

    }
    return hash.trim();
}

ImportError: Cannot import name X

The problem is clear: circular dependency between names in entity and physics modules.

Regardless of importing the whole module or just a class, the names must be loaded .

Watch this example:

# a.py
import b
def foo():
  pass
b.bar()
# b.py
import a
def bar():
  pass
a.foo()

This will be compiled into:

# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
  pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
  pass
b.bar()
# done!

With one slight change we can solve this:

# a.py
def foo():
  pass
import b
b.bar()
# b.py
def bar():
  pass
import a
a.foo()

This will be compiled into:

# a.py
def foo():
  pass
# import b
# b.py
def bar():
  pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!

Why use prefixes on member variables in C++ classes

You should never need such a prefix. If such a prefix offers you any advantage, your coding style in general needs fixing, and it's not the prefix that's keeping your code from being clear. Typical bad variable names include "other" or "2". You do not fix that with requiring it to be mOther, you fix it by getting the developer to think about what that variable is doing there in the context of that function. Perhaps he meant remoteSide, or newValue, or secondTestListener or something in that scope.

It's an effective anachronism that's still propagated too far. Stop prefixing your variables and give them proper names whose clarity reflects how long they're used. Up to 5 lines you could call it "i" without confusion; beyond 50 lines you need a pretty long name.

How to delete SQLite database from Android programmatically

Once you have your Context and know the name of the database, use:

context.deleteDatabase(DATABASE_NAME);

When this line gets run, the database should be deleted.

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

OnItemCLickListener not working in listview

you need to do 2 steps in your listview_item.xml

  1. set the root layout with: android:descendantFocusability="blocksDescendants"
  2. set any focusable or clickable view in this item with:
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"

Here is an example: listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants">

    <RadioButton
        android:id="@+id/script_name_radio_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textColor="#000"
        android:padding="5dp"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        />

</LinearLayout>

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

Windows equivalent to UNIX pwd

hmm - pwd works for me on Vista...

Final EDIT: it works for me on Vista because WinAvr installed pwd.exe and added \Program Files\WinAvr\Utils\bin to my path.

Check/Uncheck a checkbox on datagridview

I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:

Turns out, I called the form1.PopulateDataGridView(my data) on the Form derived class Form1 before I called form1.Show(). When I changed up the order, that is to call Show() first, and then read the data and fill in the checkboxes, the value did not stay null.

Download File Using Javascript/jQuery

let args = {"data":htmlData,"filename":exampleName}

To create a HTMl file and download

window.downloadHTML = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.html';
data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
console.log(data);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}

To create and download a CSV

window.downloadCSV = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.csv';
if (!csv.match(/^data:text\/csv/i)) {
    csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

}

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

TypeError: $ is not a function when calling jQuery function

You come across this issue when your function name and one of the id names in the file are same. just make sure all your id names in the file are unique.

.attr("disabled", "disabled") issue

UPDATED

DEMO: http://jsbin.com/uneti3/3

your code is wrong, it should be something like this:

 $(bla).click(function() { 
        var disable =  $target.toggleClass('open').hasClass('open');
       $target.prev().prop("disabled", disable);
  });

you are using the toggleClass function in wrong way

static const vs #define

Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:

  1. enums:

    • only possible for integer values
    • properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
    • strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
    • can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
    • stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
    • each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
    • even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
    • the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
    • you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)

  1. consts:

    • properly scoped / identifier clash issues handled nicely
    • strong, single, user-specified type
      • you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
    • One Definition Rule complications
    • can take address, create const references to them etc.
    • most similar to a non-const value, which minimises work and impact if switching between the two
    • value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change

  1. #defines:

    • "global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
      • long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
      • while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
    • more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
      • downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
    • can't use sizeof directly on a defined numeric literal
    • untyped (GCC doesn't warn if compared to unsigned)
    • some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
    • can't take the address
    • the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
    • some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
    • you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
    • substituted text has to be exposed:
      • in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
      • or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)

My personal opinion:

As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).

How to hide action bar before activity is created, and then show it again?

Just add this to your MainActivity in the onCreate function.

val actionBar = supportActionBar?.apply { hide() }

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

In my case, the import references in many of the classes contained an extra word. I solved it by editing all the files to have the correct imports. I started doing the edits manually. But when I saw the pattern, I automated it with a find..replace in eclipse. This resolved the error.

JS search in object values

Something like this:

var objects = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
];

var results = [];

var toSearch = "lo";

for(var i=0; i<objects.length; i++) {
  for(key in objects[i]) {
    if(objects[i][key].indexOf(toSearch)!=-1) {
      results.push(objects[i]);
    }
  }
}

The results array will contain all matched objects.

If you search for 'lo', the result will be like:

[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]

NEW VERSION - Added trim code, code to ensure no duplicates in result set.

function trimString(s) {
  var l=0, r=s.length -1;
  while(l < s.length && s[l] == ' ') l++;
  while(r > l && s[r] == ' ') r-=1;
  return s.substring(l, r+1);
}

function compareObjects(o1, o2) {
  var k = '';
  for(k in o1) if(o1[k] != o2[k]) return false;
  for(k in o2) if(o1[k] != o2[k]) return false;
  return true;
}

function itemExists(haystack, needle) {
  for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
  return false;
}

var objects = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor blor",
    "bar" : "amet blo"
  }
];

function searchFor(toSearch) {
  var results = [];
  toSearch = trimString(toSearch); // trim it
  for(var i=0; i<objects.length; i++) {
    for(var key in objects[i]) {
      if(objects[i][key].indexOf(toSearch)!=-1) {
        if(!itemExists(results, objects[i])) results.push(objects[i]);
      }
    }
  }
  return results;
}

console.log(searchFor('lo '));

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

Changing API level Android Studio

For me what worked was: (right click)project->android tools->clear lint markers. Although for some reason the Manifest reverted to the old (lower) minimum API level, but after I changed it back to the new (higher) API level there was no red error underline and the project now uses the new minimum API level.

Edit: Sorry, I see you were using Android Studio, not Eclipse. But I guess there is a similar 'clear lint markers' in Studio somewhere and it might solve the problem.

Match exact string

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you would want to use \b (word boundaries):

_x000D_
_x000D_
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
_x000D_
_x000D_

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Windows batch - concatenate multiple text files into one

Try this:

@echo off
set yyyy=%date:~6,4%
set mm=%date:~3,2%
set dd=%date:~0,2%

set /p temp= "Enter the name of text file: "
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%temp%.txt

This code ask you to set the name of the file after "day_" where you can input the date. If you want to name your file like the actual date you can do this:

FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%yyyy%-%mm%-%dd%.txt

How do I make WRAP_CONTENT work on a RecyclerView

Here is the c# version for mono android

/* 
* Ported by Jagadeesh Govindaraj (@jaganjan)
 *Copyright 2015 serso aka se.solovyev
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Contact details
 *
 * Email: se.solovyev @gmail.com
 * Site:  http://se.solovyev.org
 */


using Android.Content;
using Android.Graphics;
using Android.Support.V4.View;
using Android.Support.V7.Widget;
using Android.Util;
using Android.Views;
using Java.Lang;
using Java.Lang.Reflect;
using System;
using Math = Java.Lang.Math;

namespace Droid.Helper
{
    public class WrapLayoutManager : LinearLayoutManager
    {
        private const int DefaultChildSize = 100;
        private static readonly Rect TmpRect = new Rect();
        private int _childSize = DefaultChildSize;
        private static bool _canMakeInsetsDirty = true;
        private static readonly int[] ChildDimensions = new int[2];
        private const int ChildHeight = 1;
        private const int ChildWidth = 0;
        private static bool _hasChildSize;
        private static  Field InsetsDirtyField = null;
        private static int _overScrollMode = ViewCompat.OverScrollAlways;
        private static RecyclerView _view;

        public WrapLayoutManager(Context context, int orientation, bool reverseLayout)
            : base(context, orientation, reverseLayout)
        {
            _view = null;
        }

        public WrapLayoutManager(Context context) : base(context)
        {
            _view = null;
        }

        public WrapLayoutManager(RecyclerView view) : base(view.Context)
        {
            _view = view;
            _overScrollMode = ViewCompat.GetOverScrollMode(view);
        }

        public WrapLayoutManager(RecyclerView view, int orientation, bool reverseLayout)
            : base(view.Context, orientation, reverseLayout)
        {
            _view = view;
            _overScrollMode = ViewCompat.GetOverScrollMode(view);
        }

        public void SetOverScrollMode(int overScrollMode)
        {
            if (overScrollMode < ViewCompat.OverScrollAlways || overScrollMode > ViewCompat.OverScrollNever)
                throw new ArgumentException("Unknown overscroll mode: " + overScrollMode);
            if (_view == null) throw new ArgumentNullException(nameof(_view));
            _overScrollMode = overScrollMode;
            ViewCompat.SetOverScrollMode(_view, overScrollMode);
        }

        public static int MakeUnspecifiedSpec()
        {
            return View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
        }

        public override void OnMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec,
            int heightSpec)
        {
            var widthMode = View.MeasureSpec.GetMode(widthSpec);
            var heightMode = View.MeasureSpec.GetMode(heightSpec);

            var widthSize = View.MeasureSpec.GetSize(widthSpec);
            var heightSize = View.MeasureSpec.GetSize(heightSpec);

            var hasWidthSize = widthMode != MeasureSpecMode.Unspecified;
            var hasHeightSize = heightMode != MeasureSpecMode.Unspecified;

            var exactWidth = widthMode == MeasureSpecMode.Exactly;
            var exactHeight = heightMode == MeasureSpecMode.Exactly;

            var unspecified = MakeUnspecifiedSpec();

            if (exactWidth && exactHeight)
            {
                // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
                base.OnMeasure(recycler, state, widthSpec, heightSpec);
                return;
            }

            var vertical = Orientation == Vertical;

            InitChildDimensions(widthSize, heightSize, vertical);

            var width = 0;
            var height = 0;

            // it's possible to get scrap views in recycler which are bound to old (invalid) adapter
            // entities. This happens because their invalidation happens after "onMeasure" method.
            // As a workaround let's clear the recycler now (it should not cause any performance
            // issues while scrolling as "onMeasure" is never called whiles scrolling)
            recycler.Clear();

            var stateItemCount = state.ItemCount;
            var adapterItemCount = ItemCount;
            // adapter always contains actual data while state might contain old data (f.e. data
            // before the animation is done). As we want to measure the view with actual data we
            // must use data from the adapter and not from the state
            for (var i = 0; i < adapterItemCount; i++)
            {
                if (vertical)
                {
                    if (!_hasChildSize)
                    {
                        if (i < stateItemCount)
                        {
                            // we should not exceed state count, otherwise we'll get
                            // IndexOutOfBoundsException. For such items we will use previously
                            // calculated dimensions
                            MeasureChild(recycler, i, widthSize, unspecified, ChildDimensions);
                        }
                        else
                        {
                            LogMeasureWarning(i);
                        }
                    }
                    height += ChildDimensions[ChildHeight];
                    if (i == 0)
                    {
                        width = ChildDimensions[ChildWidth];
                    }
                    if (hasHeightSize && height >= heightSize)
                    {
                        break;
                    }
                }
                else
                {
                    if (!_hasChildSize)
                    {
                        if (i < stateItemCount)
                        {
                            // we should not exceed state count, otherwise we'll get
                            // IndexOutOfBoundsException. For such items we will use previously
                            // calculated dimensions
                            MeasureChild(recycler, i, unspecified, heightSize, ChildDimensions);
                        }
                        else
                        {
                            LogMeasureWarning(i);
                        }
                    }
                    width += ChildDimensions[ChildWidth];
                    if (i == 0)
                    {
                        height = ChildDimensions[ChildHeight];
                    }
                    if (hasWidthSize && width >= widthSize)
                    {
                        break;
                    }
                }
            }

            if (exactWidth)
            {
                width = widthSize;
            }
            else
            {
                width += PaddingLeft + PaddingRight;
                if (hasWidthSize)
                {
                    width = Math.Min(width, widthSize);
                }
            }

            if (exactHeight)
            {
                height = heightSize;
            }
            else
            {
                height += PaddingTop + PaddingBottom;
                if (hasHeightSize)
                {
                    height = Math.Min(height, heightSize);
                }
            }

            SetMeasuredDimension(width, height);

            if (_view == null || _overScrollMode != ViewCompat.OverScrollIfContentScrolls) return;
            var fit = (vertical && (!hasHeightSize || height < heightSize))
                      || (!vertical && (!hasWidthSize || width < widthSize));

            ViewCompat.SetOverScrollMode(_view, fit ? ViewCompat.OverScrollNever : ViewCompat.OverScrollAlways);
        }

        private void LogMeasureWarning(int child)
        {
#if DEBUG
            Log.WriteLine(LogPriority.Warn, "LinearLayoutManager",
                "Can't measure child #" + child + ", previously used dimensions will be reused." +
                "To remove this message either use #SetChildSize() method or don't run RecyclerView animations");
#endif
        }

        private void InitChildDimensions(int width, int height, bool vertical)
        {
            if (ChildDimensions[ChildWidth] != 0 || ChildDimensions[ChildHeight] != 0)
            {
                // already initialized, skipping
                return;
            }
            if (vertical)
            {
                ChildDimensions[ChildWidth] = width;
                ChildDimensions[ChildHeight] = _childSize;
            }
            else
            {
                ChildDimensions[ChildWidth] = _childSize;
                ChildDimensions[ChildHeight] = height;
            }
        }

        public void ClearChildSize()
        {
            _hasChildSize = false;
            SetChildSize(DefaultChildSize);
        }

        public void SetChildSize(int size)
        {
            _hasChildSize = true;
            if (_childSize == size) return;
            _childSize = size;
            RequestLayout();
        }

        private void MeasureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize,
            int[] dimensions)
        {
            View child = null;
            try
            {
                child = recycler.GetViewForPosition(position);
            }
            catch (IndexOutOfRangeException e)
            {
                Log.WriteLine(LogPriority.Warn, "LinearLayoutManager",
                    "LinearLayoutManager doesn't work well with animations. Consider switching them off", e);
            }

            if (child != null)
            {
                var p = child.LayoutParameters.JavaCast<RecyclerView.LayoutParams>()

                var hPadding = PaddingLeft + PaddingRight;
                var vPadding = PaddingTop + PaddingBottom;

                var hMargin = p.LeftMargin + p.RightMargin;
                var vMargin = p.TopMargin + p.BottomMargin;

                // we must make insets dirty in order calculateItemDecorationsForChild to work
                MakeInsetsDirty(p);
                // this method should be called before any getXxxDecorationXxx() methods
                CalculateItemDecorationsForChild(child, TmpRect);

                var hDecoration = GetRightDecorationWidth(child) + GetLeftDecorationWidth(child);
                var vDecoration = GetTopDecorationHeight(child) + GetBottomDecorationHeight(child);

                var childWidthSpec = GetChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.Width,
                    CanScrollHorizontally());
                var childHeightSpec = GetChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.Height,
                    CanScrollVertically());

                child.Measure(childWidthSpec, childHeightSpec);

                dimensions[ChildWidth] = GetDecoratedMeasuredWidth(child) + p.LeftMargin + p.RightMargin;
                dimensions[ChildHeight] = GetDecoratedMeasuredHeight(child) + p.BottomMargin + p.TopMargin;

                // as view is recycled let's not keep old measured values
                MakeInsetsDirty(p);
            }
            recycler.RecycleView(child);
        }

        private static void MakeInsetsDirty(RecyclerView.LayoutParams p)
        {
            if (!_canMakeInsetsDirty)
            {
                return;
            }
            try
            {
                if (InsetsDirtyField == null)
                {
                   var klass = Java.Lang.Class.FromType (typeof (RecyclerView.LayoutParams));
                    InsetsDirtyField = klass.GetDeclaredField("mInsetsDirty");
                    InsetsDirtyField.Accessible = true;
                }
                InsetsDirtyField.Set(p, true);
            }
            catch (NoSuchFieldException e)
            {
                OnMakeInsertDirtyFailed();
            }
            catch (IllegalAccessException e)
            {
                OnMakeInsertDirtyFailed();
            }
        }

        private static void OnMakeInsertDirtyFailed()
        {
            _canMakeInsetsDirty = false;
#if DEBUG
            Log.Warn("LinearLayoutManager",
                "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
#endif
        }
    }
}

Google Maps API v2: How to make markers clickable?

Avoid using Activity implements OnMarkerClickListener, use a local OnMarkerClickListener

// Not a good idea
class MapActivity extends Activity implements OnMarkerClickListener {
}

You will need a map to lookup the original data model linked to the marker

private Map<Marker, Map<String, Object>> markers = new HashMap<>();

You will need a data model

private Map<String, Object> dataModel = new HashMap<>();

Put some data in the data model

dataModel.put("title", "My Spot");
dataModel.put("snipet", "This is my spot!");
dataModel.put("latitude", 20.0f);
dataModel.put("longitude", 100.0f);

When creating a new marker using a data model add both to the maker map

Marker marker = googleMap.addMarker(markerOptions);
markers.put(marker, dataModel);

For on click marker event, use a local OnMarkerClickListener:

@Override
public void onMapReady(GoogleMap googleMap) {
    // grab for laters
    this.googleMap = googleMap;

    googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Map dataModel = (Map)markers.get(marker);
            String title = (String)dataModel.get("title");
            markerOnClick(title);

            return false;
        }
    });

    mapView.onResume();

    showMarkers();

    ZoomAsync zoomAsync = new ZoomAsync();
    zoomAsync.execute();
}

For displaying the info window retrieve the original data model from the marker map:

@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            Map dataModel = (Map)markers.get(marker);
            String title = (String)dataModel.get("title");

            infoWindowOnClick(title);
        }
    });

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I had this problem when I was trying to use the range.AddComment() function. I was able to solve this by calling range.ClearComment() before adding the comment.

How to clear/remove observable bindings in Knockout.js?

You could try using the with binding that knockout offers: http://knockoutjs.com/documentation/with-binding.html The idea is to use apply bindings once, and whenever your data changes, just update your model.

Lets say you have a top level view model storeViewModel, your cart represented by cartViewModel, and a list of items in that cart - say cartItemsViewModel.

You would bind the top level model - the storeViewModel to the whole page. Then, you could separate the parts of your page that are responsible for cart or cart items.

Lets assume that the cartItemsViewModel has the following structure:

var actualCartItemsModel = { CartItems: [
  { ItemName: "FirstItem", Price: 12 }, 
  { ItemName: "SecondItem", Price: 10 }
] }

The cartItemsViewModel can be empty at the beginning.

The steps would look like this:

  1. Define bindings in html. Separate the cartItemsViewModel binding.

      
        <div data-bind="with: cartItemsViewModel">
          <div data-bind="foreach: CartItems">
            <span data-bind="text: ItemName"></span>
            <span data-bind="text: Price"></span>
          </div>
        </div>
      
    
  2. The store model comes from your server (or is created in any other way).

    var storeViewModel = ko.mapping.fromJS(modelFromServer)

  3. Define empty models on your top level view model. Then a structure of that model can be updated with actual data.

      
        storeViewModel.cartItemsViewModel = ko.observable();
        storeViewModel.cartViewModel = ko.observable();
     
    
  4. Bind the top level view model.

    ko.applyBindings(storeViewModel);

  5. When the cartItemsViewModel object is available then assign it to the previously defined placeholder.

    storeViewModel.cartItemsViewModel(actualCartItemsModel);

If you would like to clear the cart items: storeViewModel.cartItemsViewModel(null);

Knockout will take care of html - i.e. it will appear when model is not empty and the contents of div (the one with the "with binding") will disappear.

Using Mysql in the command line in osx - command not found?

You have to create a symlink to your mysql installation if it is not the most recent version of mysql.

$ brew link --force [email protected]

see this post by Alex Todd

What does %s and %d mean in printf in the C language?

%s is for string %d is for decimal (or int) %c is for character

It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.

The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.

Git push won't do anything (everything up-to-date)

For my case, none of other solutions worked. I had to do a backup of new modified files (shown with git status), and run a git reset --hard. This allowed me to realign with the remote server. Adding new modified files, and running

git add .
git commit -am "my comment"
git push

Did the trick. I hope this helps someone, as a "last chance" solution.

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

How to completely remove node.js from Windows

The best thing to do is to remove Node.js from the control panel. Once deleted download the desired version of Node.js and install it and it works.

How do I check what version of Python is running my script?

The even simpler simplest way:

In Spyder, start a new "IPython Console", then run any of your existing scripts.

Now the version can be seen in the first output printed in the console window:

"Python 3.7.3 (default, Apr 24 2019, 15:29:51)..."

enter image description here

How to iterate over a std::map full of strings in C++

Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.

How to use jQuery with Angular?

The most effective way that I have found is to use setTimeout with time of 0 inside of the page/component constructor. This let's the jQuery run in the next execution cycle after Angular has finished loading all the child components. A few other component methods could be used but all I have tried work best when run inside a setTimeout.

export class HomePage {
    constructor() {
        setTimeout(() => {
            // run jQuery stuff here
        }, 0);
    }
}

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

getting the ng-object selected with ng-change

This might give you some ideas

.NET C# View Model

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

before the position where repetitive objects begin , you should close the session and then you should start a new session

session.close();      
session = HibernateUtil.getSessionFactory().openSession();

so in this way in one session there is not more than one entities that have the same identifier.

How to calculate the bounding box for a given lat/lng location?

I was working on the bounding box problem as a side issue to finding all the points within SrcRad radius of a static LAT, LONG point. There have been quite a few calculations that use

maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));

to calculate the longitude bounds, but I found this to not give all the answers that were needed. Because what you really want to do is

(SrcRad/RadEarth)/cos(deg2rad(lat))

I know, I know the answer should be the same, but I found that it wasn't. It appeared that by not making sure I was doing the (SRCrad/RadEarth) First and then dividing by the Cos part I was leaving out some location points.

After you get all your bounding box points, if you have a function that calculates the Point to Point Distance given lat, long it is easy to only get those points that are a certain distance radius from the fixed point. Here is what I did. I know it took a few extra steps but it helped me

-- GLOBAL Constants
gc_pi CONSTANT REAL := 3.14159265359;  -- Pi

-- Conversion Factor Constants
gc_rad_to_degs          CONSTANT NUMBER := 180/gc_pi; -- Conversion for Radians to Degrees 180/pi
gc_deg_to_rads          CONSTANT NUMBER := gc_pi/180; --Conversion of Degrees to Radians

lv_stat_lat    -- The static latitude point that I am searching from 
lv_stat_long   -- The static longitude point that I am searching from 

-- Angular radius ratio in radians
lv_ang_radius := lv_search_radius / lv_earth_radius;
lv_bb_maxlat := lv_stat_lat + (gc_rad_to_deg * lv_ang_radius);
lv_bb_minlat := lv_stat_lat - (gc_rad_to_deg * lv_ang_radius);

--Here's the tricky part, accounting for the Longitude getting smaller as we move up the latitiude scale
-- I seperated the parts of the equation to make it easier to debug and understand
-- I may not be a smart man but I know what the right answer is... :-)

lv_int_calc := gc_deg_to_rads * lv_stat_lat;
lv_int_calc := COS(lv_int_calc);
lv_int_calc := lv_ang_radius/lv_int_calc;
lv_int_calc := gc_rad_to_degs*lv_int_calc;

lv_bb_maxlong := lv_stat_long + lv_int_calc;
lv_bb_minlong := lv_stat_long - lv_int_calc;

-- Now select the values from your location datatable 
SELECT *  FROM (
SELECT cityaliasname, city, state, zipcode, latitude, longitude, 
-- The actual distance in miles
spherecos_pnttopntdist(lv_stat_lat, lv_stat_long, latitude, longitude, 'M') as miles_dist    
FROM Location_Table 
WHERE latitude between lv_bb_minlat AND lv_bb_maxlat
AND   longitude between lv_bb_minlong and lv_bb_maxlong)
WHERE miles_dist <= lv_limit_distance_miles
order by miles_dist
;

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

How to solve a pair of nonlinear equations using Python?

Short answer: use fsolve

As mentioned in other answers the simplest solution to the particular problem you have posed is to use something like fsolve:

from scipy.optimize import fsolve
from math import exp

def equations(vars):
    x, y = vars
    eq1 = x+y**2-4
    eq2 = exp(x) + x*y - 3
    return [eq1, eq2]

x, y =  fsolve(equations, (1, 1))

print(x, y)

Output:

0.6203445234801195 1.8383839306750887

Analytic solutions?

You say how to "solve" but there are different kinds of solution. Since you mention SymPy I should point out the biggest difference between what this could mean which is between analytic and numeric solutions. The particular example you have given is one that does not have an (easy) analytic solution but other systems of nonlinear equations do. When there are readily available analytic solutions SymPY can often find them for you:

from sympy import *

x, y = symbols('x, y')
eq1 = Eq(x+y**2, 4)
eq2 = Eq(x**2 + y, 4)

sol = solve([eq1, eq2], [x, y])

Output:

?? ?  5   v17? ?3   v17?    v17   1?  ? ?  5   v17? ?3   v17?    1   v17?  ? ?  3   v13? ?v13   5?  1   v13?  ? ?5   v13? ?  v13   3?  1   v13??
??-?- - - ---?·?- - ---?, - --- - -?, ?-?- - + ---?·?- + ---?, - - + ---?, ?-?- - + ---?·?--- + -?, - + ---?, ?-?- - ---?·?- --- - -?, - - ---??
?? ?  2    2 ? ?2    2 ?     2    2?  ? ?  2    2 ? ?2    2 ?    2    2 ?  ? ?  2    2 ? ? 2    2?  2    2 ?  ? ?2    2 ? ?   2    2?  2    2 ??

Note that in this example SymPy finds all solutions and does not need to be given an initial estimate.

You can evaluate these solutions numerically with evalf:

soln = [tuple(v.evalf() for v in s) for s in sol]
[(-2.56155281280883, -2.56155281280883), (1.56155281280883, 1.56155281280883), (-1.30277563773199, 2.30277563773199), (2.30277563773199, -1.30277563773199)]

Precision of numeric solutions

However most systems of nonlinear equations will not have a suitable analytic solution so using SymPy as above is great when it works but not generally applicable. That is why we end up looking for numeric solutions even though with numeric solutions: 1) We have no guarantee that we have found all solutions or the "right" solution when there are many. 2) We have to provide an initial guess which isn't always easy.

Having accepted that we want numeric solutions something like fsolve will normally do all you need. For this kind of problem SymPy will probably be much slower but it can offer something else which is finding the (numeric) solutions more precisely:

from sympy import *

x, y = symbols('x, y')
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1])
?0.620344523485226?
?                 ?
?1.83838393066159 ?

With greater precision:

nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1], prec=50)
?0.62034452348522585617392716579154399314071550594401?
?                                                    ?
? 1.838383930661594459049793153371142549403114879699 ?

Check file uploaded is in csv format

So I ran into this today.

Was attempting to validate an uploaded CSV file's MIME type by looking at $_FILES['upload_file']['type'], but for certain users on various browsers (and not necessarily the same browsers between said users; for instance it worked fine for me in FF but for another user it didn't work on FF) the $_FILES['upload_file']['type'] was coming up as "application/vnd.ms-excel" instead of the expected "text/csv" or "text/plain".

So I resorted to using the (IMHO) much more reliable finfo_* functions something like this:

$acceptable_mime_types = array('text/plain', 'text/csv', 'text/comma-separated-values');

if (!empty($_FILES) && array_key_exists('upload_file', $_FILES) && $_FILES['upload_file']['error'] == UPLOAD_ERR_OK) {
    $tmpf = $_FILES['upload_file']['tmp_name'];

    // Make sure $tmpf is kosher, then:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $tmpf);

    if (!in_array($mime_type, $acceptable_mime_types)) {
        // Unacceptable mime type.
    }
}

C# removing items from listbox

With this code you can remove every item from your listbox ... Notice that you should write this code in the click event of your button :

        if (listBox1.SelectedIndex != -1)
        {
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        } 

What issues should be considered when overriding equals and hashCode in Java?

There are a couple of ways to do your check for class equality before checking member equality, and I think both are useful in the right circumstances.

  1. Use the instanceof operator.
  2. Use this.getClass().equals(that.getClass()).

I use #1 in a final equals implementation, or when implementing an interface that prescribes an algorithm for equals (like the java.util collection interfaces—the right way to check with with (obj instanceof Set) or whatever interface you're implementing). It's generally a bad choice when equals can be overridden because that breaks the symmetry property.

Option #2 allows the class to be safely extended without overriding equals or breaking symmetry.

If your class is also Comparable, the equals and compareTo methods should be consistent too. Here's a template for the equals method in a Comparable class:

final class MyClass implements Comparable<MyClass>
{

  …

  @Override
  public boolean equals(Object obj)
  {
    /* If compareTo and equals aren't final, we should check with getClass instead. */
    if (!(obj instanceof MyClass)) 
      return false;
    return compareTo((MyClass) obj) == 0;
  }

}

Is there an auto increment in sqlite?

Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.

The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.

Read here for detailed information.

How to Automatically Close Alerts using Twitter Bootstrap

This is the coffescript version:

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000

How to add text to JFrame?

Instead of wasting your time to design a JFrame just to display a error message, you can use an JOptionPane which is by default modal:

import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Your message goes here!","Message", JOptionPane.ERROR_MESSAGE);
    }
}

enter image description here

P.S. Stop using Windowbuilder if you want to learn Swing.

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

Printing Lists as Tabular Data

I know that I am late to the party, but I just made a library for this that I think could really help. It is extremely simple, that's why I think you should use it. It is called TableIT.

Basic Use

To use it, first follow the download instructions on the GitHub Page.

Then import it:

import TableIt

Then make a list of lists where each inner list is a row:

table = [
    [4, 3, "Hi"],
    [2, 1, 808890312093],
    [5, "Hi", "Bye"]
]

Then all you have to do is print it:

TableIt.printTable(table)

This is the output you get:

+--------------------------------------------+
| 4            | 3            | Hi           |
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

Field Names

You can use field names if you want to (if you aren't using field names you don't have to say useFieldNames=False because it is set to that by default):


TableIt.printTable(table, useFieldNames=True)

From that you will get:

+--------------------------------------------+
| 4            | 3            | Hi           |
+--------------+--------------+--------------+
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

There are other uses to, for example you could do this:

import TableIt

myList = [
    ["Name", "Email"],
    ["Richard", "[email protected]"],
    ["Tasha", "[email protected]"]
]

TableIt.print(myList, useFieldNames=True)

From that:

+-----------------------------------------------+
| Name                  | Email                 |
+-----------------------+-----------------------+
| Richard               | [email protected] |
| Tasha                 | [email protected]    |
+-----------------------------------------------+

Or you could do:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True)

And from that you get:

+-----------------------+
|       | a     | b     |
+-------+-------+-------+
| x     | a + x | a + b |
| z     | a + z | z + b |
+-----------------------+

Colors

You can also use colors.

You use colors by using the color option (by default it is set to None) and specifying RGB values.

Using the example from above:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True, color=(26, 156, 171))

Then you will get:

enter image description here

Please note that printing colors might not work for you but it does works the exact same as the other libraries that print colored text. I have tested and every single color works. The blue is not messed up either as it would if using the default 34m ANSI escape sequence (if you don't know what that is it doesn't matter). Anyway, it all comes from the fact that every color is RGB value rather than a system default.

More Info

For more info check the GitHub Page

HTTP Basic Authentication - what's the expected web browser experience?

You can use Postman a plugin for chrome. It gives the ability to choose the authentication type you need for each of the requests. In that menu you can configure user and password. Postman will automatically translate the config to a authentication header that will be sent with your request.

What is difference between monolithic and micro kernel?

Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site. For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here

How to remove the URL from the printing page?

Nowadays, you can use history API to modify the URL before print, then change back:

var curURL = window.location.href;
history.replaceState(history.state, '', '/');
window.print();
history.replaceState(history.state, '', curURL);

But you need to make a custom PRINT button for user to click.

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

MemoryStream - Cannot access a closed Stream

when it gets out from the using statement the Dispose method will be called automatically closing the stream

try the below:

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

How to find out what is locking my tables?

I have a stored procedure that I have put together, that deals not only with locks and blocking, but also to see what is running in a server. I have put it in master. I will share it with you, the code is below:

USE [master]
go


CREATE PROCEDURE [dbo].[sp_radhe] 

AS
BEGIN

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


-- the current_processes
-- marcelo miorelli 
-- CCHQ 
-- 04 MAR 2013 Wednesday

SELECT es.session_id AS session_id
,COALESCE(es.original_login_name, '') AS login_name
,COALESCE(es.host_name,'') AS hostname
,COALESCE(es.last_request_end_time,es.last_request_start_time) AS last_batch
,es.status
,COALESCE(er.blocking_session_id,0) AS blocked_by
,COALESCE(er.wait_type,'MISCELLANEOUS') AS waittype
,COALESCE(er.wait_time,0) AS waittime
,COALESCE(er.last_wait_type,'MISCELLANEOUS') AS lastwaittype
,COALESCE(er.wait_resource,'') AS waitresource
,coalesce(db_name(er.database_id),'No Info') as dbid
,COALESCE(er.command,'AWAITING COMMAND') AS cmd
,sql_text=st.text
,transaction_isolation =
CASE es.transaction_isolation_level
    WHEN 0 THEN 'Unspecified'
    WHEN 1 THEN 'Read Uncommitted'
    WHEN 2 THEN 'Read Committed'
    WHEN 3 THEN 'Repeatable'
    WHEN 4 THEN 'Serializable'
    WHEN 5 THEN 'Snapshot'
END
,COALESCE(es.cpu_time,0) 
    + COALESCE(er.cpu_time,0) AS cpu
,COALESCE(es.reads,0) 
    + COALESCE(es.writes,0) 
    + COALESCE(er.reads,0) 
+ COALESCE(er.writes,0) AS physical_io
,COALESCE(er.open_transaction_count,-1) AS open_tran
,COALESCE(es.program_name,'') AS program_name
,es.login_time
FROM sys.dm_exec_sessions es
LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
LEFT OUTER JOIN sys.server_principals sp ON es.security_id = sp.sid
LEFT OUTER JOIN sys.dm_os_tasks ota ON es.session_id = ota.session_id
LEFT OUTER JOIN sys.dm_os_threads oth ON ota.worker_address = oth.worker_address
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS st
where es.is_user_process = 1 
  and es.session_id <> @@spid
  and es.status = 'running'
ORDER BY es.session_id

end 

GO

this procedure has done very good for me in the last couple of years. to run it just type sp_radhe

Regarding putting sp_radhe in the master database

I use the following code and make it a system stored procedure

exec sys.sp_MS_marksystemobject 'sp_radhe'

as you can see on the link below

Creating Your Own SQL Server System Stored Procedures

Regarding the transaction isolation level

Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask

Jonathan Kehayias

Once you change the transaction isolation level it only changes when the scope exits at the end of the procedure or a return call, or if you change it explicitly again using SET TRANSACTION ISOLATION LEVEL.

In addition the TRANSACTION ISOLATION LEVEL is only scoped to the stored procedure, so you can have multiple nested stored procedures that execute at their own specific isolation levels.

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Calling Scalar-valued Functions in SQL

That syntax works fine for me:

CREATE FUNCTION dbo.test_func
(@in varchar(20))
RETURNS INT
AS
BEGIN
    RETURN 1
END
GO

SELECT dbo.test_func('blah')

Are you sure that the function exists as a function and under the dbo schema?

How do I go about adding an image into a java project with eclipse?

It is very simple to adding an image into project and view the image. First create a folder into in your project which can contain any type of images.

Then Right click on Project ->>Go to Build Path ->> configure Build Path ->> add Class folder ->> choose your folder (which you just created for store the images) under the project name.

class Surface extends JPanel {

    private BufferedImage slate;
    private BufferedImage java;
    private BufferedImage pane;
    private TexturePaint slatetp;
    private TexturePaint javatp;
    private TexturePaint panetp;

    public Surface() {

        loadImages();
    }

    private void loadImages() {

        try {

            slate = ImageIO.read(new File("images\\slate.png"));
            java = ImageIO.read(new File("images\\java.png"));
            pane = ImageIO.read(new File("images\\pane.png"));

        } catch (IOException ex) {

            Logger.`enter code here`getLogger(Surface.class.getName()).log(
                    Level.SEVERE, null, ex);
        }
    }

    private void doDrawing(Graphics g) {

        Graphics2D g2d = (Graphics2D) g.create();

        slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
        javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
        panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));

        g2d.setPaint(slatetp);
        g2d.fillRect(10, 15, 90, 60);

        g2d.setPaint(javatp);
        g2d.fillRect(130, 15, 90, 60);

        g2d.setPaint(panetp);
        g2d.fillRect(250, 15, 90, 60);

        g2d.dispose();
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        doDrawing(g);
    }
}

public class TexturesEx extends JFrame {

    public TexturesEx() {

        initUI();
    }

    private void initUI() {

        add(new Surface());

        setTitle("Textures");
        setSize(360, 120);
        setLocationRelativeTo(null);        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TexturesEx ex = new TexturesEx();
                ex.setVisible(true);
            }
        });
    }
}

How to use underscore.js as a template engine?

Everything you need to know about underscore template is here. Only 3 things to keep in mind:

  1. <% %> - to execute some code
  2. <%= %> - to print some value in template
  3. <%- %> - to print some values HTML escaped

That's all about it.

Simple example:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

then tpl({foo: "blahblah"}) would be rendered to the string <h1>Some text: blahblah</h1>

Alternative to Intersect in MySQL

AFAIR, MySQL implements INTERSECT through INNER JOIN.

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

How to get item count from DynamoDB?

len(response['Items'])

will give you the count of the filtered rows

where,

fe = Key('entity').eq('tesla')
response = table.scan(FilterExpression=fe)

How to iterate object in JavaScript?

for(index in dictionary) {
 for(var index in dictionary[]){
    // do something
  }
}

Mvn install or Mvn package

package - takes the compiled code and package it in its distributable format, such as a JAR or WAR file. install - install the package into the local repository, for use as a dependency in other projects locally

The import com.google.android.gms cannot be resolved

Another way is to let Eclipse do the import work for you. Hover your mouse over the com.google.android.gms import that can not be resolved and towards the bottom of the popup menu, select the Fix project setup... option as below. Then it'll prompt to import the google play services library. Select that and you should be good to go.

enter image description here

iterating quickly through list of tuples

Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value

EDIT: To create a reverse mapping, use something like:

revDct = dict((val, key) for (key, val) in tuples)

Checking if a website is up via Python

In my opinion, caisah's answer misses an important part of your question, namely dealing with the server being offline.

Still, using requests is my favorite option, albeit as such:

import requests

try:
    requests.get(url)
except requests.exceptions.ConnectionError:
    print(f"URL {url} not reachable")

Why use HttpClient for Synchronous Connection

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

I can't understand why this JAXB IllegalAnnotationException is thrown

I once received this message after thinking that putting @XmlTransient on a field I didn't need to serialize, in a class that was annotated with @XmlAccessorType(XmlAccessType.NONE).

In that case, removing XmlTransient resolved the issue. I am not a JAXB expert, but I suspect that because AccessType.NONE indicates that no auto-serialization should be done (i.e. fields must be specifically annotated to serialize them) that makes XmlTransient illegal since its sole purpose is to exclude a field from auto-serialization.

How to keep one variable constant with other one changing with row in excel

There are two kinds of cell reference, and it's really valuable to understand them well.

One is relative reference, which is what you get when you just type the cell: A5. This reference will be adjusted when you paste or fill the formula into other cells.

The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5. This cell reference will not change when pasted or filled.

A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5 and A$5. This comes in handy for producing things like multiplication tables from a single formula.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

Forbidden :You don't have permission to access /phpmyadmin on this server

You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.

Javascript add method to object

There are many ways to create re-usable objects like this in JavaScript. Mozilla have a nice introduction here:

The following will work in your example:

function Foo(){
    this.bar = function (){
        alert("Hello World!");
    }
}

myFoo = new Foo();
myFoo.bar(); // Hello World?????????????????????????????????

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

In my case I am using:

  • SQLite,

  • prepared statements with placeholders to handle unknown number of fields,

  • AJAX request sent by user where everything is a string and there is no such thing like NULL value and

  • I desperately need to insert NULLs as that does not violates foreign key constrains (acceptable value).

Suppose, now user sends with post: $_POST[field1] with value value1 which can be the empty string "" or "null" or "NULL".

First I make the statement:

$stmt = $this->dbh->prepare("INSERT INTO $table ({$sColumns}) VALUES ({$sValues})");

where {$sColumns} is sth like field1, field2, ... and {$sValues} are my placeholders ?, ?, ....

Then, I collect my $_POST data related with the column names in an array $values and replace with NULLs:

  for($i = 0; $i < \count($values); $i++)
     if((\strtolower($values[$i]) == 'null') || ($values[$i] == ''))
        $values[$i] = null;

Now, I can execute:

$stmt->execute($values);

and among other bypass foreign key constrains.

If on the other hand, an empty string does makes more sense then you have to check if that field is part of a foreign key or not (more complicated).

jQuery Set Cursor Position in Text Area

Small modification to the code I found in bitbucket

Code is now able to select/highlight with start/end points if given 2 positions. Tested and works fine in FF/Chrome/IE9/Opera.

$('#field').caret(1, 9);

The code is listed below, only a few lines changed:

(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
    if (arguments.length == 0) { //get
      if (target.selectionStart) { //DOM
        var pos = target.selectionStart;
        return pos > 0 ? pos : 0;
      }
      else if (target.createTextRange) { //IE
        target.focus();
        var range = document.selection.createRange();
        if (range == null)
            return '0';
        var re = target.createTextRange();
        var rc = re.duplicate();
        re.moveToBookmark(range.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
      }
      else return 0;
    }

    //set
    var pos_start = pos;
    var pos_end = pos;

    if (arguments.length > 1) {
        pos_end = arguments[1];
    }

    if (target.setSelectionRange) //DOM
      target.setSelectionRange(pos_start, pos_end);
    else if (target.createTextRange) { //IE
      var range = target.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos_end);
      range.moveStart('character', pos_start);
      range.select();
    }
  }
})(jQuery)

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

How to make shadow on border-bottom?

funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:

<h3>Your Text</h3><div class="border-shadow"></div>

and the css:

    .shadow {
        width:100%;
        height:1px; // = "border height (without the shadow)!"
        background:#000; // = "border color!"
        -webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        -moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"

}

Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Sometimes, such a question can be asked at an interview.

For example, when you write:

int a = 2;
long b = 3;
a = a + b;

there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.

So to avoid it, you must write your code like this:

int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting

JSON to string variable dump

You can use console.log() in Firebug or Chrome to get a good object view here, like this:

$.getJSON('my.json', function(data) {
  console.log(data);
});

If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).

If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/

Select2 doesn't work when embedded in a bootstrap modal

to use bootstrap 4.0 with server-side(ajax or json data inline), you need to add all of this:

$.fn.modal.Constructor.prototype._enforceFocus = function() {};

and then when modal is open, create the select2:

  // when modal is open
  $('.modal').on('shown.bs.modal', function () {
            $('select').select2({
                  // ....
            });
  });

How do I fix the indentation of an entire file in Vi?

In Vim, use :insert. This will keep all your formatting and not do autoindenting. For more information help :insert.

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

grep exclude multiple strings

The greps can be chained. For example:

tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Splitting String with delimiter

dependencies {
   compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
     ['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
       def (g, m) = i.tokenize( ':' )
       dep.exclude group: g  , module: m
     }
   }
}

How to use a decimal range() step value?

frange(start, stop, precision)

def frange(a,b,i):
    p = 10**i
    sr = a*p
    er = (b*p) + 1
    p = float(p)
    return map(lambda x: x/p, xrange(sr,er))

In >frange(-1,1,1)

Out>[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

Most efficient way to get table row count

None of these answers seem to be quite right. I tried them all. Here are my results.

Sending query: SELECT count(*) FROM daximation
91
Sending query: SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'
96
Sending query: SHOW TABLE STATUS LIKE 'daximation'
98
Sending query: SELECT id FROM daximation ORDER BY id DESC LIMIT 1
97

here's the screenshot: https://www.screencast.com/t/s8c3trYU

Here is my PHP code:

$query = "SELECT count(*) FROM daximation"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SHOW TABLE STATUS LIKE 'daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[10]);

$query = "SELECT id FROM daximation ORDER BY id DESC LIMIT 1"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

What is the best way to redirect a page using React Router?

Actually it depends on your use case.

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

Keep in mind that if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history:

myFunction() {
  addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

or

myFunction() {
  addSomeStuff()
  this.props.history.push('/path')
}

In order to have access to history, you can wrap your component with an HOC called withRouter. When you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation for withRouter.

If your component is a child of a <Route /> component, i.e. if it is something like <Route path='/path' component={myComponent} />, you don't have to wrap your component with withRouter, because <Route /> passes match, location, and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to an onClick event:

<div onClick={this.props.history.push('/path')}> some stuff </div>

or you can use a <Link /> component:

 <Link to='/path' > some stuff </Link>

I think the rule of thumb with this case is to try to use <Link /> first, I suppose especially because of performance.

How do I remove an object from an array with JavaScript?

Use the splice method.

(At least I assume that is the answer, you say you have an object, but the code you give just creates two variables, and there is no sign of how the Array is created)

How to establish ssh key pair when "Host key verification failed"

Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.

$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts

Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.

#!/bin/bash
#Jason Xiong: Dec 2013   
# The ip or ipalias stored in known_hosts file is hashed and   
# is not human readable.This script check if the supplied ip    
# or ipalias exists in ~/.ssh/known_hosts file

if [[ $# != 2 ]]; then
   echo "Usage: ./search_known_hosts -i ip_or_ipalias"
   exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;

cat $known_host_file | while read -r line;do
  if [[ -z "$line" ]]; then
    continue;
  fi   
  hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}'); 
  key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
  stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}'); 
  hex_key=$(echo $key | base64 -d | xxd -p); 
  if  [[ $hash_type = 1 ]]; then      
     gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
         -macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);     
     if [[ $gen_value = $stored_value ]]; then
       echo $gen_value;
       echo "Found match in known_hosts file : entry#"$entry" !!!!"
     fi
  else
     echo "unknown hash_type"
  fi
  entry=$((entry + 1));
done

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.

UIBarButtonItem in navigation bar programmatically?

This is a crazy thing of apple. When you say self.navigationItem.rightBarButtonItem.title then it will say nil while on the GUI it shows Edit or Save. Fresher likes me will take a lot of time to debug this behavior.

There is a requirement that the Item will show Edit in the firt load then user taps on it It will change to Save title. To archive this, i did as below.

//view did load will say Edit title

private func loadRightBarItem() {
    let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
}

// tap Edit item will change to Save title

@objc private func handleEditBtn() {
    print("clicked on Edit btn")
    let logoutBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(handleSaveBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
    blockEditTable(isBlock: false)
}

//tap Save item will display Edit title

@objc private func handleSaveBtn(){
    print("clicked on Save btn")
    let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem

    saveInvitation()
    blockEditTable(isBlock: true)

}

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

The following technique worked for me:

1) Right click on the project Solution -> Click on Clean solution

2) Right click on the project Solution -> Click on Rebuild solution

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

XML Parsing - Read a Simple XML File and Retrieve Values

I usually use XmlDocument for this. The interface is pretty straight forward:

var doc = new XmlDocument();
doc.LoadXml(xmlString);

You can access nodes similar to a dictionary:

var tasks = doc["Tasks"];

and loop over all children of a node.

Redirect after Login on WordPress

The accepted answer is very wrong. One should never be modifying the WordPress Core. Not only will edits be lost at a given update, some changes you make on a whim may compromise other functionality or even endanger the security of your site.

Action Hooks & Filters are included within the core to allow modifying functionality without modifying code.

An example of using the login_redirect filter to redirect certain users can be found here and is a much more robust solution to your problem.

For your specific problem, you want to do this:

function login_redirect( $redirect_to, $request, $user ){
    return home_url('news.php');
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

Don't reload application when orientation changes

As Pacerier mentioned,

android:configChanges="orientation|screenSize"

Plain Old CLR Object vs Data Transfer Object

I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).

One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.

Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.

How to execute a Ruby script in Terminal?

For those not getting a solution for older answers, i simply put my file name as the very first line in my code.

like so

 #ruby_file_name_here.rb

 puts "hello world"

Check div is hidden using jquery

You can check the CSS display property:

if ($('#car').css('display') == 'none') {
    alert('Car 2 is hidden');
}

Here is a demo: http://jsfiddle.net/YjP4K/

ASP.NET MVC on IIS 7.5

If you're running IIS 8.5 on Windows 8, or Server 2012, you might find that running mvc 4/5 (.net 4.5) doesn't work in a virtual directory. If you create a local host entry in the host file to point back to your local machine and then point a new local IIS website to that folder (with the matching host header entry) you'll find it works then.

"End of script output before headers" error in Apache

Internal error is due to a HIDDEN character at end of shebang line !! ie line #!/usr/bin/perl

By adding - or -w at end moves the character away from "perl" allowing the path to the perl processor to be found and script to execute.

HIDDEN character is created by the editor used to create the script

Angular 2 declaring an array of objects

Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{
        private id:number;
        private text: string;
    
        constructor(id,text) {
            this.id = id;
            this.text = text;
        }
    
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {
        private search_key: string;
        private dataList: Data[] = [];
    
        getWikiData() {
           this.httpService.getDataFromAPI()
            .subscribe(data => {
              this.parseData(data);
            });
         }
    
        parseData(jsonData: string) {
        //considering you get your data in json arrays
        for (let i = 0; i < jsonData[1].length; i++) {
             const data = new WikiData(jsonData[1][i], jsonData[2][i]);
             this.wikiData.push(data);
        }
      }
    }
    

How to create websockets server in PHP

I was in the same boat as you recently, and here is what I did:

  1. I used the phpwebsockets code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.)

  2. I used PHP.net to read the details about every socket function used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle.

  3. I read the actual WebSocket draft. I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API.

  4. I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad.

  5. I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (original link broken) Archived copy.

    Please note that the code available at this link has a number of problems and won't work properly without further modification.

  6. I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: How can I send and receive WebSocket messages on the server side?

    This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying.

  7. I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: What is this data at the end of WebRTC candidate info?

  8. At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done.

That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script.

Good luck!


Edit: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution:
https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php


Edit #2: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like Heroku to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

Check the version of Gradle install in Android Studio and the one mentioned in Build.Grable file

`dependencies { classpath 'com.android.tools.build:gradle:3.1.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}`

I replace 3.1.1 to 3.0.0 and it worked for me, check your own version of Gradle. Or try to create new project and check its build.gradle file to know the installed version.

Extract a substring according to a pattern

The unglue package provides an alternative, no knowledge about regular expressions is required for simple cases, here we'd do :

# install.packages("unglue")
library(unglue)
string = c("G1:E001", "G2:E002", "G3:E003")
unglue_vec(string,"{x}:{y}", var = "y")
#> [1] "E001" "E002" "E003"

Created on 2019-11-06 by the reprex package (v0.3.0)

More info : https://github.com/moodymudskipper/unglue/blob/master/README.md

Best /Fastest way to read an Excel Sheet into a DataTable?

Use the below snippet it will be helpfull.

string POCpath = @"G:\Althaf\abc.xlsx";

string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);

Making a PowerShell POST request if a body param starts with '@'

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{
    "@type" = "login"
    "username" = "[email protected]"
    "password" = "yyy"
} | ConvertTo-Json

Calculate business days

Get the number of working days without holidays between two dates :

Use example:

echo number_of_working_days('2013-12-23', '2013-12-29');

Output:

3

Function:

function number_of_working_days($from, $to) {
    $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)
    $holidayDays = ['*-12-25', '*-01-01', '2013-12-23']; # variable and fixed holidays

    $from = new DateTime($from);
    $to = new DateTime($to);
    $to->modify('+1 day');
    $interval = new DateInterval('P1D');
    $periods = new DatePeriod($from, $interval, $to);

    $days = 0;
    foreach ($periods as $period) {
        if (!in_array($period->format('N'), $workingDays)) continue;
        if (in_array($period->format('Y-m-d'), $holidayDays)) continue;
        if (in_array($period->format('*-m-d'), $holidayDays)) continue;
        $days++;
    }
    return $days;
}

Two column div layout with fluid left and fixed right column

Here's a solution (and it has some quirks, but let me know if you notice them and that they're a concern):

<div>
    <div style="width:200px;float:left;display:inline-block;">
        Hello world
    </div>
    <div style="margin-left:200px;">
        Hello world
    </div>
</div>

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.

[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]

How to select the first element of a set with JSTL?

Using ${mySet.toArray[0]} does not work.

I do not think it is possible without having forEach loop at least one iteration.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I used this one for list view loading may helpful.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >

<LinearLayout
    android:id="@+id/progressbar_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Loading data..." />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#C0C0C0" />
</LinearLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="1dip"
    android:visibility="gone" />

</RelativeLayout>

and my MainActivity class is,

public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    layout = (LinearLayout) findViewById(R.id.progressbar_view);

    stringValues = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, stringValues);

    listView.setAdapter(adapter);
    new Task().execute();
}

class Task extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
        layout.setVisibility(View.VISIBLE);
        listView.setVisibility(View.GONE);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        layout.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        stringValues.add("String 1");
        stringValues.add("String 2");
        stringValues.add("String 3");
        stringValues.add("String 4");
        stringValues.add("String 5");

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

this activity display progress for 3sec then it will display listview, instead of adding data statically to stringValues list you can get data from server in doInBackground() and display it.

NSString property: copy or retain?

Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:

p.name = [someName copy];

Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:

"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:

//person object has details of an individual you're assigning to a contact list.

Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;

//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.

In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.

How to remove only 0 (Zero) values from column in excel 2010

Consider your data is into column A and will write coding now

Sub deletezeros()
    Dim c As Range
    Dim searchrange As Range
    Dim i As Long

    Set searchrange = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp))

    For i = searchrange.Cells.Count To 1 Step -1
        Set c = searchrange.Cells(i)
        If c.Value = "0" Then c.EntireRow.delete
    Next i
End Sub

How to input a regex in string.replace?

import os, sys, re, glob

pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"

for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
   for line in reader: 
      retline =  pattern.sub(replacementStringMatchesPattern, "", line)         
      sys.stdout.write(retline)
      print (retline)

Why is 1/1/1970 the "epoch time"?

http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.

But it does not say why exactly 1/1/1970 was chosen in the end.

Notable excerpts from the Wikipedia page:

The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.

Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.

Convert string to decimal number with 2 decimal places in Java

Float.parseFloat() is the problem as it returns a new float.

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

You are formatting just for the purpose of display . It doesn't mean the float will be represented by the same format internally .

You can use java.lang.BigDecimal.

I am not sure why are you using parseFloat() twice. If you want to display the float in a certain format then just format it and display it.

Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));

How to efficiently concatenate strings in go

If you know the total length of the string that you're going to preallocate then the most efficient way to concatenate strings may be using the builtin function copy. If you don't know the total length before hand, do not use copy, and read the other answers instead.

In my tests, that approach is ~3x faster than using bytes.Buffer and much much faster (~12,000x) than using the operator +. Also, it uses less memory.

I've created a test case to prove this and here are the results:

BenchmarkConcat  1000000    64497 ns/op   502018 B/op   0 allocs/op
BenchmarkBuffer  100000000  15.5  ns/op   2 B/op        0 allocs/op
BenchmarkCopy    500000000  5.39  ns/op   0 B/op        0 allocs/op

Below is code for testing:

package main

import (
    "bytes"
    "strings"
    "testing"
)

func BenchmarkConcat(b *testing.B) {
    var str string
    for n := 0; n < b.N; n++ {
        str += "x"
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); str != s {
        b.Errorf("unexpected result; got=%s, want=%s", str, s)
    }
}

func BenchmarkBuffer(b *testing.B) {
    var buffer bytes.Buffer
    for n := 0; n < b.N; n++ {
        buffer.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); buffer.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", buffer.String(), s)
    }
}

func BenchmarkCopy(b *testing.B) {
    bs := make([]byte, b.N)
    bl := 0

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        bl += copy(bs[bl:], "x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); string(bs) != s {
        b.Errorf("unexpected result; got=%s, want=%s", string(bs), s)
    }
}

// Go 1.10
func BenchmarkStringBuilder(b *testing.B) {
    var strBuilder strings.Builder

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        strBuilder.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); strBuilder.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", strBuilder.String(), s)
    }
}

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Authenticate with GitHub using a token

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/

Adding an external directory to Tomcat classpath

See also question: Can I create a custom classpath on a per application basis in Tomcat

Tomcat 7 Context hold Loader element. According to docs deployment descriptor (what in <Context> tag) can be placed in:

  • $CATALINA_BASE/conf/server.xml - bad - require server restarts in order to reread config
  • $CATALINA_BASE/conf/context.xml - bad - shared across all applications
  • $CATALINA_BASE/work/$APP.war:/META-INF/context.xml - bad - require repackaging in order to change config
  • $CATALINA_BASE/work/[enginename]/[hostname]/$APP/META-INF/context.xml - nice, but see last option!!
  • $CATALINA_BASE/webapps/$APP/META-INF/context.xml - nice, but see last option!!
  • $CATALINA_BASE/conf/[enginename]/[hostname]/$APP.xml - best - completely out of application and automatically scanned for changes!!!

Here my config which demonstrate how to use development version of project files out of $CATALINA_BASE hierarchy (note that I place this file into src/test/resources dir and intruct Maven to preprocess ${basedir} placeholders through pom.xml <filtering>true</filtering> so after build in new environment I copy it to $CATALINA_BASE/conf/Catalina/localhost/$APP.xml):

<Context docBase="${basedir}/src/main/webapp"
         reloadable="true">
    <!-- http://tomcat.apache.org/tomcat-7.0-doc/config/context.html -->
    <Resources className="org.apache.naming.resources.VirtualDirContext"
               extraResourcePaths="/WEB-INF/classes=${basedir}/target/classes,/WEB-INF/lib=${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <Loader className="org.apache.catalina.loader.VirtualWebappLoader"
            virtualClasspath="${basedir}/target/classes;${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <JarScanner scanAllDirectories="true"/>

    <!-- Use development version of JS/CSS files. -->
    <Parameter name="min" value="dev"/>
    <Environment name="app.devel.ldap" value="USER" type="java.lang.String" override="true"/>
    <Environment name="app.devel.permitAll" value="true" type="java.lang.String" override="true"/>
</Context>

UPDATE Tomcat 8 change syntax for <Resources> and <Loader> elements, corresponding part now look like:

<Resources>
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/classes" base="${basedir}/target/classes" />
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/lib" base="${basedir}/target/${project.build.finalName}/WEB-INF/lib" />
</Resources>

Java integer to byte array

The class org.apache.hadoop.hbase.util.Bytes has a bunch of handy byte[] conversion methods, but you might not want to add the whole HBase jar to your project just for this purpose. It's surprising that not only are such method missing AFAIK from the JDK, but also from obvious libs like commons io.

Graph implementation C++

It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).

I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:

struct Node
{
    ... payload ...
    Link *first_in, *last_in, *first_out, *last_out;
};

struct Link
{
    ... payload ...
    Node *from, *to;
    Link *prev_same_from, *next_same_from,
         *prev_same_to, *next_same_to;
};

In other words each node has a doubly-linked list of incoming links and a doubly-linked list of outgoing links. Each link knows from and to nodes and is at the same time in two different doubly-linked lists: the list of all links coming out from the same from node and the list of all links arriving at the same to node.

The pointers prev_same_from and next_same_from are used when following the chain of all the links coming out from the same node; the pointers prev_same_to and next_same_to are instead used when managing the chain of all the links pointing to the same node.

Data structure diagram

It's a lot of pointer twiddling (so unless you love pointers just forget about this) but query and update operations are efficient; for example adding a node or a link is O(1), removing a link is O(1) and removing a node x is O(deg(x)).

Of course depending on the problem, payload size, graph size, graph density this approach can be way overkilling or too much demanding for memory (in addition to payload you've 4 pointers per node and 6 pointers per link).

A similar structure full implementation can be found here.

Swift: How to get substring from start to last index of character

Swift 4:

extension String {

    /// the length of the string
    var length: Int {
        return self.characters.count
    }

    /// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
    ///
    /// - parameter index:  the start index
    /// - parameter length: the length of the substring
    ///
    /// - returns: the substring
    public func substring(index: Int, length: Int) -> String {
        if self.length <= index {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: index)
        if self.length <= index + length {
            return self.substring(from: leftIndex)
        }
        let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
        return self.substring(with: leftIndex..<rightIndex)
    }

    /// Get substring, e.g. -> "ABCDE".substring(left: 0, right: 2) -> "ABC"
    ///
    /// - parameter left:  the start index
    /// - parameter right: the end index
    ///
    /// - returns: the substring
    public func substring(left: Int, right: Int) -> String {
        if length <= left {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: left)
        if length <= right {
            return self.substring(from: leftIndex)
        }
        else {
            let rightIndex = self.index(self.endIndex, offsetBy: -self.length + right + 1)
            return self.substring(with: leftIndex..<rightIndex)
        }
    }
}

you can test it as follows:

    print("test: " + String("ABCDE".substring(index: 2, length: 3) == "CDE"))
    print("test: " + String("ABCDE".substring(index: 0, length: 3) == "ABC"))
    print("test: " + String("ABCDE".substring(index: 2, length: 1000) == "CDE"))
    print("test: " + String("ABCDE".substring(left: 0, right: 2) == "ABC"))
    print("test: " + String("ABCDE".substring(left: 1, right: 3) == "BCD"))
    print("test: " + String("ABCDE".substring(left: 3, right: 1000) == "DE"))

Check https://gitlab.com/seriyvolk83/SwiftEx library. It contains these and other helpful methods.

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

How to determine if a string is a number with C++?

C/C++ style for unsigned integers, using range based for C++11:

int isdigits(const std::string & s)
{
    for (char c : s) if (!isdigit(c)) return (0);
    return (1);
}

Adding Text to DataGridView Row Header

yes you can

DataGridView1.Rows[0].HeaderCell.Value = "my text";

Send multipart/form-data files with angular using $http

Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

How do I replace a character at a particular index in JavaScript?

There are lot of answers here, and all of them are based on two methods:

  • METHOD1: split the string using two substrings and stuff the character between them
  • METHOD2: convert the string to character array, replace one array member and join it

Personally, I would use these two methods in different cases. Let me explain.

@FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.

@vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.

But what will happen if I have to make quite a few replacements?

I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:

var str = "... {A LARGE STRING HERE} ...";

for(var i=0; i<100000; i++)
{
  var n = '' + Math.floor(Math.random() * 10);
  var p = Math.floor(Math.random() * 1000);
  // replace character *n* on position *p*
}

I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).

Results:

  • TEST1: 195ms
  • TEST2: 6ms

It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???

What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.

So, it's all about choosing the right tool for the job. Again.

Is there a difference between "throw" and "throw ex"?

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

    static void Main(string[] args)
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace.ToString());
            Console.ReadKey();
        }
    }
    
    private static void Method2()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
            throw ex;
        }
    }
    
    private static void Method1()
    {
        try
        {
            throw new Exception("Inside Method1");
        }
        catch (Exception)
        {
            throw;
        }
    }
    

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

Javascript date regex DD/MM/YYYY

((?=\d{4})\d{4}|(?=[a-zA-Z]{3})[a-zA-Z]{3}|\d{2})((?=\/)\/|\-)((?=[0-9]{2})[0-9]{2}|(?=[0-9]{1,2})[0-9]{1,2}|[a-zA-Z]{3})((?=\/)\/|\-)((?=[0-9]{4})[0-9]{4}|(?=[0-9]{2})[0-9]{2}|[a-zA-Z]{3})

Regex Compile on it

2012/22/Jan
2012/22/12 
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012-Dec-22
2012-12-22
23/12/2012
23/12/2012
Dec-22-2012
12-2-2012
23-12-2012
23-12-2012

How to make lists contain only distinct element in Python?

How about dictionary comprehensions?

>>> mylist = [3, 2, 1, 3, 4, 4, 4, 5, 5, 3]

>>> {x:1 for x in mylist}.keys()
[1, 2, 3, 4, 5]

EDIT To @Danny's comment: my original suggestion does not keep the keys ordered. If you need the keys sorted, try:

>>> from collections import OrderedDict

>>> OrderedDict( (x,1) for x in mylist ).keys()
[3, 2, 1, 4, 5]

which keeps elements in the order by the first occurrence of the element (not extensively tested)

How can I kill a process by name instead of PID?

The easiest way to do is first check you are getting right process IDs with:

pgrep -f [part_of_a_command]

If the result is as expected. Go with:

pkill -f [part_of_a_command]

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

Make WPF Application Fullscreen (Cover startmenu)

window.WindowStyle = WindowStyle.None;
window.ResizeMode = ResizeMode.NoResize;
window.Left = 0;
window.Top = 0;
window.Width = SystemParameters.VirtualScreenWidth;
window.Height = SystemParameters.VirtualScreenHeight;
window.Topmost = true;

Works with multiple screens

How to get rid of the "No bootable medium found!" error in Virtual Box?

Follow the steps below:

1) Select your VM Instance. Go to Settings->Storage

2) Under the storage tree select the default image or "Empty"(which ever is present)

3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file"

4) Browse and select the image file(iso or what ever format) from the system

5) Select OK.

Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.

Insert data through ajax into mysql database

Try this:

  $(document).on('click','#save',function(e) {
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insertmail.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

and in insertmail.php:

<?php 
if(isset($_REQUEST))
{
        mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

Don't use mysql_ it's deprecated.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

<?php
if($_POST['email']!="")
{
    mysql_connect("localhost","root","");
    mysql_select_db("eciticket_db");
    error_reporting(E_ALL && ~E_NOTICE);
    $email=$_POST['email'];
    $sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
    $result=mysql_query($sql);
    if($result){
    //echo "You have been successfully subscribed.";
              setcookie("msg","You have been successfully subscribed.",time()+5,"/");
              header("location:yourphppage.php");
    }
     if(!$sql)
    die(mysql_error());
    mysql_close();
}
?>
    <?php if(isset($_COOKIE['msg'])){?>
       <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> 
    <?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="submit" value="subscribe" class="submit"/>
</form>

Generate random numbers uniformly over an entire range

The solution given by man 3 rand for a number between 1 and 10 inclusive is:

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

In your case, it would be:

j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));

Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.

jQuery Ajax requests are getting cancelled without being sent

In my case, it was the missing trailing slash in the url. Adding the trailing slash solved my problem.

Counting the occurrences / frequency of array elements

So here's how I'd do it with some of the newest javascript features:

First, reduce the array to a Map of the counts:

let countMap = array.reduce(
  (map, value) => {map.set(value, (map.get(value) || 0) + 1); return map}, 
  new Map()
)

By using a Map, your starting array can contain any type of object, and the counts will be correct. Without a Map, some types of objects will give you strange counts. See the Map docs for more info on the differences.

This could also be done with an object if all your values are symbols, numbers, or strings:

let countObject = array.reduce(
  (map, value) => { map[value] = (map[value] || 0) + 1; return map },
  {}
)

Or slightly fancier in a functional way without mutation, using destructuring and object spread syntax:

let countObject = array.reduce(
  (value, {[value]: count = 0, ...rest}) => ({ [value]: count + 1, ...rest }),
  {}
)

At this point, you can use the Map or object for your counts (and the map is directly iterable, unlike an object), or convert it to two arrays.

For the Map:

countMap.forEach((count, value) => console.log(`value: ${value}, count: ${count}`)

let values = countMap.keys()
let counts = countMap.values()

Or for the object:

Object
  .entries(countObject) // convert to array of [key, valueAtKey] pairs
  .forEach(([value, count]) => console.log(`value: ${value}, count: ${count}`)

let values = Object.keys(countObject)
let counts = Object.values(countObject)

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.

I would check your application servers SSL settings and make sure that the certification is configured correctly.

How to export all data from table to an insertable sql format?

I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).

If you dont have identity column in table B_table:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.

In case if you dont have existing B_table in B_db

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

will create table B_table in database B_db with all existing values

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How can I generate a list of files with their absolute path in Linux?

Most if not all of the suggested methods result in paths that cannot be used directly in some other terminal command if the path contains spaces. Ideally the results will have slashes prepended. This works for me on macOS:

find / -iname "*SEARCH TERM spaces are okay*" -print 2>&1  | grep -v denied |grep -v permitted |sed -E 's/\ /\\ /g'

FIND_IN_SET() vs IN()

To get the all related companies name, not based on particular Id.

SELECT 
    (SELECT GROUP_CONCAT(cmp.cmpny_name) 
    FROM company cmp 
    WHERE FIND_IN_SET(cmp.CompanyID, odr.attachedCompanyIDs)
    ) AS COMPANIES
FROM orders odr

Sending event when AngularJS finished loading

According to the Angular team and this Github issue:

we now have $viewContentLoaded and $includeContentLoaded events that are emitted in ng-view and ng-include respectively. I think this is as close as one can get to knowing when we are done with the compilation.

Based on this, it seems this is currently not possible to do in a reliable way, otherwise Angular would have provided the event out of the box.

Bootstrapping the app implies running the digest cycle on the root scope, and there is also not a digest cycle finished event.

According to the Angular 2 design docs:

Because of multiple digests, it is impossible to determine and notify the component that the model is stable. This is because notification can further change data, which can restart the binding process.

According to this, the fact that this is not possible is one the reasons why the decision was taken to go for a rewrite in Angular 2.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Try this jobber

String stringy =null;
 byte[] buffer =  new byte[100000];
            for (int i = 0; i < buffer.length; i++) {
            buffer[i] =0;

        }
            stringy =StringUtils.toAsciiString(buffer);

Relational Database Design Patterns?

Your question is a bit vague, but I suppose UPSERT could be considered a design pattern. For languages that don't implement MERGE, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE; else INSERT) exist.

In MS DOS copying several files to one file

make sure you have mapped the y: drive, or copy all the files to local dir c:/local

c:/local> copy *.* c:/newfile.txt

How to split a comma separated string and process in a loop using JavaScript

Like this:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

Automapper missing type map configuration or unsupported mapping - Error

I did this to remove the error:

Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);

Open a folder using Process.Start

You're using the @ symbol, which removes the need for escaping your backslashes.

Remove the @ or replace \\ with \

What is ANSI format?

When using single-byte characters, the ASCII format defines the first 127 characters. The extended characters from 128-255 are defined by various ANSI code pages to allow limited support for other languages. In order to make sense of an ANSI encoded string, you need to know which code page it uses.

Throwing multiple exceptions in a method of an interface in java

You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}

How to iterate over a JSONObject?

I made a small recursive function that goes through the entire json object and saves the key path and its value.

// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();

// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();

// Recursive function that goes through a json object and stores 
// its key and values in the hashmap 
private void loadJson(JSONObject json){
    Iterator<?> json_keys = json.keys();

    while( json_keys.hasNext() ){
        String json_key = (String)json_keys.next();

        try{
            key_path.push(json_key);
            loadJson(json.getJSONObject(json_key));
       }catch (JSONException e){
           // Build the path to the key
           String key = "";
           for(String sub_key: key_path){
               key += sub_key+".";
           }
           key = key.substring(0,key.length()-1);

           System.out.println(key+": "+json.getString(json_key));
           key_path.pop();
           myKeyValues.put(key, json.getString(json_key));
        }
    }
    if(key_path.size() > 0){
        key_path.pop();
    }
}

Putty: Getting Server refused our key Error

Steps to fix Root mount (That i followed as i changed permission with ec2-user folder and the authorization key file) This process will be similar to detach and attach a pen-drive

Below are some other scenarios you may encounter -

  1. You're using an SSH private key but the corresponding public key is not in the authorized_keys file.
  2. You don't have permissions for your authorized_keys file.
  3. You don't have permissions for the .ssh folder.
  4. Your authorized_keys file or .ssh folder isn't named correctly.
  5. Your authorized_keys file or .ssh folder was deleted.

Steps to fix them

  • Stop the problematic Ec2 instance
  • Detach the root volume (/dev/sda1)
  • Create an ec2 instance or use an running one
  • Mount the detached volume (/dev/sdvf) to new ec2 instance

Now after you login to new ec2 run below steps

  • Lsblk command - list all available mounts
  • Pick the mount value that you unmount from the problematic instance
  • As ec2-user run “sudo mount /dev/mapper/rootvg-home /mnt” sudo mount /dev/mapper/rootvg-home /mnt
  • Then change directory to /mnt
  • Make all necessary changes

Now we have fixed our volume with the issue that we faced. Mostly it could be user permission issue - Umount /mnt to unmounts it - Now go to the console and point to the volume attached to new instance and detach it - After detached, attached it to your new volume as /dev/sda1

With that said you should be able to login successfully

How to use store and use session variables across pages?

Try this

First Page

<?php
   session_start();
   $_SESSION['myvar']='myvalue';
?>

Second page

 <?php
   session_start();
   echo $_SESSION['myvar'];
 ?>

List submodules in a Git repository

The following command will list the submodules:

git submodule--helper list

The output is something like this:

<mode> <sha1> <stage> <location>

Note: It requires Git 2.7.0 or above.

Capture close event on Bootstrap Modal

This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:

$("#myModal").on("hidden.bs.modal", function () {
    // put your default event here
});

Powershell: count members of a AD group

The Get-ADGroupMember cmdlet would solve this in a much more efficient way than you're tying.

As an example:

$users = Get-ADGroupMember -Identity 'Group Name'
$users.count
132

EDIT:

In order to clarify things, and to make your script simpler. Here's a generic script that will work for your environment that outputs the user count for each group matching your filters.

$groups = Get-ADGroup -filter {(name -like "WA*") -or (name -like "workstation*")}
foreach($group in $groups){
  $countUser = (Get-ADGroupMember $group.DistinguishedName).count
  Write-Host "The group $($group.Name) has $countUser user(s)."
}

How can I bring my application window to the front?

I use SwitchToThisWindow to bring the application to the forefront as in this example:

static class Program
{
    [DllImport("User32.dll", SetLastError = true)]
    static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);



    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew;
        int iP;
        Process currentProcess = Process.GetCurrentProcess();
        Mutex m = new Mutex(true, "XYZ", out createdNew);
        if (!createdNew)
        {
            // app is already running...
            Process[] proc = Process.GetProcessesByName("XYZ");

            // switch to other process
            for (iP = 0; iP < proc.Length; iP++)
            {
                if (proc[iP].Id != currentProcess.Id)
                    SwitchToThisWindow(proc[0].MainWindowHandle, true);
            }

            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new form());
        GC.KeepAlive(m);

    }

Laravel Checking If a Record Exists

if (User::where('email', '[email protected]')->first()) {
    // It exists
} else {
    // It does not exist
}

Use first(), not count() if you only need to check for existence.

first() is faster because it checks for a single match whereas count() counts all matches.

How to get JSON from webpage into Python script

I have found this to be the easiest and most efficient way to get JSON from a webpage when using Python 3:

import json,urllib.request
data = urllib.request.urlopen("https://api.github.com/users?since=100").read()
output = json.loads(data)
print (output)

Shortcuts in Objective-C to concatenate NSStrings

NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];

Convert string with comma to integer

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

SQL Server 2008 - Help writing simple INSERT Trigger

check this code:

CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin   
    Insert into Employee (Name, Department)  
    Select Distinct i.Name, i.Department   
        from Inserted i
        Left Join Employee e on i.Name = e.Name and i.Department = e.Department
        where e.Name is null
End

Calling an API from SQL Server stored procedure

Simple SQL triggered API call without building a code project

I know this is far from perfect or architectural purity, but I had a customer with a short term, critical need to integrate with a third party product via an immature API (no wsdl) I basically needed to call the API when a database event occurred. I was given basic call info - URL, method, data elements and Token, but no wsdl or other start to import into a code project. All recommendations and solutions seemed start with that import.

I used the ARC (Advanced Rest Client) Chrome extension and JaSON to test the interaction with the Service from a browser and refine the call. That gave me the tested, raw call structure and response and let me play with the API quickly. From there, I started trying to generate the wsdl or xsd from the json using online conversions but decided that was going to take too long to get working, so I found cURL (clouds part, music plays). cURL allowed me to send the API calls to a local manager from anywhere. I then broke a few more design rules and built a trigger that queued the DB events and a SQL stored procedure and scheduled task to pass the parameters to cURL and make the calls. I initially had the trigger calling XP_CMDShell (I know, booo) but didn't like the transactional implications or security issues, so switched to the Stored Procedure method.

In the end, DB insert matching the API call case triggers write to Queue table with parameters for API call Stored procedure run every 5 seconds runs Cursor to pull each Queue table entry, send the XP_CMDShell call to the bat file with parameters Bat file contains Curl call with parameters inserted sending output to logs. Works well.

Again, not perfect, but for a tight timeline, and a system used short term, and that can be closely monitored to react to connectivity and unforeseen issues, it worked.

Hope that helps someone struggling with limited API info get a solution going quickly.

How to save MySQL query output to excel or .txt file?

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

Good Patterns For VBA Error Handling

Also relevant to the discussion is the relatively unknown Erl function. If you have numeric labels within your code procedure, e.g.,

Sub AAA()
On Error Goto ErrorHandler

1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
   Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
      "Last Successful Line: " + CStr(Erl)
End If   
End Sub 

The Erl function returns the most recently encountered numberic line label. In the example above, if a run-time error occurs after label 1200: but before 1300:, the Erl function will return 1200, since that is most recenlty sucessfully encountered line label. I find it to be a good practice to put a line label immediately above your error handling block. I typcially use 9999 to indicate that the main part of the procuedure ran to its expected conculsion.

NOTES:

  • Line labels MUST be positive integers -- a label like MadeItHere: isn't recogonized by Erl.

  • Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000. There is no relationship between editor line numbers and line label numbers used with Erl.

  • Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl is greatly diminished, but Erl will still report the correct number.

  • Line labels are specific to the procedure in which they appear. If procedure ProcA calls procedure ProcB and an error occurs in ProcB that passes control back to ProcA, Erl (in ProcA) will return the most recently encounterd line label number in ProcA before it calls ProcB. From within ProcA, you cannot get the line label numbers that might appear in ProcB.

Use care when putting line number labels within a loop. For example,

For X = 1 To 100
500:
' some code that causes an error
600:
Next X

If the code following line label 500 but before 600 causes an error, and that error arises on the 20th iteration of the loop, Erl will return 500, even though 600 has been encounterd successfully in the previous 19 interations of the loop.

Proper placement of line labels within the procedure is critical to using the Erl function to get truly meaningful information.

There are any number of free utilies on the net that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.

If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl in that information can make finding and fixing the problem VASTLY simpler than if value of Erl is not reported.

Creating a custom JButton in Java

You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:

try {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    Class aClass = MainFrame.class;
    InputStream stream = aClass.getResourceAsStream("\\default.xml");

    if (stream == null) {
        System.err.println("Missing configuration file");
        System.exit(-1);                
    }

    synth.load(stream, aClass);

    UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
    System.err.println("Bad configuration file");
    pe.printStackTrace();
    System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
    System.err.println("Old JRE in use. Get a new one");
    System.exit(-3);
}

From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.

The xml file might look like this:

<synth>
    <style id="button">
        <font name="DIALOG" size="12" style="BOLD"/>
        <state value="MOUSE_OVER">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
        <state value="ENABLED">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
    </style>
    <bind style="button" type="name" key="dirt"/>
</synth>

The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").

And a couple of useful links:

http://javadesktop.org/articles/synth/

http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The answer of @cheez sometime doesn't work and recursively call the function again and again. To solve this problem you should copy the function deeply. You can do this by using the function partial, so the final code is:

import numpy as np
from functools import partial

# save np.load
np_load_old = partial(np.load)

# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)

# call load_data with allow_pickle implicitly set to true
(train_data, train_labels), (test_data, test_labels) = 
imdb.load_data(num_words=10000)

# restore np.load for future normal usage
np.load = np_load_old

C# int to enum conversion

Casting should be enough. If you're using C# 3.0 you can make a handy extension method to parse enum values:

public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
    Type type = typeof(TEnum);

    if (value == default(TInput))
    {
        throw new ArgumentException("Value is null or empty.", "value");
    }

    if (!type.IsEnum)
    {
        throw new ArgumentException("Enum expected.", "TEnum");
    }

    return (TEnum)Enum.Parse(type, value.ToString(), true);
}

How to remove the querystring and get only the url?

Use PHP Manual - parse_url() to get the parts you need.

Edit (example usage for @Navi Gamage)

You can use it like this:

<?php
function reconstruct_url($url){    
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];

    return $constructed_url;
}

?>

Edit (second full example):

Updated function to make sure scheme will be attached and none notice msgs appear:

function reconstruct_url($url){    
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');

    return $constructed_url;
}


$test = array(
    'http://www.mydomian.com/myurl.html?unwan=abc',
    'http://www.mydomian.com/myurl.html',
    'http://www.mydomian.com',
    'https://mydomian.com/myurl.html?unwan=abc&ab=1'
);

foreach($test as $url){
    print_r(parse_url($url));
}       

Will return:

Array
(
    [scheme] => http
    [host] => www.mydomian.com
    [path] => /myurl.html
    [query] => unwan=abc
)
Array
(
    [scheme] => http
    [host] => www.mydomian.com
    [path] => /myurl.html
)
Array
(
    [scheme] => http
    [host] => www.mydomian.com
)
Array
(
    [path] => mydomian.com/myurl.html
    [query] => unwan=abc&ab=1
)

This is the output from passing example urls through parse_url() with no second parameter (for explanation only).

And this is the final output after constructing url using:

foreach($test as $url){
    echo reconstruct_url($url) . '<br/>';
}   

Output:

http://www.mydomian.com/myurl.html
http://www.mydomian.com/myurl.html
http://www.mydomian.com
https://mydomian.com/myurl.html

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Commenting code in Notepad++

Yes in Notepad++ you can do that!

Some hotkeys regarding comments:

  • Ctrl+Q Toggle block comment
  • Ctrl+K Block comment
  • Ctrl+Shift+K Block uncomment
  • Ctrl+Shift+Q Stream comment

Source: shortcutworld.com from the Comment / uncomment section.

On the link you will find many other useful shortcuts too.

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

Checking whether a variable is an integer or not

Found a related question here on SO itself.

Python developers prefer to not check types but do a type specific operation and catch a TypeError exception. But if you don't know the type then you have the following.

>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True

How to define static constant in a class in swift

Perhaps a nice idiom for declaring constants for a class in Swift is to just use a struct named MyClassConstants like the following.

struct MyClassConstants{
    static let testStr = "test"
    static let testStrLength = countElements(testStr)

    static let arrayOfTests: [String] = ["foo", "bar", testStr]
}

In this way your constants will be scoped within a declared construct instead of floating around globally.

Update

I've added a static array constant, in response to a comment asking about static array initialization. See Array Literals in "The Swift Programming Language".

Notice that both string literals and the string constant can be used to initialize the array. However, since the array type is known the integer constant testStrLength cannot be used in the array initializer.

How to change or add theme to Android Studio?

Simple. Just hit CTRL + alt + s - appearance & behavior - appearance - Theme - (Darcula)

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

How to set an iframe src attribute from a variable in AngularJS

It is the $sce service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.

You can disable it completely, but it's not recommended

angular.module('myAppWithSceDisabledmyApp', [])
   .config(function($sceProvider) {
       $sceProvider.enabled(false);
   });

for more info https://docs.angularjs.org/api/ng/service/$sce

Javascript to display the current date and time

(function(con) {
    var oDate = new Date();
    var nHrs = oDate.getHours();
    var nMin = oDate.getMinutes();
    var nDate = oDate.getDate();
    var nMnth = oDate.getMonth();
    var nYear = oDate.getFullYear();

    con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
    con.log(nHrs + ' : ' + nMin);
})(console);

This produces an output like:

30 - 8 - 2013
21 : 30

Perhaps you may refer documentation on Date object at MDN for more information

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

Resolve promises one after another (i.e. in sequence)?

My preferred solution:

function processArray(arr, fn) {
    return arr.reduce(
        (p, v) => p.then((a) => fn(v).then(r => a.concat([r]))),
        Promise.resolve([])
    );
}

It's not fundamentally different from others published here but:

  • Applies the function to items in series
  • Resolves to an array of results
  • Doesn't require async/await (support is still quite limited, circa 2017)
  • Uses arrow functions; nice and concise

Example usage:

const numbers = [0, 4, 20, 100];
const multiplyBy3 = (x) => new Promise(res => res(x * 3));

// Prints [ 0, 12, 60, 300 ]
processArray(numbers, multiplyBy3).then(console.log);

Tested on reasonable current Chrome (v59) and NodeJS (v8.1.2).

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

This Error hit me after installing RVM correctly. Solution: re-boot Terminal.

Reference RailsCast's RVM Install tutorial.