Programs & Examples On #Multiton

The Multiton pattern is a creational design pattern. This pattern expands on the singleton concept to manage a fixed number of instances of the Multiton class. This typically done with a map of named instances as key-value pairs.

jQuery How to Get Element's Margin and Padding?

var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

Here's the edited jsFiddle showing the result.

You can perform the same type of operations for the Height to get its margin, border, and padding.

Step-by-step debugging with IPython

If you type exit() in embed() console the code continue and go to the next embed() line.

How to make --no-ri --no-rdoc the default for gem install?

As mentioned above, put gem: --no-document in your gem file. However, the system-wide gemrc will not always necessarily go into /etc/gemrc. If you are using RVM, or you have Ruby installed under /usr/local/bin, it needs to go in a different location. You can find this location by running irb and typing...

require 'rubygems'
Gem::ConfigFile::SYSTEM_WIDE_CONFIG_FILE

See the original post on this over here.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Lambda function in list comprehensions

This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.

I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:

squares = []
for x in range(10): squares.append(x*x)
  • this is the good ol' way of imperative syntax.

But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).

So, the OP's comprehension returned a list of lambdas:

[(lambda x: x*x) for x in range(10)]

This is of course just 10 different copies of the squaring function, see:

>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]

Note the memory addresses of the lambdas - they are all different!

You could of course have a more "optimal" (haha) version of this expression:

>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]

See? 3 time the same lambda.

Please note, that I used _ as the for variable. It has nothing to do with the x in the lambda (it is overshadowed lexically!). Get it?

I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:

[lambda x: (x*x for x in range(10))]

which could be: [[0, 1, 4, ..., 81]], or [(0, 1, 4, ..., 81)], or which I find most logical, this would be a list of 1 element - a generator returning the values. It is just not the case, the language doesn't work this way.

BUT What, If...

What if you DON'T overshadow the for variable, AND use it in your lambdas???

Well, then crap happens. Look at this:

[lambda x: x * i for i in range(4)]

this means of course:

[(lambda x: x * i) for i in range(4)]

BUT it DOESN'T mean:

[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]

This is just crazy!

The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i via reference, and not its value when they were evaluated!

So, this expression:

[(lambda x: x * i) for i in range(4)]

IS roughly EQUIVALENT to:

[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]

I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis module), but for Python-VM-agnostic discussion this is enough. So much for the job interview question.

Now, how to make a list of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i by wrapping it in another lambda, which is getting called inside the list comprehension expression:

Before:

>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
2

After:

>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
1

(I had the outer lambda variable also = i, but I decided this is the clearer solution - I introduced y so that we can all see which witch is which).

Edit 2019-08-30:

Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda and calling it immediately with the current value of i. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i inside a partial object, and have the "inner" (original) lambda take it as an argument (passed supplied by the partial object at the time of the call), i.e.:

After 2:

>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial). Let's do some renaming:

After 2.5:

>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a[0](1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'

WAT?

>>> a[0]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'

Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?

Well, it's not a real WAT, when we pass coef to partial in this way, it becomes a keyword argument, so it must come after the positional x argument, like so:

After 3:

>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

I would prefer the last version over the nested lambda, but to each their own...

Edit 2020-08-18:

Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):

>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).

What is the difference between mocking and spying when using Mockito?

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.

Source: http://www.baeldung.com/mockito-spy + self notes.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

How to implement a Keyword Search in MySQL?

Personally, I wouldn't use the LIKE string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.

Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:

SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Using -XX:+UseParNewGC along with -XX:+UseConcMarkSweepGC, will cause higher pause time for Minor GCs, when compared to -XX:+UseParallelGC.

This is because, promotion of objects from Young to Old Generation will require running a Best-Fit algorithm (due to old generation fragmentation) to find an address for this object.
Running such an algorithm is not required when using -XX:+UseParallelGC, as +UseParallelGC can be configured only with MarkandCompact Collector, in which case there is no fragmentation.

Storing and displaying unicode string (??????) using PHP and MySQL

CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');

What is recursion and when should I use it?

Recursion as it applies to programming is basically calling a function from inside its own definition (inside itself), with different parameters so as to accomplish a task.

Determining the size of an Android view at runtime

Here is the code for getting the layout via overriding a view if API < 11 (API 11 includes the View.OnLayoutChangedListener feature):

public class CustomListView extends ListView
{
    private OnLayoutChangedListener layoutChangedListener;

    public CustomListView(Context context)
    {
        super(context);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        if (layoutChangedListener != null)
        {
            layoutChangedListener.onLayout(changed, l, t, r, b);
        }
        super.onLayout(changed, l, t, r, b);
    }

    public void setLayoutChangedListener(
        OnLayoutChangedListener layoutChangedListener)
    {
        this.layoutChangedListener = layoutChangedListener;
    }
}
public interface OnLayoutChangedListener
{
    void onLayout(boolean changed, int l, int t, int r, int b);
}

How to make HTML element resizable using pure Javascript?

what about a pure css3 solution?

div {
    resize: both;
    overflow: auto;
} 

MDN Web Docs

W3Schools example

Browser support

Create or update mapping in elasticsearch

Generally speaking, you can update your index mapping using the put mapping api (reference here) :

curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
    "advert_type" : {
        "properties" : {

          //your new mapping properties

        }
    }
}
'

It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.

You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.

Finally, you will have to reindex your data for your new mapping to be taken into account.

The best solution would really be to create a new index.

If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.

Append Char To String in C?

In my case, this was the best solution I found:

snprintf(str, sizeof str, "%s%c", str, c);

Sort Go map values by keys

This provides you the code example on sorting map. Basically this is what they provide:

var keys []int
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark1-8      2863149           374 ns/op         152 B/op          5 allocs/op

and this is what I would suggest using instead:

keys := make([]int, 0, len(myMap))
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark2-8      5320446           230 ns/op          80 B/op          2 allocs/op

Full code can be found in this Go Playground.

Call asynchronous method in constructor?

In order to use async within the constructor and ensure the data is available when you instantiate the class, you can use this simple pattern:

class FooClass : IFooAsync
{        
    FooClass 
    {
        this.FooAsync = InitFooTask();
    }

    public Task FooAsync { get; }

    private async Task InitFooTask()
    {
        await Task.Delay(5000);
    }
}

The interface:

public interface IFooAsync
{
    Task FooAsync { get; }
}

The usage:

FooClass foo = new FooClass();    
if (foo is IFooAsync)
    await foo.FooAsync;

Instantiating a generic class in Java

Generics in Java are generally more powerful than in C#.

If you want to construct an object but without hardwiring a constructor/static method, use an abstract factory. You should be able to find detailed information and tutorials on the Abstract Factory Pattern in any basic design patterns book, introduction to OOP or all over the interwebs. It's not worth duplicating code here, other than to mention that Java's closure syntax sucks.

IIRC, C# has a special case for specifying a generic type has a no-args constructor. This irregularity, by definition, presupposes that client code wants to use this particular form of construction and encourages mutability.

Using reflection for this is just wrongheaded. Generics in Java are a compile-time, static-typing feature. Attempts to use them at runtime are a clear indication of something going wrong. Reflection causes verbose code, runtime failures, unchecked dependencies and security vulnerabilities. (Class.forName is particularly evil.)

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I use this way with Resource file (don't need Prompt anymore !)

@Html.TextBoxFor(m => m.Name, new 
{
     @class = "form-control",
     placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
     autofocus = "autofocus",
     required = "required"
})

.substring error: "is not a function"

try this code below :

var currentLocation = document.location;
muzLoc = String(currentLocation).substring(0,45);
prodLoc = String(currentLocation).substring(0,48); 
techLoc = String(currentLocation).substring(0,47);

Google Chrome Printing Page Breaks

I just wanted to note here that Chrome also ignores page-break-* css settings in divs that have been floated.

I suspect there is a sound justification for this somewhere in the css spec, but I figured noting it might help someone someday ;-)

Just another note: IE7 can't acknowledge page break settings without an explicit height on the previous block element:

http://social.msdn.microsoft.com/forums/en-US/iewebdevelopment/thread/fe523ec6-2f01-41df-a31d-9ba93f21787b/

Where's my JSON data in my incoming Django request?

The HTTP POST payload is just a flat bunch of bytes. Django (like most frameworks) decodes it into a dictionary from either URL encoded parameters, or MIME-multipart encoding. If you just dump the JSON data in the POST content, Django won't decode it. Either do the JSON decoding from the full POST content (not the dictionary); or put the JSON data into a MIME-multipart wrapper.

In short, show the JavaScript code. The problem seems to be there.

Error: Jump to case label

The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case.

In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally use the i variable which does exist but probably contains garbage.

switch(foo) {
  case 1:
    int i = 42; // i exists all the way to the end of the switch
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); // i is *also* in scope here, but is not initialized!
}

Wrapping the case in an explicit block solves the problem:

switch(foo) {
  case 1:
    {
        int i = 42; // i only exists within the { }
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123); // Now you cannot use i accidentally
}

Edit

To further elaborate, switch statements are just a particularly fancy kind of a goto. Here's an analoguous piece of code exhibiting the same issue but using a goto instead of a switch:

int main() {
    if(rand() % 2) // Toss a coin
        goto end;

    int i = 42;

  end:
    // We either skipped the declaration of i or not,
    // but either way the variable i exists here, because
    // variable scopes are resolved at compile time.
    // Whether the *initialization* code was run, though,
    // depends on whether rand returned 0 or 1.
    std::cout << i;
}

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

How should I validate an e-mail address?

I know that It's very too late, still I will give my answer.

I used this line of code to check the inputted Email format:

!TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();

The problem is, it will only check for the FORMAT not the SPELLING.

When I entered @gmal.com missing i ,and @yaho.com missing another o . It return true. Since it satisfies the condition for Email Format.

What I did is, I used the code above. Since it will give / return true if the if the user inputted @gmail.com ONLY, no text at the start.

FORMAT CHECKER

check

If I enter this email it will give me: true but the spelling is wrong. In my textInputLayout error

wrongSpelling

EMAIL ADDRESS @yahoo.com , @gmail.com, @outlook.com CHECKER

 //CHECK EMAIL
public boolean checkEmailValidity(AppCompatEditText emailFormat){

    String getEmail = emailFormat.getText().toString();
    boolean getEnd;

    //CHECK STARTING STRING IF THE USER
    //entered @gmail.com / @yahoo.com / @outlook.com only
    boolean getResult = !TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();

    //CHECK THE EMAIL EXTENSION IF IT ENDS CORRECTLY
    if (getEmail.endsWith("@gmail.com") || getEmail.endsWith("@yahoo.com") || getEmail.endsWith("@outlook.com")){
        getEnd = true;
    }else {
        getEnd = false;
    }

    //TEST THE START AND END
    return (getResult && getEnd);
}

RETURN: false

false

noSpecial

RETURN:true

true

XML:

<android.support.v7.widget.AppCompatEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editTextEmailAddress"
            android:inputType="textEmailAddress|textWebEmailAddress"
            android:cursorVisible="true"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:singleLine="true"
            android:maxLength="50"
            android:theme="@style/EditTextCustom"/>

Note: I tried to get the value from EditText and used split on it and even StringTokenizer. Both return false to me.

Find if current time falls in a time range

You're very close, the problem is you're comparing a DateTime to a TimeOfDay. What you need to do is add the .TimeOfDay property to the end of your Convert.ToDateTime() functions.

How to apply !important using .css()?

Three working examples

I had a similar situation, but I used .find() after struggling with .closest() for a long time with many variations.

The Example Code

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

Alternative

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

Working: http://jsfiddle.net/fx4mbp6c/

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

What is a reasonable code coverage % for unit tests (and why)?

The accepted answer makes a good point - there is not a single number that is going to make sense as a standard for every project. There are projects that just don't need such a standard. Where the accepted answer falls short, in my opinion, is in describing how one might make that decision for a given project.

I will take a shot at doing so. I am not an expert in test engineering and would be happy to see a more informed answer.

When to set code coverage requirements

First, why would you want to impose such a standard in the first place? In general, when you want to introduce empirical confidence in your process. What do I mean by "empirical confidence"? Well, the real goal correctness. For most software, we can't possibly know this across all inputs, so we settle for saying that code is well-tested. This is more knowable, but is still a subjective standard: It will always be open to debate whether or not you have met it. Those debates are useful and should occur, but they also expose uncertainty.

Code coverage is an objective measurement: Once you see your coverage report, there is no ambiguity about whether standards have been met are useful. Does it prove correctness? Not at all, but it has a clear relationship to how well-tested the code is, which in turn is our best way to increase confidence in its correctness. Code coverage is a measurable approximation of immeasurable qualities we care about.

Some specific cases where having an empirical standard could add value:

  • To satisfy stakeholders. For many projects, there are various actors who have an interest in software quality who may not be involved in the day-to-day development of the software (managers, technical leads, etc.) Saying "we're going to write all the tests we really need" is not convincing: They either need to trust entirely, or verify with ongoing close oversight (assuming they even have the technical understanding to do so.) Providing measurable standards and explaining how they reasonably approximate actual goals is better.
  • To normalize team behavior. Stakeholders aside, if you are working on a team where multiple people are writing code and tests, there is room for ambiguity for what qualifies as "well-tested." Do all of your colleagues have the same idea of what level of testing is good enough? Probably not. How do you reconcile this? Find a metric you can all agree on and accept it as a reasonable approximation. This is especially (but not exclusively) useful in large teams, where leads may not have direct oversight over junior developers, for instance. Networks of trust matter as well, but without objective measurements, it is easy for group behavior to become inconsistent, even if everyone is acting in good faith.
  • To keep yourself honest. Even if you're the only developer and only stakeholder for your project, you might have certain qualities in mind for the software. Instead of making ongoing subjective assessments about how well-tested the software is (which takes work), you can use code coverage as a reasonable approximation, and let machines measure it for you.

Which metrics to use

Code coverage is not a single metric; there are several different ways of measuring coverage. Which one you might set a standard upon depends on what you're using that standard to satisfy.

I'll use two common metrics as examples of when you might use them to set standards:

  • Statement coverage: What percentage of statements have been executed during testing? Useful to get a sense of the physical coverage of your code: How much of the code that I have written have I actually tested?
    • This kind of coverage supports a weaker correctness argument, but is also easier to achieve. If you're just using code coverage to ensure that things get tested (and not as an indicator of test quality beyond that) then statement coverage is probably sufficient.
  • Branch coverage: When there is branching logic (e.g. an if), have both branches been evaluated? This gives a better sense of the logical coverage of your code: How many of the possible paths my code may take have I tested?
    • This kind of coverage is a much better indicator that a program has been tested across a comprehensive set of inputs. If you're using code coverage as your best empirical approximation for confidence in correctness, you should set standards based on branch coverage or similar.

There are many other metrics (line coverage is similar to statement coverage, but yields different numeric results for multi-line statements, for instance; conditional coverage and path coverage is similar to branch coverage, but reflect a more detailed view of the possible permutations of program execution you might encounter.)

What percentage to require

Finally, back to the original question: If you set code coverage standards, what should that number be?

Hopefully it's clear at this point that we're talking about an approximation to begin with, so any number we pick is going to be inherently approximate.

Some numbers that one might choose:

  • 100%. You might choose this because you want to be sure everything is tested. This doesn't give you any insight into test quality, but does tell you that some test of some quality has touched every statement (or branch, etc.) Again, this comes back to degree of confidence: If your coverage is below 100%, you know some subset of your code is untested.
    • Some might argue that this is silly, and you should only test the parts of your code that are really important. I would argue that you should also only maintain the parts of your code that are really important. Code coverage can be improved by removing untested code, too.
  • 99% (or 95%, other numbers in the high nineties.) Appropriate in cases where you want to convey a level of confidence similar to 100%, but leave yourself some margin to not worry about the occasional hard-to-test corner of code.
  • 80%. I've seen this number in use a few times, and don't entirely know where it originates. I think it might be a weird misappropriation of the 80-20 rule; generally, the intent here is to show that most of your code is tested. (Yes, 51% would also be "most", but 80% is more reflective of what most people mean by most.) This is appropriate for middle-ground cases where "well-tested" is not a high priority (you don't want to waste effort on low-value tests), but is enough of a priority that you'd still like to have some standard in place.

I haven't seen numbers below 80% in practice, and have a hard time imagining a case where one would set them. The role of these standards is to increase confidence in correctness, and numbers below 80% aren't particularly confidence-inspiring. (Yes, this is subjective, but again, the idea is to make the subjective choice once when you set the standard, and then use an objective measurement going forward.)

Other notes

The above assumes that correctness is the goal. Code coverage is just information; it may be relevant to other goals. For instance, if you're concerned about maintainability, you probably care about loose coupling, which can be demonstrated by testability, which in turn can be measured (in certain fashions) by code coverage. So your code coverage standard provides an empirical basis for approximating the quality of "maintainability" as well.

Else clause on Python while statement

In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.

Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.

for k in [2, 3, 5, 7, 11, 13, 17, 25]:
    for m in range(2, 10):
        if k == m:
            continue
        print 'trying %s %% %s' % (k, m)
        if k % m == 0:
            print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
            break
    else:
        continue
    print 'breaking another level of loop'
    break
else:
    print 'no divisor could be found!'

For both while and for loops, the else statement is executed at the end, unless break was used.

In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

How to avoid using Select in Excel VBA

The main reason never to use Select or Activesheet is because most people will have at least another couple of workbooks open (sometimes dozens) when they run your macro, and if they click away from your sheet while your macro is running and click on some other book they have open, then the "Activesheet" changes, and the target workbook for an unqualified "Select" command changes as well.

At best, your macro will crash, at worst you might end up writing values or changing cells in the wrong workbook with no way to "Undo" them.

I have a simple golden rule that I follow: Add variables named "wb" and "ws" for a Workbook object and a Worksheet object and always use those to refer to my macro book. If I need to refer to more than one book, or more than one sheet, I add more variables.

For example,

Dim wb as Workbook
Dim ws as Worksheet
Set wb = ThisWorkBook
Set ws = wb.sheets("Output")

The "Set wb = ThisWorkbook" command is absolutely key. "ThisWorkbook" is a special value in Excel, and it means the workbook that your VBA code is currently running from. A very helpful shortcut to set your Workbook variable with.

After you've done that at the top of your Sub, using them could not be simpler, just use them wherever you would use "Selection":

So to change the value of cell "A1" in "Output" to "Hello", instead of:

Sheets("Output").Activate
ActiveSheet.Range("A1").Select
Selection.Value = "Hello"

We can now do this:

ws.Range("A1").Value = "Hello"

Which is not only much more reliable and less likely to crash if the user is working with multiple spreadsheets; it's also much shorter, quicker and easier to write.

As an added bonus, if you always name your variables "wb" and "ws", you can copy and paste code from one book to another and it will usually work with minimal changes needed, if any.

break/exit script

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.

error_reporting(E_ALL);

Filers can be made according to requirements.

E_ALL
E_ALL | E_STRICT

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

Is there any quick way to get the last two characters in a string?

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

Check if PHP-page is accessed from an iOS device

preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT'], $matches);
$os = current($matches);

switch($os){
   case 'iPhone': /*do something...*/ break;
   case 'Android': /*do something...*/ break;
   case 'iPad': /*do something...*/ break;
   case 'iPod': /*do something...*/ break;
   case 'webOS': /*do something...*/ break;
}

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Sending Multipart File as POST parameters with RestTemplate requests

I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,

String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);

fo.write(asset.getBytes());    
fo.close();   

parts.add("file", new FileSystemResource(tempFileName));    
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);   


//clean-up    
File f = new File(tempFileName);    
f.delete();

I am still looking for a more elegant solution to this problem.

What's an Aggregate Root?

From Evans DDD:

An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE.

And:

The root is the only member of the AGGREGATE that outside objects are allowed to hold references to[.]

This means that aggregate roots are the only objects that can be loaded from a repository.

An example is a model containing a Customer entity and an Address entity. We would never access an Address entity directly from the model as it does not make sense without the context of an associated Customer. So we could say that Customer and Address together form an aggregate and that Customer is an aggregate root.

Getting attribute using XPath

you can use:

(//@lang)[1]

these means you get all attributes nodes with name equal to "lang" and get the first one.

How to run a shell script at startup

Create your own /init executable

This is not what you want, but it is fun!

Just pick an arbitrary executable file, even a shell script, and boot the kernel with the command line parameter:

init=/path/to/myinit

Towards the end of boot, the Linux kernel runs the first userspace executable at the given path.

Several projects provide popular init executables used by major distros, e.g. systemd, and in most distros init will fork a bunch of processes used in normal system operation.

But we can hijack /init it to run our own minimal scripts to better understand our system.

Here is a minimal reproducible setup: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/f96d4d55c9caa7c0862991025e1291c48c33e3d9/README.md#custom-init

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

How do I determine the size of an object in Python?

Just use the sys.getsizeof function defined in the sys module.

sys.getsizeof(object[, default]):

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.

getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.

Usage example, in python 3.0:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead. Never used it though.

How to remove non UTF-8 characters from text file

cat foo.txt | strings -n 8 > bar.txt

will do the job.

'ssh-keygen' is not recognized as an internal or external command

if you run from cmd on windows check the path System Variable value must have inside C:\Program Files\Git\bin or the path of you git installation on cmd type set to see the variables

Best way to check for "empty or null value"

another way is

nullif(trim(stringExpression),'') is not null

SELECT INTO Variable in MySQL DECLARE causes syntax error?

I am using version 6 (MySQL Workbench Community (GPL) for Windows version 6.0.9 revision 11421 build 1170) on Windows Vista. I have no problem with the following options. Probably they fixed it since these guys got the problems three years ago.

/* first option */
SELECT ID 
INTO @myvar 
FROM party 
WHERE Type = 'individual';

-- get the result
select @myvar;

/* second option */
SELECT @myvar:=ID
FROM party
WHERE Type = 'individual';


/* third option. The same as SQL Server does */
SELECT @myvar = ID FROM party WHERE Type = 'individual';

All option above give me a correct result.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

One solution is to reset_index (and get back to df) and use pivot_table.

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

The operation cannot be completed because the DbContext has been disposed error

using(var database=new DatabaseEntities()){}

Don't use using statement. Just write like that

DatabaseEntities database=new DatabaseEntities ();{}

It will work.

For documentation on the using statement see here.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.

Viscon

How to call a vue.js function on page load

Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}

Handling Dialogs in WPF with MVVM

I think that the handling of a dialog should be the responsibility of the view, and the view needs to have code to support that.

If you change the ViewModel - View interaction to handle dialogs then the ViewModel is dependant on that implementation. The simplest way to deal with this problem is to make the View responsible for performing the task. If that means showing a dialog then fine, but could also be a status message in the status bar etc.

My point is that the whole point of the MVVM pattern is to separate business logic from the GUI, so you shouldn't be mixing GUI logic (to display a dialog) in the business layer (the ViewModel).

C# "as" cast vs classic cast

The as operator is useful in a couple of circumstances.

  1. When you only need to know an object is of a specific type but don't need to specifically act on members of that type
  2. When you'd like to avoid exceptions and instead explicitly deal with null
  3. You want to know if there is a CLR conversion between the objects and not just some user defined conversion.

The 3rd point is subtle but important. There is not a 1-1 mapping between which casts will succeed with the cast operator and those which will succeed with the as operator. The as operator is strictly limited to CLR conversions and will not consider user defined conversions (the cast operator will).

Specifically the as operator only allows for the following (from section 7.9.11 of the C# lang spec)

  • An identity (§6.1.1), implicit reference (§6.1.6), boxing (§6.1.7), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists from the type of E to T.
  • The type of E or T is an open type.
  • E is the null literal.

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show 'State' as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance's error log. So the next troubleshooting option is to look at the Event Viewer's security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

Count elements with jQuery

$('.someclass').length

You could also use:

$('.someclass').size()

which is functionally equivalent, but the former is preferred. In fact, the latter is now deprecated and shouldn't be used in any new development.

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

How can I close a login form and show the main form without my application closing?

try this

 private void cmdLogin_Click(object sender, EventArgs e)
    {
        if (txtUserName.Text == "admin" || txtPassword.Text == "1")
        {

            FrmMDI mdi = new FrmMDI();
            mdi.Show();
            this.Hide();
        }
        else {

            MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }

and when you exit the Application you can use

 Application.Exit();

How Do I Uninstall Yarn

Try this, it works well on macOS:

$ brew uninstall --force yarn
$ npm uninstall -g yarn
$ yarn -v

v0.24.5 (or your current version)

$ which yarn

/usr/local/bin/yarn

$ rm -rf /usr/local/bin/yarn
$ rm -rf /usr/local/bin/yarnpkg
$ which yarn

yarn not found

$ brew install yarn 
$ brew link yarn
$ yarn -v

v1.17.3 (latest version)

Egit rejected non-fast-forward

  1. Go in Github an create a repo for your new code.
  2. Use the new https or ssh url in Eclise when you are doing the push to upstream;

How do I create a right click context menu in Java Swing?

This question is a bit old - as are the answers (and the tutorial as well)

The current api for setting a popupMenu in Swing is

myComponent.setComponentPopupMenu(myPopupMenu);

This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:

myChild.setInheritsPopupMenu(true);

Spring @PropertySource using YAML

I found a workaround by using @ActiveProfiles("test") and adding an application-test.yml file to src/test/resources.

It ended up looking like this:

@SpringApplicationConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests {

}

The file application-test.yml just contains the properties that I want to override from application.yml (which can be found in src/main/resources).

Bootstrap carousel width and height

I had the same problem.

My height changed to its original height while my slide was animating to the left, ( in a responsive website )

so I fixed it with CSS only :

.carousel .item.left img{
    width: 100% !important;
}

Excel "External table is not in the expected format."

My scope consists of template download and verifies the template when it's filled with data So,

1) Download a template (.xlsx) file with the header row. the file is generated using openxml and it's working perfectly.

2) Upload the same file without any change from it's downloaded state. This will cause a connection error and fails (OLEDB connection is using for reading the excel sheet).

Here if the data is filled the program works as expected.

Anybody having an idea the issue is connected with the file we are creating it's in xml format if we open it and just save convert it in to excel format and it works well.

Any idea to download the excel with the preferred file type?

Call to undefined function mysql_query() with Login

I would recommend that start using mysqli_() and stop using mysql_()

Check the following page: LINK

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_affected_rows() PDOStatement::rowCount()

Try and use mysqli_() Or PDO

How do I show/hide a UIBarButtonItem?

Improving From @lnafziger answer

Save your Barbuttons in a strong outlet and do this to hide/show it:

-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you remove the button from the toolbar and animate it
    [navBarBtns removeObject:myButton];
    [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}


-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you add the button to the toolbar and animate it
    if (![navBarBtns containsObject:myButton]) {
        [navBarBtns addObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
}

When ever required use below Function..

[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

ORA-00904: invalid identifier

FYI, in this case the cause was found to be mixed case column name in the DDL for table creation.

However, if you are mixing "old style" and ANSI joins you could get the same error message even when the DDL was done properly with uppercase table name. This happened to me, and google sent me to this stackoverflow page so I thought I'd share since I was here.

--NO PROBLEM: ANSI syntax
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM PS_PERSON A
INNER JOIN PS_NAME_PWD_VW B ON B.EMPLID = A.EMPLID
INNER JOIN PS_HCR_PERSON_NM_I C ON C.EMPLID = A.EMPLID
WHERE 
    LENGTH(A.EMPLID) = 9
    AND LENGTH(B.LAST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
ORDER BY 1, 2, 3
/

--NO PROBLEM: OLD STYLE/deprecated/traditional oracle proprietary join syntax
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM PS_PERSON A
, PS_NAME_PWD_VW B 
, PS_HCR_PERSON_NM_I C 
WHERE 
    B.EMPLID = A.EMPLID
    and C.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.LAST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
ORDER BY 1, 2, 3
/

The two SQL statements above are equivalent and produce no error.

When you try to mix them you can get lucky, or you can get an Oracle has a ORA-00904 error.

--LUCKY: mixed syntax (ANSI joins appear before OLD STYLE)
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM 
    PS_PERSON A
    inner join PS_HCR_PERSON_NM_I C on C.EMPLID = A.EMPLID
    , PS_NAME_PWD_VW B
WHERE 
    B.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.FIRST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
/

--PROBLEM: mixed syntax (OLD STYLE joins appear before ANSI)
--http://sqlfascination.com/2013/08/17/oracle-ansi-vs-old-style-joins/
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM 
    PS_PERSON A
    , PS_NAME_PWD_VW B
    inner join PS_HCR_PERSON_NM_I C on C.EMPLID = A.EMPLID
WHERE 
    B.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.FIRST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
/

And the unhelpful error message that doesn't really describe the problem at all:

>[Error] Script lines: 1-12 -------------------------
ORA-00904: "A"."EMPLID": invalid identifier  Script line 6, statement line 6,
column 51 

I was able to find some research on this in the following blog post:

In my case, I was attempting to manually convert from old style to ANSI style joins, and was doing so incrementally, one table at a time. This appears to have been a bad idea. Instead, it's probably better to convert all tables at once, or comment out a table and its where conditions in the original query in order to compare with the new ANSI query you are writing.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.

You have to call show() either in onProgressUpdate() or in onPostExecute().

For example:

class ExampleTask extends AsyncTask<String, String, String> {

    // Your onPreExecute method.

    @Override
    protected String doInBackground(String... params) {
        // Your code.
        if (condition_is_true) {
            this.publishProgress("Show the dialog");
        }
        return "Result";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        connectionProgressDialog.dismiss();
        downloadSpinnerProgressDialog.show();
    }
}

Nullable DateTime conversion

You can try this

var lastPostDate = reader[3] == DBNull.Value ?
                                default(DateTime?): 
                                Convert.ToDateTime(reader[3]);

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

how to change php version in htaccess in server

Note that all above answers are correct for Apache+ setups. They're less likely to work with more current PHP-FPM setups. Those can typically only be defined in VirtualHost section, not .htaccess.

Again, this highly depends on how your hoster has configured PHP. Each domain/user will typically have it's own running PHP FPM instance. And subsequently a generic …/x-httpd-php52 type will not be recognized.

See ServerFault: Alias a FastCGI proxy protocol handler via Action/ScriptAlias/etc for some overview.

For Apache 2.4.10+/ configs you might be able to use something like:

 AddHandler "proxy:unix:/var/run/php-fpm-usr123.sock|fcgi://localhost" .php

Or SetHandler with name mapping from your .htaccess. But again, consulting your hoster on the concrete FPM socket is unavoidable. There's no generic answer to this on modern PHP-FPM setups.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

If you're behind a proxy, you should use X-Forwarded-For: http://en.wikipedia.org/wiki/X-Forwarded-For

It is an IETF draft standard with wide support:

The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.

If not, here are a couple other common headers I've seen:

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

How do I do a HTTP GET in Java?

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

How to change an element's title attribute using jQuery

In jquery ui modal dialogs you need to use this construct:

$( "#my_dialog" ).dialog( "option", "title", "my new title" );

How to check if a subclass is an instance of a class at runtime?

I've never actually used this, but try view.getClass().getGenericSuperclass()

Looping through a hash, or using an array in PowerShell

You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

How to convert integer to char in C?

To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence

int i=5;
char c = i+'0';

json.net has key method?

Just use x["error_msg"]. If the property doesn't exist, it returns null.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Go to command prompt, cd to the appropriate folder and type:

notepad .htaccess

After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try

echo. > .htaccess

Google Gson - deserialize list<class> object? (generic type)

Here is a solution that works with a dynamically defined type. The trick is creating the proper type of of array using Array.newInstance().

    public static <T> List<T> fromJsonList(String json, Class<T> clazz) {
    Object [] array = (Object[])java.lang.reflect.Array.newInstance(clazz, 0);
    array = gson.fromJson(json, array.getClass());
    List<T> list = new ArrayList<T>();
    for (int i=0 ; i<array.length ; i++)
        list.add(clazz.cast(array[i]));
    return list; 
}

Reading Properties file in Java

If your properties file path and your java class path are same then you should this.

For example:

src/myPackage/MyClass.java

src/myPackage/MyFile.properties

Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);

JavaScript property access: dot notation vs. brackets?

Dot notation does not work with some keywords (like new and class) in internet explorer 8.

I had this code:

//app.users is a hash
app.users.new = {
  // some code
}

And this triggers the dreaded "expected indentifier" (at least on IE8 on windows xp, I havn't tried other environments). The simple fix for that is to switch to bracket notation:

app.users['new'] = {
  // some code
}

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

How do I kill background processes / jobs when my shell script exits?

To be on the safe side I find it better to define a cleanup function and call it from trap:

cleanup() {
        local pids=$(jobs -pr)
        [ -n "$pids" ] && kill $pids
}
trap "cleanup" INT QUIT TERM EXIT [...]

or avoiding the function altogether:

trap '[ -n "$(jobs -pr)" ] && kill $(jobs -pr)' INT QUIT TERM EXIT [...]

Why? Because by simply using trap 'kill $(jobs -pr)' [...] one assumes that there will be background jobs running when the trap condition is signalled. When there are no jobs one will see the following (or similar) message:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

because jobs -pr is empty - I ended in that 'trap' (pun intended).

Event detect when css property changed using Jquery

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You can try out this one as well as. Because this worked for me and it's simple.

<style>
    <%@ include file="/css/style.css" %>
</style>

Instagram how to get my user id from username?

Working solution ~2018

I've found that, providing you have an access token, you can perform the following request in your browser:

https://api.instagram.com/v1/users/self?access_token=[VALUE]

In fact, access token contain the User ID (the first segment of the token):

<user-id>.1677aaa.aaa042540a2345d29d11110545e2499

You can get an access token by using this tool provided by Pixel Union.

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

If you're using the new emulator that comes with Android Studio 2.0, the keyboard shortcut for the menu key is now Cmd+M, just like in Genymotion.

Alternatively, you can always send a menu button press using adb in a terminal:

adb shell input keyevent KEYCODE_MENU

Also note that the menu button shortcut isn't a strict requirement, it's just the default behavior provided by the ReactActivity Java class (which is used by default if you created your project with react-native init). Here's the relevant code from onKeyUp in ReactActivity.java:

if (keyCode == KeyEvent.KEYCODE_MENU) {
  mReactInstanceManager.showDevOptionsDialog();
  return true;
}

If you're adding React Native to an existing app (documentation here) and you aren't using ReactActivity, you'll need to hook the menu button up in a similar way. You can also call ReactInstanceManager.showDevOptionsDialog through any other mechanism. For example, in an app I'm working on, I added a dev-only Action Bar menu item that brings up the menu, since I find that more convenient than shaking the device when working on a physical device.

Naming Conventions: What to name a boolean variable?

Two issues to think about

  1. What is the scope of the variable (in other words: are you speaking about a local variable or a field?) ? A local variable has a narrower scope compared to a field. In particular, if the variable is used inside a relatively short method I would not care so much about its name. When the scope is large naming is more important.

  2. I think there's an inherent conflict in the way you treat this variable. On the one hand you say "false when an object is the last in a list", where on the other hand you also want to call it "inFront". An object that is (not) last in the list does not strike me as (not) inFront. This I would go with isLast.

jQuery set checkbox checked

.attr("checked",true)
.attr("checked",false)

will work.Make sure true and false are not inside quotes.

no debugging symbols found when using gdb

Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.)

In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.

Is it not possible to stringify an Error using JSON.stringify?

Make it serializable

// example error
let err = new Error('I errored')

// one liner converting Error into regular object that can be stringified
err = Object.getOwnPropertyNames(err).reduce((acc, key) => { acc[key] = err[key]; return acc; }, {})

If you want to send this object from child process, worker or though the network there's no need to stringify. It will be automatically stringified and parsed like any other normal object

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

How do I measure separate CPU core usage for a process?

you can use ps.
e.g. having python process with two busy threads on dual core CPU:

$ ps -p 29492 -L -o pid,tid,psr,pcpu
  PID   TID PSR %CPU
29492 29492   1  0.0
29492 29493   1 48.7
29492 29494   1 51.9

(PSR is CPU id the thread is currently assigned to)

you see that the threads are running on the same cpu core (because of GIL)

running the same python script in jython, we see, that the script is utilizing both cores (and there are many other service or whatever threads, which are almost idle):

$ ps -p 28671 -L -o pid,tid,psr,pcpu
  PID   TID PSR %CPU
28671 28671   1  0.0
28671 28672   0  4.4
28671 28673   0  0.6
28671 28674   0  0.5
28671 28675   0  2.3
28671 28676   0  0.0
28671 28677   1  0.0
28671 28678   1  0.0
28671 28679   0  4.6
28671 28680   0  4.4
28671 28681   1  0.0
28671 28682   1  0.0
28671 28721   1  0.0
28671 28729   0 88.6
28671 28730   1 88.5

you can process the output and calculate the total CPU for each CPU core.

Unfortunately, this approach does not seem to be 100% reliable, sometimes i see that in the first case, the two working threads are reported to be separated to each CPU core, or in the latter case, the two threads are reported to be on the same core..

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

How do you print in Sublime Text 2

UPDATE 2016: Somewhere between July 2015 and January 2016 the printing feature request that I wrote about in 2014 was removed. The original answer is below, with the relevant links changed to the latest working versions in the Web Archive:

Original 2014 Answer

Printing in Sublime Text is a feature that has been requested for about 4 years (as of 2014), with 1600+ supporting votes and 160+ comments in the discussion below. For something around 6000 feature requests this is in the top 5.

See the original, still open, feature request:

enter image description here

Judging from the feature request (still open with no official answer) it seems unlikely that printing will ever get implemented in version 3 (as others have suggested) or in any version at all.

The discussion below this feature request may give some insight on why printing is not supported and whether or not it has a chance to get supported in the future.

Maybe if more people vote or comment it will change in the future. (See Update 2016 below for an up-to-date list of feature requests)

Some workarounds were suggested, the most popular advices were to use some other editor for printing (eg. Brackets, Atom, gedit, Notepad++) or to use some 3rd party plugins that reportedly don't work well or at all.

In general there is a strong opposition to adding printing as a native feature of Sublime Text which for such a universal functionality among text editors seems surprising, but may nevertheless shed some light on this issue.

Meanwhile, there are many free editors that can print (in fact I cannot think of a single one that couldn't) so it is easy to use some other editor whenever a need for printing arises.

Update 2016

Since the feature request described above was removed (please comment if anyone knows why) here is an up-to-date list of some other places to find more info about printing in Sublime Text:

Since the original feature request #25170 was removed, you should vote and comment in the other feature requests about printing instead.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

Get battery level and state in Android

You can use this to get remaining charged in percentage.

private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }

How to convert std::string to LPCSTR?

These are Microsoft defined typedefs which correspond to:

LPCSTR: pointer to null terminated const string of char

LPSTR: pointer to null terminated char string of char (often a buffer is passed and used as an 'output' param)

LPCWSTR: pointer to null terminated string of const wchar_t

LPWSTR: pointer to null terminated string of wchar_t (often a buffer is passed and used as an 'output' param)

To "convert" a std::string to a LPCSTR depends on the exact context but usually calling .c_str() is sufficient.

This works.

void TakesString(LPCSTR param);

void f(const std::string& param)
{
    TakesString(param.c_str());
}

Note that you shouldn't attempt to do something like this.

LPCSTR GetString()
{
    std::string tmp("temporary");
    return tmp.c_str();
}

The buffer returned by .c_str() is owned by the std::string instance and will only be valid until the string is next modified or destroyed.

To convert a std::string to a LPWSTR is more complicated. Wanting an LPWSTR implies that you need a modifiable buffer and you also need to be sure that you understand what character encoding the std::string is using. If the std::string contains a string using the system default encoding (assuming windows, here), then you can find the length of the required wide character buffer and perform the transcoding using MultiByteToWideChar (a Win32 API function).

e.g.

void f(const std:string& instr)
{
    // Assumes std::string is encoded in the current Windows ANSI codepage
    int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);

    if (bufferlen == 0)
    {
        // Something went wrong. Perhaps, check GetLastError() and log.
        return;
    }

    // Allocate new LPWSTR - must deallocate it later
    LPWSTR widestr = new WCHAR[bufferlen + 1];

    ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);

    // Ensure wide string is null terminated
    widestr[bufferlen] = 0;

    // Do something with widestr

    delete[] widestr;
}

Javascript: best Singleton pattern

Why use a constructor and prototyping for a single object?

The above is equivalent to:

var earth= {
    someMethod: function () {
        if (console && console.log)
            console.log('some method');                             
    }
};
privateFunction1();
privateFunction2();

return {
    Person: Constructors.Person,
    PlanetEarth: earth
};

Windows could not start the Apache2 on Local Computer - problem

Remove apache from Control Panel and delete the apache folder from Program Files and restart the machine, then install apache again. This will solve the problem; if not do the following: Install IIS if not installed, then start IIS and stop it ... Using services start apache service... enjoy apache.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

This is related to compact option of Babel compiler, which commands to "not include superfluous whitespace characters and line terminators. When set to 'auto' compact is set to true on input sizes of >100KB." By default its value is "auto", so that is probably the reason you are getting the warning message. See Babel documentation.

You can change this option from Webpack using a query parameter. For example:

loaders: [
    { test: /\.js$/, loader: 'babel', query: {compact: false} }
]

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Automating running command on Linux from Windows using PuTTY

You can write a TCL script and establish SSH session to that Linux machine and issue commands automatically. Check http://wiki.tcl.tk/11542 for a short tutorial.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

Jquery to open Bootstrap v3 modal of remote url

If using @worldofjr answer in jQuery you are getting error:

e.relatedTarget.data is not a function

you should use:

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

Not that e.relatedTarget if wrapped by $(..)

I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.

Select option padding not working in chrome

I have a little trick for your problem. But for that you must use javascript. If you detected that the browser is Chrome insert "dummy" options between every options. Give a new class for those "dummy" options and make them disabled. The height of "dummy" options you can define with font-size property.

CSS:

option.dummy-option-for-chrome {
  font-size:2px;
  color:transparent;
}

Script:

function prepareHtml5Selects() {

  var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
  if(!is_chrome) return;

  $('select > option').each(function() {
    $('<option class="dummy-option-for-chrome" disabled></option>')
     .insertBefore($(this));
  });
  $('<option class="dummy-option-for-chrome" disabled></option>')
    .insertAfter($('select > option:last-child'));
}

C++ sorting and keeping track of indexes

Consider using std::multimap as suggested by @Ulrich Eckhardt. Just that the code could be made even simpler.

Given

std::vector<int> a = {5, 2, 1, 4, 3};  // a: 5 2 1 4 3

To sort in the mean time of insertion

std::multimap<int, std::size_t> mm;
for (std::size_t i = 0; i != a.size(); ++i)
    mm.insert({a[i], i});

To retrieve values and original indices

std::vector<int> b;
std::vector<std::size_t> c;
for (const auto & kv : mm) {
    b.push_back(kv.first);             // b: 1 2 3 4 5
    c.push_back(kv.second);            // c: 2 1 4 3 0
}

The reason to prefer a std::multimap to a std::map is to allow equal values in original vectors. Also please note that, unlike for std::map, operator[] is not defined for std::multimap.

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

Android TabLayout Android Design

Add this to the module build.gradle:

implementation 'com.android.support.constraint:constraint-layout:1.1.3'

implementation 'com.android.support:design:28.0.0'

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

PHP Using RegEx to get substring of a string

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

How to check whether a string is Base64 encoded or not

If you are using Java, you can actually use commons-codec library

import org.apache.commons.codec.binary.Base64;

String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());

[UPDATE 1] Deprecation Notice Use instead

Base64.isBase64(value);

   /**
     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
     * method treats whitespace as valid.
     *
     * @param arrayOctet
     *            byte array to test
     * @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
     *         {@code false}, otherwise
     * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
     */
    @Deprecated
    public static boolean isArrayByteBase64(final byte[] arrayOctet) {
        return isBase64(arrayOctet);
    }

Java: Get first item from a collection

Looks like that is the best way to do it:

String first = strs.iterator().next();

Great question... At first, it seems like an oversight for the Collection interface.

Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item) call, since the order isn't necessarily preserved.

While it might seem a bit wasteful, it might not be as bad as you think. The Iterator really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator object, but that is really the only overhead (not like copying all the elements).

For example, looking at the type returned by the ArrayList<String>.iterator() method, we see that it is ArrayList::Itr. This is an internal class that just accesses the elements of the list directly, rather than copying them.

Just be sure you check the return of iterator() since it may be empty or null depending on the implementation.

Test for existence of nested JavaScript object key

var a;

a = {
    b: {
        c: 'd'
    }
};

function isset (fn) {
    var value;
    try {
        value = fn();
    } catch (e) {
        value = undefined;
    } finally {
        return value !== undefined;
    }
};

// ES5
console.log(
    isset(function () { return a.b.c; }),
    isset(function () { return a.b.c.d.e.f; })
);

If you are coding in ES6 environment (or using 6to5) then you can take advantage of the arrow function syntax:

// ES6 using the arrow function
console.log(
    isset(() => a.b.c),
    isset(() => a.b.c.d.e.f)
);

Regarding the performance, there is no performance penalty for using try..catch block if the property is set. There is a performance impact if the property is unset.

Consider simply using _.has:

var object = { 'a': { 'b': { 'c': 3 } } };

_.has(object, 'a');
// ? true

_.has(object, 'a.b.c');
// ? true

_.has(object, ['a', 'b', 'c']);
// ? true

How open PowerShell as administrator from the run window

Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd for the search term.

image of win 10 start menu
(source: winaero.com)

Javascript: set label text

you are doing several things wrong. The explanation follows the corrected code:

<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>

Note the quotes around the id.

function checkLength(object, maxlength, label) {
    charsleft = (maxlength - object.value.length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        object.value = object.value.substring(0, maxlength-1);
    }

    // set the value of charsleft into the label
    document.getElementById(label).innerHTML = charsleft;
}

First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.

Let me know how that works out for you

EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:

var charsleft = ....

Eclipse interface icons very small on high resolution screen in Windows 8.1

For anyone seeing this after upgrading their Windows 10 (post April 2018 update), the DPI Scaling Override setting has moved into a dedicated window:

enter image description here

enter image description here

How do I force "git pull" to overwrite local files?

You could ignore that file with a file in your project base folder:

.gitignore

public/images/*

Then pull the changes and then remove that line from your gitignore file.

MySQL Orderby a number, Nulls last

Try using this query:

SELECT * FROM tablename
WHERE visible=1 
ORDER BY 
CASE WHEN position IS NULL THEN 1 ELSE 0 END ASC,id DESC

Adding dictionaries together, Python

>>> dic0 = {'dic0':0}
>>> dic1 = {'dic1':1}
>>> ndic = dict(dic0.items() + dic1.items())
>>> ndic
{'dic0': 0, 'dic1': 1}
>>>

Reimport a module in python while interactive

Another small point: If you used the import some_module as sm syntax, then you have to re-load the module with its aliased name (sm in this example):

>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

Username and password in command for git push

I used below format

git push https://username:[email protected]/file.git --all

and if your password or username contain @ replace it with %40

How to copy a directory structure but only include certain files (using windows batch files)

That's only two simple commands, but I wouldn't recommend this, unless the files that you DON'T need to copy are small. That's because this will copy ALL files and then remove the files that are not needed in the copy.

xcopy /E /I folder1 copy_of_folder1
for /F "tokens=1 delims=" %i in ('dir /B /S /A:-D copy_of_files ^| find /V "info.txt" ^| find /V "data.zip"') do del /Q "%i"

Sure, the second command is kind of long, but it works!

Also, this approach doesn't require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).

angular ng-repeat in reverse

Sorry for bringing this up after a year, but there is an new, easier solution, which works for Angular v1.3.0-rc.5 and later.

It is mentioned in the docs: "If no property is provided, (e.g. '+') then the array element itself is used to compare where sorting". So, the solution will be:

ng-repeat="friend in friends | orderBy:'-'" or

ng-repeat="friend in friends | orderBy:'+':true"

This solution seems to be better because it does not modify an array and does not require additional computational resources (at least in our code). I've read all existing answers and still prefer this one to them.

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

Going through a text file line by line in C

To read a line from a file, you should use the fgets function: It reads a string from the specified file up to either a newline character or EOF.

The use of sscanf in your code would not work at all, as you use filename as your format string for reading from line into a constant string literal %s.

The reason for SEGV is that you write into the non-allocated memory pointed to by line.

How do you count the number of occurrences of a certain substring in a SQL varchar?

I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.

CREATE FUNCTION [dbo].[CountOccurrency]
(
@Input nvarchar(max),
@Search nvarchar(max)
)
RETURNS int AS
BEGIN
    declare @SearhLength as int = len('-' + @Search + '-') -2;
    declare @conteinerIndex as int = 255;
    declare @conteiner as char(1) = char(@conteinerIndex);
    WHILE ((CHARINDEX(@conteiner, @Search)>0) and (@conteinerIndex>0))
    BEGIN
        set @conteinerIndex = @conteinerIndex-1;
        set @conteiner = char(@conteinerIndex);
    END;
    set @Input = @conteiner + @Input + @conteiner
    RETURN (len(@Input) - len(replace(@Input, @Search, ''))) / @SearhLength
END 

usage

select dbo.CountOccurrency('a,b,c,d ,', ',')

How do I create a readable diff of two spreadsheets using git diff?

Diff Doc may be what you're looking for.

  • Compare documents of MS Word (DOC, DOCX etc), Excel, PDF, Rich Text (RTF), Text, HTML, XML, PowerPoint, or Wordperfect and retain formatting
  • Choose any portion of any document (file) and compare it against any portion of the same or different document (file).

API Gateway CORS: no 'Access-Control-Allow-Origin' header

In my case, I was simply writing the fetch request URL wrong. On serverless.yml, you set cors to true:

register-downloadable-client:
    handler: fetch-downloadable-client-data/register.register
    events:
      - http:
          path: register-downloadable-client
          method: post
          integration: lambda
          cors: true
          stage: ${self:custom.stage}

and then on the lambda handler you send the headers, but if you make the fetch request wrong on the frontend, you're not going to get that header on the response and you're going to get this error. So, double check your request URL on the front.

memcpy() vs memmove()

The code given in the links http://clc-wiki.net/wiki/memcpy for memcpy seems to confuse me a bit, as it does not give the same output when I implemented it using the below example.

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[11] = "abcdefghij";

void *memcpyCustom(void *dest, const void *src, size_t n)
{
    char *dp = (char *)dest;
    const char *sp = (char *)src;
    while (n--)
        *dp++ = *sp++;
    return dest;
}

void *memmoveCustom(void *dest, const void *src, size_t n)
{
    unsigned char *pd = (unsigned char *)dest;
    const unsigned char *ps = (unsigned char *)src;
    if ( ps < pd )
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
    else
        while(n--)
            *pd++ = *ps++;
    return dest;
}

int main( void )
{
    printf( "The string: %s\n", str1 );
    memcpy( str1 + 1, str1, 9 );
    printf( "Actual memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memcpyCustom( str1 + 1, str1, 9 );
    printf( "Implemented memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memmoveCustom( str1 + 1, str1, 9 );
    printf( "Implemented memmove output: %s\n", str1 );
    getchar();
}

Output :

The string: abcdefghij
Actual memcpy output: aabcdefghi
Implemented memcpy output: aaaaaaaaaa
Implemented memmove output: aabcdefghi

But you can now understand why memmove will take care of overlapping issue.

how to convert from int to char*?

Converting our integer value to std::string so we can know how long (how long number of digits).

Then we creating char array length of string letter size +1, so we can copy our value to string then char array.

#include <string>

char* intToStr(int data) {
    std::string strData = std::to_string(data);

    char* temp = new char[strData.length() + 1];
    strcpy(temp, strData.c_str());

   return temp;
}

How to run single test method with phpunit?

I am late to the party though. But as personal I hate to write the whole line.

Instead, I use the following shortcuts in the .bash_profile file make sure to source .bash_profile the file after adding any new alias else it won't work.

alias pa="php artisan"
alias pu="vendor/bin/phpunit" 
alias puf="vendor/bin/phpunit --filter"

Usage:

puf function_name

puf filename

If you use Visual Studio Code you can use the following package to make your tests breeze.

Package Name: Better PHPUnit
Link: https://marketplace.visualstudio.com/items?itemName=calebporzio.better-phpunit

You can then set the keybinding in the settings. I use Command + T binding in my MAC.

Now once you place your cursor on any function and then use the key binding then it will automatically run that single test.

If you need to run the whole class then place the cursor on top of the class and then use the key binding.

If you have any other things then always tweek with the Terminal

Happy Coding!

How to clean old dependencies from maven repositories?

Just clean every content under .m2-->repository folder.When you build project all dependencies load here.

In your case may be your project earlier was using old version of any dependency and now version is upgraded.So better clean .m2 folder and build your project with mvn clean install.

Now dependencies with latest version modules will be downloaded in this folder.

Add horizontal scrollbar to html table

I couldn't get any of the above solutions to work. However, I found a hack:

_x000D_
_x000D_
body {_x000D_
  background-color: #ccc;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  width: 300px;_x000D_
  background-color: white;_x000D_
}_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
/* try removing the "hack" below to see how the table overflows the .body */_x000D_
.hack1 {_x000D_
  display: table;_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.hack2 {_x000D_
  display: table-cell;_x000D_
  overflow-x: auto;_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="hack1">_x000D_
    <div class="hack2">_x000D_
_x000D_
      <table>_x000D_
        <tr>_x000D_
          <td>table or other arbitrary content</td>_x000D_
          <td>that will cause your page to stretch</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>uncontrollably</td>_x000D_
          <td>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a countdown timer in Android?

Just Call below function by passing seconds and textview object

public void reverseTimer(int Seconds,final TextView tv){

    new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("TIME : " + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you are using AdonisJS (REST API, for instance), one way to avoid this is to define the response header this way:

response.safeHeader('Content-type', 'application/json')

how to clear JTable

You must remove the data from the TableModel used for the table.

If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

If you are using other TableModel, please check the documentation.

scp (secure copy) to ec2 instance without password

I've used below command to copy from local linux Centos 7 to AWS EC2.

scp -i user_key.pem file.txt [email protected]:/home/ec2-user

current/duration time of html5 video?

https://www.w3schools.com/tags/av_event_timeupdate.asp

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;
}

Boto3 to download all files from a S3 Bucket

I got the similar requirement and got help from reading few of the above solutions and across other websites, I have came up with below script, Just wanted to share if it might help anyone.

from boto3.session import Session
import os

def sync_s3_folder(access_key_id,secret_access_key,bucket_name,folder,destination_path):    
    session = Session(aws_access_key_id=access_key_id,aws_secret_access_key=secret_access_key)
    s3 = session.resource('s3')
    your_bucket = s3.Bucket(bucket_name)
    for s3_file in your_bucket.objects.all():
        if folder in s3_file.key:
            file=os.path.join(destination_path,s3_file.key.replace('/','\\'))
            if not os.path.exists(os.path.dirname(file)):
                os.makedirs(os.path.dirname(file))
            your_bucket.download_file(s3_file.key,file)
sync_s3_folder(access_key_id,secret_access_key,bucket_name,folder,destination_path)

Rails ActiveRecord date between

Rails 5.1 introduced a new date helper method all_day, see: https://github.com/rails/rails/pull/24930

>> Date.today.all_day
=> Wed, 26 Jul 2017 00:00:00 UTC +00:00..Wed, 26 Jul 2017 23:59:59 UTC +00:00

If you are using Rails 5.1, the query would look like:

Comment.where(created_at: @selected_date.all_day)

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

I had the same issue with Axios requests in a Vue-CLI App. On further checking in Network tab of Chrome, I found that the request URL of axios correctly had https but response 'location' header was http.

This was caused by nginx and I fixed it by adding these 2 lines to server config for nginx:

server {
    ...
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header Content-Security-Policy upgrade-insecure-requests;
    ...
}

Might be irrelevant but my Vue-CLI App was served under a subpath in nginx with config as:

location ^~ /admin {
        alias   /home/user/apps/app_admin/dist;
        index  index.html;
        try_files $uri $uri/ /index.html;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
}

Multiple axis line chart in excel

Best and Free ( maybe only) solution for this is google sheets. i don't know whether it plots as u expected or not but certainly you can draw multiple axes.

Regards

keerthan

Loading .sql files from within PHP

An updated solution of Plahcinski solution. Alternatively you can use fopen and fread for bigger files:

$fp = file('database.sql', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$query = '';
foreach ($fp as $line) {
    if ($line != '' && strpos($line, '--') === false) {
        $query .= $line;
        if (substr($query, -1) == ';') {
            mysql_query($query);
            $query = '';
        }
    }
}

How to escape double quotes in a title attribute

There is at least one situation where using single quotes will not work and that is if you are creating the markup "on the fly" from JavaScript. You use single quotes to contain the string and then any property in the markup can have double quotes for its value.

How to make a smaller RatingBar?

use the following code for small rating bar with onTouch event

enter code here


<RatingBar
            android:id="@+id/ratingBar"
            style="?android:ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:isIndicator="false"
            android:rating="4"
            android:stepSize="0.5" />

How to configure WAMP (localhost) to send email using Gmail?

i know in XAMPP i can configure sendmail.ini to forward local email. need to set

smtp_sever
smtp_port
auth_username
auth_password

this works when using my own server, not gmail so can't say for certain you'd have no problems

How to extract the decision rules from scikit-learn decision-tree?

Modified Zelazny7's code to fetch SQL from the decision tree.

# SQL from decision tree

def get_lineage(tree, feature_names):
     left      = tree.tree_.children_left
     right     = tree.tree_.children_right
     threshold = tree.tree_.threshold
     features  = [feature_names[i] for i in tree.tree_.feature]
     le='<='               
     g ='>'
     # get ids of child nodes
     idx = np.argwhere(left == -1)[:,0]     

     def recurse(left, right, child, lineage=None):          
          if lineage is None:
               lineage = [child]
          if child in left:
               parent = np.where(left == child)[0].item()
               split = 'l'
          else:
               parent = np.where(right == child)[0].item()
               split = 'r'
          lineage.append((parent, split, threshold[parent], features[parent]))
          if parent == 0:
               lineage.reverse()
               return lineage
          else:
               return recurse(left, right, parent, lineage)
     print 'case '
     for j,child in enumerate(idx):
        clause=' when '
        for node in recurse(left, right, child):
            if len(str(node))<3:
                continue
            i=node
            if i[1]=='l':  sign=le 
            else: sign=g
            clause=clause+i[3]+sign+str(i[2])+' and '
        clause=clause[:-4]+' then '+str(j)
        print clause
     print 'else 99 end as clusters'

How can I pass command-line arguments to a Perl program?

Alternatively, a sexier perlish way.....

my ($src, $dest) = @ARGV;

"Assumes" two values are passed. Extra code can verify the assumption is safe.

Change URL and redirect using jQuery

Try this...

$("#abc").attr("action", "/yourapp/" + temp).submit();

What it means:

Find a form with id "abc", change it's attribute named "action" and then submit it...

This works for me... !!!

HTML - how can I show tooltip ONLY when ellipsis is activated

This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:

$.when($('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
})).done(function(){ 
   setupTooltip();
});

If you didn't want to check for ellipsis css, you could simplify like:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
})).done(function(){ 
   setupTooltip();
});

I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.

If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:

$('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
});

Or without check for ellipsis:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
});

Adding to the classpath on OSX

Normally there's no need for that. First of all

echo $CLASSPATH

If there's something in there, you probably want to check Applications -> Utilites -> Java.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

This is a slight modification to Edens answer - which for me in chrome didn't catch the error. Although you'll still get an error in the console: "Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'sameorigin'." At least this will catch the error message and then you can deal with it.

 <iframe id="myframe" src="https://google.ca"></iframe>

 <script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

PostgreSQL: Which version of PostgreSQL am I running?

If you're using CLI and you're a postgres user, then you can do this:

psql -c "SELECT version();"


Possible output:

                                                         version                                                         
-------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 11.1 (Debian 11.1-3.pgdg80+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10+deb8u2) 4.9.2, 64-bit
(1 row)

how to read all files inside particular folder

Try this It is working for me..

The syntax is GetFiles(string path, string searchPattern);

var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");

This code will return all the files inside App_Data folder.

The second parameter . indicates the searchPattern with File Extension where the first * is for file name and second is for format of the file or File Extension like (*.png - any file name with .png format.

How to tell if string starts with a number with Python?

Use Regular Expressions, if you are going to somehow extend method's functionality.

How to find rows in one table that have no corresponding row in another table

You can also use exists, since sometimes it's faster than left join. You'd have to benchmark them to figure out which one you want to use.

select
    id
from
    tableA a
where
    not exists
    (select 1 from tableB b where b.id = a.id)

To show that exists can be more efficient than a left join, here's the execution plans of these queries in SQL Server 2008:

left join - total subtree cost: 1.09724:

left join

exists - total subtree cost: 1.07421:

exists

How to update a value in a json file and save it through node.js

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

will be...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

Button button = findViewById(R.id.button) always resolves to null in Android Studio

The button code should be moved to the PlaceholderFragment() class. There you will call the layout fragment_main.xml in the onCreateView method. Like so

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button buttonClick = (Button) view.findViewById(R.id.button);
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onButtonClick((Button) view);
        }

    });

    return view;
}

How to implement class constructor in Visual Basic?

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

curl POST format for CURLOPT_POSTFIELDS

In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-type header is automatically set to multipart/form-data.

Also, you don't have to create extra functions to build the query for your arrays, you already have that:

$query = http_build_query($data, '', '&');

Adobe Reader Command Line Reference

You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)

The FAQ notes that the use of the command line switches is unsupported.

To open a file it's:

AcroRd32.exe <filename>

The following switches are available:

  • /n - Launch a new instance of Reader even if one is already open
  • /s - Don't show the splash screen
  • /o - Don't show the open file dialog
  • /h - Open as a minimized window
  • /p <filename> - Open and go straight to the print dialog
  • /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

jQuery - Add active class and remove active from other element on click

Try this

$(document).ready(function() {
$(".tab").click(function () {
    $(".tab").removeClass("active");
    // $(".tab").addClass("active"); // instead of this do the below 
    $(this).addClass("active");   
});
});

when you are using $(".tab").addClass("active");, it targets all the elements with class name .tab. Instead when you use this it looks for the element which has an event, in your case the element which is clicked.

Hope this helps you.

How to add local .jar file dependency to build.gradle file?

You can try reusing your local Maven repository for Gradle:

  • Install the jar into your local Maven repository:

    mvn install:install-file -Dfile=utility.jar -DgroupId=com.company -DartifactId=utility -Dversion=0.0.1 -Dpackaging=jar

  • Check that you have the jar installed into your ~/.m2/ local Maven repository

  • Enable your local Maven repository in your build.gradle file:

    repositories {
      mavenCentral()  
      mavenLocal()  
    }
    
    dependencies {  
      implementation ("com.company:utility:0.0.1")  
    }
    
    • Now you should have the jar enabled for implementation in your project

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

Addressing localhost from a VirtualBox virtual machine

In virtual Box as said upper, you can add this line hosts file

10.0.2.2   outer

but to save it, if you don't have administrators right in your VM just move hosts file to desktop, then edit it to add the line 10.0....outer, save the file, and move to its original place.

Automatically capture output of last command into a variable using Bash?

If all you want is to rerun your last command and get the output, a simple bash variable would work:

LAST=`!!`

So then you can run your command on the output with:

yourCommand $LAST

This will spawn a new process and rerun your command, then give you the output. It sounds like what you would really like would be a bash history file for command output. This means you will need to capture the output that bash sends to your terminal. You could write something to watch the /dev or /proc necessary, but that's messy. You could also just create a "special pipe" between your term and bash with a tee command in the middle which redirects to your output file.

But both of those are kind of hacky solutions. I think the best thing would be terminator which is a more modern terminal with output logging. Just check your log file for the results of the last command. A bash variable similar to the above would make this even simpler.

Is it better to return null or empty collection?

I would argue that null isn't the same thing as an empty collection and you should choose which one best represents what you're returning. In most cases null is nothing (except in SQL). An empty collection is something, albeit an empty something.

If you have have to choose one or the other, I would say that you should tend towards an empty collection rather than null. But there are times when an empty collection isn't the same thing as a null value.

Conda version pip install -r requirements.txt --target ./lib

To create an environment named py37 with python 3.7, using the channel conda-forge and a list of packages:

conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate

Flags explained:

  • -y: Do not ask for confirmation.
  • --force-reinstall: Install the package even if it already exists.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

The ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.

Alternatively you can create an environment.yml file instead of requirements.txt:

name: py37
channels:
  - conda-forge
dependencies:
  - python=3.7
  - numpy=1.9.*
  - pandas

Use this command to list the environments you have:

conda info --envs

Use this command to remove the environment:

conda env remove -n py37

Constants in Objective-C

If you want something like global constants; a quick an dirty way is to put the constant declarations into the pch file.

Cleanest way to write retry logic?

You should try Polly. It's a .NET library written by me that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

Example

Policy
    .Handle<SqlException>(ex => ex.Number == 1205)
    .Or<ArgumentException>(ex => ex.ParamName == "example")
    .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(3))
    .Execute(() => DoSomething());

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

Int or Number DataType for DataAnnotation validation attribute

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
    options.rules.mustbeinteger = {};
    options.messages["mustbeinteger"] = options.message;
});

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

SQL Case Expression Syntax?

Oracle syntax from the 11g Documentation:

CASE { simple_case_expression | searched_case_expression }
     [ else_clause ]
     END

simple_case_expression

expr { WHEN comparison_expr THEN return_expr }...

searched_case_expression

{ WHEN condition THEN return_expr }...

else_clause

ELSE else_expr

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Java NIO: What does IOException: Broken pipe mean?

Broken pipe means you wrote to a connection that is already closed by the other end.

isConnected() does not detect this condition. Only a write does.

is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()

It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

forEach is not a function error with JavaScript array

parent.children will return a node list list, technically a html Collection. That is an array like object, but not an array, so you cannot call array functions over it directly. At this context you can use Array.from() to convert that into a real array,

Array.from(parent.children).forEach(child => {
  console.log(child)
})