Programs & Examples On #Sonicmq

Understanding string reversal via slicing

It's basic step notation, consider the functionality of:

a[2:4:2]

What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.

Find if variable is divisible by 2

Please write the following code in your console:

var isEven = function(deep) {

  if (deep % 2 === 0) {
        return true;  
    }
    else {
        return false;    
    }
};
isEven(44);

Please Note: It will return true, if the entered number is even otherwise false.

Using Mockito to stub and execute methods for testing

So, the idea of mocking the class under test is anathima to testing practice. You should NOT do this. Because you have done so, your test is entering Mockito's mocking classes not your class under test.

Spying will also not work because this only provides a wrapper / proxy around the spied class. Once execution is inside the class it will not go through the proxy and therefore not hit the spy. UPDATE: although I believe this to be true of Spring proxies it appears to not be true of Mockito spies. I set up a scenario where method m1() calls m2(). I spy the object and stub m2() to doNothing. When I invoke m1() in my test, m2() of the class is not reached. Mockito invokes the stub. So using a spy to accomplish what is being asked is possible. However, I would reiterate that I would consider it bad practice (IMHO).

You should mock all the classes on which the class under test depends. This will allow you to control the behavior of the methods invoked by the method under test in that you control the class that those methods invoke.

If your class creates instances of other classes, consider using factories.

IsNumeric function in c#

Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:

public bool IsNumeric(string val) => int.TryParse(val, out int result);

Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.

Remove row lines in twitter bootstrap

The other way around, if you have problems ADDING the lines to your panel dont forget to add the to your TABLE. By default (http://getbootstrap.com/components/#panels), it is suppose to add the line but It helped me to add the tag so now the row lines are shown.

The following example "probably" wont display the lines between rows:

<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel heading</div>
    <!-- Table -->
    <table class="table">
        <tr><td> Hi 1! </td></tr>
        <tr><td> Hi 2! </td></tr>
    </table>
</div>

The following example WILL display the lines between rows:

<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel heading</div>
    <!-- Table -->
    <table class="table">
        <thead></thead>
        <tr><td> Hi 1! </td></tr>
        <tr><td> Hi 2! </td></tr>
    </table>
</div>

How to add 'libs' folder in Android Studio?

also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib

SQL Not Like Statement not working

If WPP.COMMENT contains NULL, the condition will not match.

This query:

SELECT  1
WHERE   NULL NOT LIKE '%test%'

will return nothing.

On a NULL column, both LIKE and NOT LIKE against any search string will return NULL.

Could you please post relevant values of a row which in your opinion should be returned but it isn't?

What is the garbage collector in Java?

To put it in the most simple terms that even a non-programmer can understand, when a program processes data it creates intermediate data and storage space (variables, arrays, certain object metadata etc.) for that data.

When these objects are accessed across functions or over a certain size, they are allocated from a central heap. Then when they are no long needed, they need to be cleaned up.

There are some very good articles online about how this works, so I'll just cover the very basic definition.

The GC is basically the function that does this cleanup. To do this is clears table entries that aren't referenced by any active objects, effectively deleting the objects, than copies and compacts the memory. It's a little more complicated than this, but you get the idea.

The big problem is some parts this process often requires the entire Java VM to require to be stopped temporarily to take place, as well as this entire process being very processor and memory bandwidth intensive. The various options as of GCs and tuning options for each one are designed to balance these various issues with the whole GC process.

React navigation goBack() and update parent state

With React Navigation v5, just use the navigate method. From the docs:

To achieve this, you can use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back

Full example:

import React from 'react';
import { StyleSheet, Button, Text, View } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function ScreenA ({ navigation, route }) {
  const { params } = route;

  return (
    <View style={styles.container}>
      <Text>Params: {JSON.stringify(params)}</Text>
      <Button title='Go to B' onPress={() => navigation.navigate('B')} />
    </View>
  );
}

function ScreenB ({ navigation }) {
  return (
    <View style={styles.container}>
      <Button title='Go to A'
        onPress={() => {
          navigation.navigate('A', { data: 'Something' })
        }}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator mode="modal">
        <Stack.Screen name="A" component={ScreenA} />
        <Stack.Screen name="B" component={ScreenB} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

c++ array - expression must have a constant value

When creating an array like that, its size must be constant. If you want a dynamically sized array, you need to allocate memory for it on the heap and you'll also need to free it with delete when you're done:

//allocate the array
int** arr = new int*[row];
for(int i = 0; i < row; i++)
    arr[i] = new int[col];

// use the array

//deallocate the array
for(int i = 0; i < row; i++)
    delete[] arr[i];
delete[] arr;

If you want a fixed size, then they must be declared const:

const int row = 8;
const int col = 8;
int arr[row][col];

Also,

int [row][col];

doesn't even provide a variable name.

End-line characters from lines read from text file, using Python

Simple. Use splitlines()

L = open("myFile.txt", "r").read().splitlines();
for line in L: 
    process(line) # this 'line' will not have '\n' character at the end

jquery input select all on focus

Try using click instead of focus. It seems to work for both mouse and key events (at least on Chrome/Mac):

jQuery < version 1.7:

$("input[type='text']").click(function () {
   $(this).select();
});

jQuery version 1.7+:

$("input[type='text']").on("click", function () {
   $(this).select();
});

Here is a demo

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Simply by adding below text in the httpd.conf file will solve this issue.

Header set Access-Control-Allow-Origin "*"

Java Array Sort descending?

For discussions above, here is an easy example to sort the primitive arrays in descending order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

Output:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

How can I disable the bootstrap hover color for links?

I am not a Bootstrap expert, but it sounds to me that you should define a new class called nohover (or something equivalent) then in your link code add the class as the last attribute value:

<a class="green nohover" href="#">green text</a>
<a class="yellow nohover" href="#">yellow text</a>

Then in your Bootstrap LESS/CSS file, define nohover (using the JSFiddle example above):

a:hover { color: red  }
/* Green */
a.green  { color: green; }
/* Yellow */
a.yellow  { color: yellow; }
a.nohover:hover { color: none;  }

Forked the JSFiddle here: http://jsfiddle.net/9rpkq/

Polymorphism vs Overriding vs Overloading

import java.io.IOException;

class Super {

    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName() + " - I'm parent");
        return null;
    }

}

class SubOne extends Super {

    @Override
    protected Super getClassName(Super s)  {
        System.out.println(this.getClass().getSimpleName() + " - I'm Perfect Overriding");
        return null;
    }

}

class SubTwo extends Super {

    @Override
    protected Super getClassName(Super s) throws NullPointerException {
        System.out.println(this.getClass().getSimpleName() + " - I'm Overriding and Throwing Runtime Exception");
        return null;
    }

}

class SubThree extends Super {

    @Override
    protected SubThree getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Returning SubClass Type");
        return null;
    }

}

class SubFour extends Super {

    @Override
    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Throwing Narrower Exception ");
        return null;
    }

}

class SubFive extends Super {

    @Override
    public Super getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and have broader Access ");
        return null;
    }

}

class SubSix extends Super {

    public Super getClassName(Super s, String ol) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading ");
        return null;
    }

}

class SubSeven extends Super {

    public Super getClassName(SubSeven s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading because Method signature (Argument) changed.");
        return null;
    }

}

public class Test{

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

        System.out.println("Overriding\n");

        Super s1 = new SubOne(); s1.getClassName(null);

        Super s2 = new SubTwo(); s2.getClassName(null);

        Super s3 = new SubThree(); s3.getClassName(null);

        Super s4 = new SubFour(); s4.getClassName(null);

        Super s5 = new SubFive(); s5.getClassName(null);

        System.out.println("Overloading\n");

        SubSix s6 = new SubSix(); s6.getClassName(null, null);

        s6 = new SubSix(); s6.getClassName(null);

        SubSeven s7 = new SubSeven(); s7.getClassName(s7);

        s7 = new SubSeven(); s7.getClassName(new Super());

    }
}

How to use template module with different set of variables?

You can do this very easy, look my Supervisor recipe:

- name: Setup Supervisor jobs files
  template:
    src: job.conf.j2
    dest: "/etc/supervisor/conf.d/{{ item.job }}.conf"
    owner: root
    group: root
    force: yes
    mode: 0644
  with_items:
    - { job: bender, arguments: "-m 64", instances: 3 }
    - { job: mailer, arguments: "-m 1024", instances: 2 }
  notify: Ensure Supervisor is restarted

job.conf.j2:

[program:{{ item.job }}]
user=vagrant
command=/usr/share/nginx/vhosts/parclick.com/app/console rabbitmq:consumer {{ item.arguments }} {{ item.job }} -e prod
process_name=%(program_name)s_%(process_num)02d
numprocs={{ item.instances }}
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisor/{{ item.job }}.stderr.log
stdout_logfile=/var/log/supervisor/{{ item.job }}.stdout.log

Output:

TASK [Supervisor : Setup Supervisor jobs files] ********************************
changed: [loc.parclick.com] => (item={u'instances': 3, u'job': u'bender', u'arguments': u'-m 64'})
changed: [loc.parclick.com] => (item={u'instances': 2, u'job': u'mailer', u'arguments': u'-m 1024'})

Enjoy!

How to wait until an element is present in Selenium?

Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:

$("#elementId").shouldBe(visible);

Here is a sample project for testing Google search: https://github.com/selenide-examples/google

Installing specific package versions with pip

TL;DR:

  • pip install -Iv (i.e. pip install -Iv MySQL_python==1.2.2)

First, I see two issues with what you're trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2

However, you'll soon find out that this doesn't work. If you look at pip's installation log, or if you do a pip install -Iv MySQL_python==1.2.2 you'll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2

The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net's recent upgrade and PyPI's stale URL.

So to properly install the driver, you can follow these steps:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

phpMyAdmin allow remote users

Just comment all lines in first Directory. Or you can remove these lines, but better to keep in case later you want to add some restrictions, you will uncomment.

#<Directory /usr/share/phpMyAdmin/>
#   <IfModule mod_authz_core.c>
#     # Apache 2.4
#     <RequireAny>
#       Require ip 127.0.0.1
#       Require ip ::1
#     </RequireAny>
#   </IfModule>
#   <IfModule !mod_authz_core.c>
#     # Apache 2.2
#     Order Deny,Allow
#     Deny from All
#     Allow from 127.0.0.1
#     Allow from ::1
#   </IfModule>
#</Directory>

Convert string to nullable type (int, double, etc...)

I wrote this generic type converter. It works with Nullable and standard values, converting between all convertible types - not just string. It handles all sorts of scenarios that you'd expect (default values, null values, other values, etc...)

I've been using this for about a year in dozens of production programs, so it should be pretty solid.

    public static T To<T>(this IConvertible obj)
    {
        Type t = typeof(T);

        if (t.IsGenericType
            && (t.GetGenericTypeDefinition() == typeof(Nullable<>)))
        {
            if (obj == null)
            {
                return (T)(object)null;
            }
            else
            {
                return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(t));
            }
        }
        else
        {
            return (T)Convert.ChangeType(obj, t);
        }
    }

    public static T ToOrDefault<T>
                 (this IConvertible obj)
    {
        try
        {
            return To<T>(obj);
        }
        catch
        {
            return default(T);
        }
    }

    public static bool ToOrDefault<T>
                        (this IConvertible obj,
                         out T newObj)
    {
        try
        {
            newObj = To<T>(obj);
            return true;
        }
        catch
        {
            newObj = default(T);
            return false;
        }
    }

    public static T ToOrOther<T>
                           (this IConvertible obj,
                           T other)
    {
        try
        {
            return To<T>(obj);
        }
        catch
        {
            return other;
        }
    }

    public static bool ToOrOther<T>
                             (this IConvertible obj,
                             out T newObj,
                             T other)
    {
        try
        {
            newObj = To<T>(obj);
            return true;
        }
        catch
        {
            newObj = other;
            return false;
        }
    }

    public static T ToOrNull<T>
                          (this IConvertible obj)
                          where T : class
    {
        try
        {
            return To<T>(obj);
        }
        catch
        {
            return null;
        }
    }

    public static bool ToOrNull<T>
                      (this IConvertible obj,
                      out T newObj)
                      where T : class
    {
        try
        {
            newObj = To<T>(obj);
            return true;
        }
        catch
        {
            newObj = null;
            return false;
        }
    }

java - iterating a linked list

iterate LinkedList by using iterator

LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);

Iterator<String>  itr = linkedList.iterator();
 while (itr.hasNext()) {
 System.out.println(“Element is =”+itr.next());

 }

Reference : Java Linkedlist Examples

CKEditor instance already exists

To support dynamic (Ajax) loading of forms (without page refreshes between) which contain textareas with the same (same form is called again) or different ID's (previously unloaded form) and convert them to CKEditor elements I did the following (using the JQuery adapter):

After the page has finished every Ajax call that delivers a textarea to be converted, I make a call to the following function:

setupCKeditor()

This looks like this (it assumes your textareas to be converted to RTE's have class="yourCKClass"):

    /* Turns textAreas into TinyMCE Rich Text Editors where
 * class: tinymce applied to textarea.
 */
function setupCKeditor(){

    // define editor configuration      
    var config = {skin : 'kama'};

    // Remove and recreate any existing CKEditor instances
    var count = 0;
    if (CKEDITOR.instances !== 'undefined') {
        for(var i in CKEDITOR.instances) {

            var oEditor   = CKEDITOR.instances[i];
            var editorName = oEditor.name;

             // Get the editor data.
            var data = $('#'+editorName).val();

            // Check if current instance in loop is the same as the textarea on current page
            if ($('textarea.yourCKClass').attr('id') == editorName) {
                if(CKEDITOR.instances[editorName]) {

                    // delete and recreate the editor
                    delete CKEDITOR.instances[editorName];
                    $('#'+editorName).ckeditor(function() { },config);
                    count++;

                }
            }   


        }
    }

    // If no editor's exist in the DOM, create any that are needed.             
    if (count == 0){

        $('textarea.yourCKClass').each( function(index) {

                var editorName = $(this).attr('id');
                $('#'+editorName).ckeditor(function() { $('#'+editorName).val(data); },config);

            });

    }


}

I should mention that the line:

$('#'+editorName).ckeditor(function() { $('#'+editorName).val(data); },config);

could (and should) be simply:

$('#'+editorName).ckeditor(function() { },config);

however I found that the editor would often show the correct content for a second after loading and them empty the editor of the desired content. So that line with the callback code forces the CKEditor content to be the same as the originating textarea content. Causes a flicker when used. If you can avoid using it, do so..

Package structure for a Java project?

The way I usually organise is
- src
        - main
                - java
                - groovy
                - resources
        - test
                - java
                - groovy
- lib
- build
        - test 
                - reports
                - classes
- doc

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

Convert string (without any separator) to list

You can use str.translate, you just have to give it the right arguments:

>>> dels=''.join(chr(x) for x in range(256) if not chr(x).isdigit())
>>> '+1-617-555-1212'.translate(None, dels)
'16175551212'

N.b.: This won't work with unicode strings in Python2, or at all in Python3. For those environments, you can create a custom class to pass to unicode.translate:

>>> class C:
...    def __getitem__(self, i):
...       if unichr(i).isdigit():
...          return i
... 
>>> u'+1-617.555/1212'.translate(C())
u'16175551212'

This works with non-ASCII digits, too:

>>> print u'+\u00b9-\uff1617.555/1212'.translate(C()).encode('utf-8')
¹6175551212

Open links in new window using AngularJS

@m59 Directives will work for ng-bind-html you just need to wait for $viewContentLoaded to finish

app.directive('targetBlank', function($timeout) {
  return function($scope, element) {
    $scope.initializeTarget = function() {
      return $scope.$on('$viewContentLoaded', $timeout(function() {
        var elems;
        elems = element.prop('tagName') === 'A' ? element : element.find('a');
        elems.attr('target', '_blank');
      }));
    };
    return $scope.initializeTarget();

  };
});

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

Bootstrap Modal sitting behind backdrop

I'm wary of moving the modal content outside its original context: other JS or styles might depend on that context.

However, I doubt there are any scripts or styles that require a specific context for the backdrop.

So my solution is to move the backdrop adjacent to the modal content, forcing it into the same stacking context:

$(document).on('shown.bs.modal', '.modal', function () {
    $('.modal-backdrop').before($(this));
});

It's only a slight deviation from jacoswarts' solution, so thanks for the inspiration!

React this.setState is not a function

You no need to assign this to a local variable if you use arrow function. Arrow functions takes binding automatically and you can stay away with scope related issues.

Below code explains how to use arrow function in different scenarios

componentDidMount = () => {

    VK.init(() => {
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},(data) => {
            if(data.response){
                that.setState({ //this available here and you can do setState
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, () => {
        console.info("API initialisation failed");

    }, '5.34');
 },

C# - How to convert string to char?

char[] myChar = theString.ToCharArray();

Textarea onchange detection

Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.

<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea> 
<div><span id="spn"></span> characters left</div>

function check(){
    var string = document.getElementById("url").value
    var left = 15 - string.length;
    document.getElementById("spn").innerHTML = left;
}

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

PHP form send email to multiple recipients

You can add your receipients to $email_to variable separating them with comma (,). Or you can add new fields to headers, namely CC: or BCC: and put your receipients there. BCC is most recommended

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

vertical align middle in <div>

_x000D_
_x000D_
.container { 
  height: 200px;
  position: relative;
  border: 3px solid green; 
}

.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
_x000D_
<h2>Centering Div inside Div, horizontally and vertically without table</h2>
<p>1. Positioning and the transform property to vertically and horizontally center</p>
<p>2. CSS Layout - Horizontal & Vertical Align</p>

<div class="container">
  <div class="center">
    <p>I am vertically and horizontally centered.</p>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How to easily consume a web service from PHP

Well, those features are specific to a tool that you are using for development in those languages.

You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.

For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

How do I create a custom Error in JavaScript?

Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.

function NotImplementedError(message = "") {
    this.name = "NotImplementedError";
    this.message = message;
}
NotImplementedError.prototype = Error.prototype;

However, I would just throw your own object and just check the name property.

throw {name : "NotImplementedError", message : "too lazy to implement"}; 

Edit based on comments

After looking at the comments and trying to remember why I would assign prototype to Error.prototype instead of new Error() like Nicholas Zakas did in his article, I created a jsFiddle with the code below:

_x000D_
_x000D_
function NotImplementedError(message = "") {
  this.name = "NotImplementedError";
  this.message = message;
}
NotImplementedError.prototype = Error.prototype;

function NotImplementedError2(message = "") {
  this.message = message;
}
NotImplementedError2.prototype = new Error();

try {
  var e = new NotImplementedError("NotImplementedError message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}

try {
  var e = new NotImplementedError2("NotImplementedError2 message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError2 = " + (ex1 instanceof NotImplementedError2));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}
_x000D_
_x000D_
_x000D_

The console output was this.

undefined
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message
Error
    at window.onload (http://fiddle.jshell.net/MwMEJ/show/:29:34)
ex1 instanceof NotImplementedError2 = true
ex1 instanceof Error = true
ex1.name = Error
ex1.message = NotImplementedError2 message

This confirmes the "problem" I ran into was the stack property of the error was the line number where new Error() was created, and not where the throw e occurred. However, that may be better that having the side effect of a NotImplementedError.prototype.name = "NotImplementedError" line affecting the Error object.

Also, notice with NotImplementedError2, when I don't set the .name explicitly, it is equal to "Error". However, as mentioned in the comments, because that version sets prototype to new Error(), I could set NotImplementedError2.prototype.name = "NotImplementedError2" and be OK.

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . " +10 hours"));

What exactly is an instance in Java?

"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"

Class in the library called Nacho

variable Libre to hold the "instance" that will change

Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)

I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!

Could not autowire field:RestTemplate in Spring boot application

  • You must add @Bean public RestTemplate restTemplate(RestTemplateBuilder builder){ return builder.build(); }

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

Creating layout constraints programmatically

Please also note that from iOS9 we can define constraints programmatically "more concise, and easier to read" using subclasses of the new helper class NSLayoutAnchor.

An example from the doc:

[self.cancelButton.leadingAnchor constraintEqualToAnchor:self.saveButton.trailingAnchor constant: 8.0].active = true;

Spring mvc @PathVariable

If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.

   @PostMapping(value = "/item/{id}/{method}")
    public String getForm(@PathVariable("id") String itemId ,  
        @PathVariable("method") String methodCall , Model model){

     if(methodCall.equals("create")){
            //logic
      }
     if(methodCall.equals("update")){
            //logic
      }

      return "path to your form";
    }

jQuery if Element has an ID?

You can do

document.getElementById(id) or 
$(id).length > 0

SyntaxError: "can't assign to function call"

You have done it backwards, it should be:

amount = invest(amount,top_company(5,year,year+1),year)

Laravel Unknown Column 'updated_at'

In the model, write the below code;

public $timestamps = false;

This would work.

Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.

Read file As String

Reworked the method set originating from -> the accepted answer

@JaredRummler An answer to your comment:

Read file As String

Won't this add an extra new line at the end of the string?

To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine

public static String convertStreamToString(InputStream is) throws IOException {
   // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    Boolean firstLine = true;
    while ((line = reader.readLine()) != null) {
        if(firstLine){
            sb.append(line);
            firstLine = false;
        } else {
            sb.append("\n").append(line);
        }
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws IOException {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}

How to create a temporary directory and get the path / file name in Python

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

Which MIME type to use for a binary file that's specific to my program?

mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,

If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),

if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319

if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:

if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way

:)

Python: Best way to add to sys.path relative to the current running script

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

Configure DataSource programmatically in Spring Boot

You can use DataSourceBuilder if you are using jdbc starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

In my case I have properties starting with datasource.postgres prefix.

E.g

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .build();
}

If it is not feasible for you, then you can use

@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .username("")
        .password("")
        .url("")
        .driverClassName("")
        .build();
}

identifier "string" undefined?

Perhaps you wanted to #include<string>, not <string.h>. std::string also needs a namespace qualification, or an explicit using directive.

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

How do I activate a Spring Boot profile when running from IntelliJ?

Try this. Edit your build.gradle file as followed.

ext { profile = project.hasProperty('profile') ? project['profile'] : 'local' }

How to convert string to boolean php

In PHP you simply can convert a value to a boolean by using double not operator (!!):

var_dump(!! true);     // true
var_dump(!! "Hello");  // true
var_dump(!! 1);        // true
var_dump(!! [1, 2]);   // true
var_dump(!! false);    // false
var_dump(!! null);     // false
var_dump(!! []);       // false
var_dump(!! 0);        // false
var_dump(!! '');       // false

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

My 5 cents.

This problem started after a solution wide clean.

I managed to get the problem to go away by setting the Active Solution configuration in: Build -> Configuration manager to release. Then build and set it back to debug again. The build succeeded after that.

Can you style an html radio button to look like a checkbox?

I don't think you can make a control look like anything other than a control with CSS.

Your best bet it to make a PRINT button goes to a new page with a graphic in place of the selected radio button, then do a window.print() from there.

How to set Navigation Drawer to be opened from right to left

I have solved this problem by changing the gravity of the navigationview

android:layout_gravity

to end instead of start

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/activity_drawer" />

It worked for me.

Trigger function when date is selected with jQuery UI datepicker

$(".datepicker").datepicker().on("changeDate", function(e) {
   console.log("Date changed: ", e.date);
});

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Using str_replace so that it only acts on the first match?

Unfortunately, I don't know of any PHP function which can do this.
You can roll your own fairly easily like this:

function replace_first($find, $replace, $subject) {
    // stolen from the comments at PHP.net/str_replace
    // Splits $subject into an array of 2 items by $find,
    // and then joins the array with $replace
    return implode($replace, explode($find, $subject, 2));
}

How do I remove lines between ListViews on Android?

   <ListView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/list"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:divider="@null"
  android:dividerHeight="0dp"/>

MySQL Data Source not appearing in Visual Studio

I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.

Postgresql: password authentication failed for user "postgres"

This was frustrating, most of the above answers are correct but they fail to mention you have to restart the database service before the changes in the pg_hba.conf file will take affect.

so if you make the changes as mentioned above:

local all postgres ident

then restart as root ( on centos its something like service service postgresql-9.2 restart ) now you should be able to access the db as the user postgres

$psql
psql (9.2.4)
Type "help" for help.

postgres=# 

Hope this adds info for new postgres users

Removing html5 required attribute with jQuery

Even though the ID selector is the simplest, you can also use the name selector as below:

$('[name='submitted[first_name]']').removeAttr('required');

For more see: https://api.jquery.com/attribute-equals-selector/

Working with time DURATION, not time of day

The best way I found to resolve this issue was by using a combination of the above. All my cells were entered as a Custom Format to only show "HH:MM" - if I entered in "4:06" (being 4 minutes and 6 seconds) the field would show the numbers I entered correctly - but the data itself would represent HH:MM in the background.

Fortunately time is based on factors of 60 (60 seconds = 60 minutes). So 7H:15M / 60 = 7M:15S - I hope you can see where this is going. Accordingly, if I take my 4:06 and divide by 60 when working with the data (eg. to total up my total time or average time across 100 cells I would use the normal SUM or AVERAGE formulas and then divide by 60 in the formula.

Example =(SUM(A1:A5))/60. If my data was across the 5 time tracking fields was the 4:06, 3:15, 9:12, 2:54, 7:38 (representing MM:SS for us, but the data in the background is actually HH:MM) then when I work out the sum of those 5 fields are, what I want should be 27M:05S but what shows instead is 1D:03H:05M:00S. As mentioned above, 1D:3H:5M divided by 60 = 27M:5S ... which is the sum I am looking for.

Further examples of this are: =(SUM(G:G))/60 and =(AVERAGE(B2:B90)/60) and =MIN(C:C) (this is a direct check so no /60 needed here!).

Note that your "formula" or "calculation" fields (average, total time, etc) MUST have the custom format of MM:SS once you have divided by 60 as Excel's default thinking is in HH:MM (hence this issue). Your data fields where you are entering in your times should need to be changed from "General" or "Number" format to the custom format of HH:MM.

This process is still a little bit cumbersome to use - but it does mean that your data entry is still entered in very easy and is "correctly" displayed on screen as 4:06 (which most people would view as minutes:seconds when under a "Minutes" header). Generally there will only be a couple of fields needing to be used for formulas such as "best time", "average time", "total time" etc when tracking times and they will not usually be changed once the formula is entered so this will be a "one off" process - I use this for my call tracking sheet at work to track "average call", "total call time for day".

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

Getting a POST variable

Use the

Request.Form[]

for POST variables,

Request.QueryString[]

for GET.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Counting lines, words, and characters within a text file using Python

file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
    data = f.read()
    line = data.splitlines()
    words = data.split()
    spaces = data.split(" ")
    charc = (len(data) - len(spaces))

    print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))

I tried this code & it works as expected.

How to clear the Entry widget after a button is pressed in Tkinter?

After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height=42, width=42)
        self.entry = tk.Entry(self)
        self.entry.focus()
        self.entry.pack()
        self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
        self.clear_button.pack()

    def clear_text(self):
        self.entry.delete(0, 'end')

def main():
    root = tk.Tk()
    App(root).pack(expand=True, fill='both')
    root.mainloop()

if __name__ == "__main__":
    main()

REST API error code 500 handling

Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.

Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.

To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.

It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.

I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.

It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

How do I get the parent directory in Python?

If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:

os.path.split(os.path.dirname(currentDir))[1]

i.e. with a currentDir value of /home/user/path/to/myfile/file.ext

The above command will return:

myfile

How to sort pandas data frame using values from several columns?

Use of sort can result in warning message. See github discussion. So you might wanna use sort_values, docs here

Then your code can look like this:

df = df.sort_values(by=['c1','c2'], ascending=[False,True])

Can I access constants in settings.py from templates in Django?

I improved chrisdew's answer (to create your own tag) a little bit.

First, create the file yourapp/templatetags/value_from_settings.py in which you define your own new tag value_from_settings:

from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings

register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
  bits = token.split_contents()
  if len(bits) < 2:
    raise TemplateSyntaxError("'%s' takes at least one " \
      "argument (settings constant to retrieve)" % bits[0])
  settingsvar = bits[1]
  settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
  asvar = None
  bits = bits[2:]
  if len(bits) >= 2 and bits[-2] == 'as':
    asvar = bits[-1]
    bits = bits[:-2]
  if len(bits):
    raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
      "the arguments '%s'" % ", ".join(bits))
  return ValueFromSettings(settingsvar, asvar)

class ValueFromSettings(Node):
  def __init__(self, settingsvar, asvar):
    self.arg = Variable(settingsvar)
    self.asvar = asvar
  def render(self, context):
    ret_val = getattr(settings,str(self.arg))
    if self.asvar:
      context[self.asvar] = ret_val
      return ''
    else:
      return ret_val

You can use this tag in your Template via:

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}

or via

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}

The advantage of the as ... notation is that this makes it easy to use in blocktrans blocks via a simple {{my_fqdn}}.

How can I enable cURL for an installed Ubuntu LAMP stack?

From Install Curl Extension for PHP in Ubuntu:

sudo apt-get install php5-curl

After installing libcurl, you should restart the web server with one of the following commands,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

Convert XLS to CSV on command line

How about with PowerShell?

Code should be looks like this, not tested though

$xlCSV = 6
$Excel = New-Object -Com Excel.Application 
$Excel.visible = $False 
$Excel.displayalerts=$False 
$WorkBook = $Excel.Workbooks.Open("YOUDOC.XLS") 
$Workbook.SaveAs("YOURDOC.csv",$xlCSV) 
$Excel.quit()

Here is a post explaining how to use it

How Can I Use Windows PowerShell to Automate Microsoft Excel?

Find and replace Android studio

Use ctrl+R or cmd+R in OSX

Inline functions in C#?

Yes Exactly, the only distinction is the fact it returns a value.

Simplification (not using expressions):

List<T>.ForEach Takes an action, it doesn't expect a return result.

So an Action<T> delegate would suffice.. say:

List<T>.ForEach(param => Console.WriteLine(param));

is the same as saying:

List<T>.ForEach(delegate(T param) { Console.WriteLine(param); });

the difference is that the param type and delegate decleration are inferred by usage and the braces aren't required on a simple inline method.

Where as

List<T>.Where Takes a function, expecting a result.

So an Function<T, bool> would be expected:

List<T>.Where(param => param.Value == SomeExpectedComparison);

which is the same as:

List<T>.Where(delegate(T param) { return param.Value == SomeExpectedComparison; });

You can also declare these methods inline and asign them to variables IE:

Action myAction = () => Console.WriteLine("I'm doing something Nifty!");

myAction();

or

Function<object, string> myFunction = theObject => theObject.ToString();

string myString = myFunction(someObject);

I hope this helps.

how do I get a new line, after using float:left?

you can also use

<br style="clear:both" />

Creating/writing into a new file in Qt

QFile file("test.txt");
/*
 *If file does not exist, it will be created
 */
if (!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::ReadWrite))
{
    qDebug() << "FAILED TO CREATE FILE / FILE DOES NOT EXIST";
}

/*for Reading line by line from text file*/
while (!file.atEnd()) {
    QByteArray line = file.readLine();
    qDebug() << "read output - " << line;
}

/*for writing line by line to text file */
if (file.open(QIODevice::ReadWrite))
{
    QTextStream stream(&file);
    stream << "1_XYZ"<<endl;
    stream << "2_XYZ"<<endl;
}

How to shut down the computer from C#

Works starting with windows XP, not available in win 2000 or lower:

This is the quickest way to do it:

Process.Start("shutdown","/s /t 0");

Otherwise use P/Invoke or WMI like others have said.

Edit: how to avoid creating a window

var psi = new ProcessStartInfo("shutdown","/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);

How to show all shared libraries used by executables in Linux?

I didn't have ldd on my ARM toolchain so I used objdump:

$(CROSS_COMPILE)objdump -p

For instance:

objdump -p /usr/bin/python:

Dynamic Section:
  NEEDED               libpthread.so.0
  NEEDED               libdl.so.2
  NEEDED               libutil.so.1
  NEEDED               libssl.so.1.0.0
  NEEDED               libcrypto.so.1.0.0
  NEEDED               libz.so.1
  NEEDED               libm.so.6
  NEEDED               libc.so.6
  INIT                 0x0000000000416a98
  FINI                 0x000000000053c058
  GNU_HASH             0x0000000000400298
  STRTAB               0x000000000040c858
  SYMTAB               0x0000000000402aa8
  STRSZ                0x0000000000006cdb
  SYMENT               0x0000000000000018
  DEBUG                0x0000000000000000
  PLTGOT               0x0000000000832fe8
  PLTRELSZ             0x0000000000002688
  PLTREL               0x0000000000000007
  JMPREL               0x0000000000414410
  RELA                 0x0000000000414398
  RELASZ               0x0000000000000078
  RELAENT              0x0000000000000018
  VERNEED              0x0000000000414258
  VERNEEDNUM           0x0000000000000008
  VERSYM               0x0000000000413534

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

Simple function:

CREATE FUNCTION [dbo].[RemoveAlphaCharacters](@InputString VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
  WHILE PATINDEX('%[^0-9]%',@InputString)>0
        SET @InputString = STUFF(@InputString,PATINDEX('%[^0-9]%',@InputString),1,'')     
  RETURN @InputString
END

GO

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

Fastest way to check if a value exists in a list

The original question was:

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is?

Thus there are two things to find:

  1. is an item in the list, and
  2. what is the index (if in the list).

Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method.

Results

enter image description here

Methods are:

  1. in--basically if x in b: return b.index(x)
  2. try--try/catch on b.index(x) (skips having to check if x in b)
  3. set--basically if x in set(b): return b.index(x)
  4. bisect--sort b with its index, binary search for x in sorted(b). Note mod from @xslittlegrass who returns the index in the sorted b, rather than the original b)
  5. reverse--form a reverse lookup dictionary d for b; then d[x] provides the index of x.

Results show that method 5 is the fastest.

Interestingly the try and the set methods are equivalent in time.


Test Code

import random
import bisect
import matplotlib.pyplot as plt
import math
import timeit
import itertools

def wrapper(func, *args, **kwargs):
    " Use to produced 0 argument function for call it"
    # Reference https://www.pythoncentral.io/time-a-python-function/
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

def method_in(a,b,c):
    for i,x in enumerate(a):
        if x in b:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_try(a,b,c):
    for i, x in enumerate(a):
        try:
            c[i] = b.index(x)
        except ValueError:
            c[i] = -1

def method_set_in(a,b,c):
    s = set(b)
    for i,x in enumerate(a):
        if x in s:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_bisect(a,b,c):
    " Finds indexes using bisection "

    # Create a sorted b with its index
    bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0])

    for i,x in enumerate(a):
        index = bisect.bisect_left(bsorted,(x, ))
        c[i] = -1
        if index < len(a):
            if x == bsorted[index][0]:
                c[i] = bsorted[index][1]  # index in the b array

    return c

def method_reverse_lookup(a, b, c):
    reverse_lookup = {x:i for i, x in enumerate(b)}
    for i, x in enumerate(a):
        c[i] = reverse_lookup.get(x, -1)
    return c

def profile():
    Nls = [x for x in range(1000,20000,1000)]
    number_iterations = 10
    methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup]
    time_methods = [[] for _ in range(len(methods))]

    for N in Nls:
        a = [x for x in range(0,N)]
        random.shuffle(a)
        b = [x for x in range(0,N)]
        random.shuffle(b)
        c = [0 for x in range(0,N)]

        for i, func in enumerate(methods):
            wrapped = wrapper(func, a, b, c)
            time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations)))

    markers = itertools.cycle(('o', '+', '.', '>', '2'))
    colors = itertools.cycle(('r', 'b', 'g', 'y', 'c'))
    labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse'))

    for i in range(len(time_methods)):
        plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels))

    plt.xlabel('list size', fontsize=18)
    plt.ylabel('log(time)', fontsize=18)
    plt.legend(loc = 'upper left')
    plt.show()

profile()

xls to csv converter

I've tested all anwers, but they were all too slow for me. If you have Excel installed you can use the COM.

I thought initially it would be slower since it will load everything for the actual Excel application, but it isn't for huge files. Maybe because the algorithm for opening and saving files runs a heavily optimized compiled code, Microsoft guys make a lot of money for it after all.

import sys
import os
import glob
from win32com.client import Dispatch

def main(path):
    excel = Dispatch("Excel.Application")
    if is_full_path(path):
        process_file(excel, path)
    else:
        files = glob.glob(path)
        for file_path in files:
            process_file(excel, file_path)
    excel.Quit()

def process_file(excel, path):
    fullpath = os.path.abspath(path)
    full_csv_path = os.path.splitext(fullpath)[0] + '.csv'
    workbook = excel.Workbooks.Open(fullpath)
    workbook.Worksheets(1).SaveAs(full_csv_path, 6)
    workbook.Saved = 1
    workbook.Close()


def is_full_path(path):
    return path.find(":") > -1

if __name__ == '__main__':
    main(sys.argv[1])

This is very raw code and won't check for errors, print help or anything, it will just create a csv file for each file that matches the pattern you entered in the function so you can batch process a lot of files only launching excel application once.

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

What does Visual Studio mean by normalize inconsistent line endings?

It means that, for example, some of your lines of text with a <Carriage Return><Linefeed> (the Windows standard), and some end with just a <Linefeed> (the Unix standard).

If you click 'yes' these the end-of-lines in your source file will be converted to have all the same format.

This won't make any difference to the compiler (because end-of-lines count as mere whitespace), but it might make some difference to other tools (e.g. the 'diff' on your version control system).

Android, How to create option Menu

please see :==

private int group1Id = 1;

int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
    menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
    menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
    menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
    menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
    menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);

    return super.onCreateOptionsMenu(menu); 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        // write your code here
        Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
        msg.show();
        return true;

    case 2:
        // write your code here
        return true;

    case 3:
        // write your code here
        return true;

    case 4:
        // write your code here
        return true;

    case 5:
        // write your code here
        return true;

    case 6:
        // write your code here
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

How to get current route

Inject Location to your component and read location.path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location. You need to add import: [RouterModule] to the module.

Update

In the V3 (RC.3) router you can inject ActivatedRoute and access more details using its snapshot property.

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

See also Angular 2 router event listener

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

Use this script, it is previous version of jquery. Solved my problem.

<script
          src="https://code.jquery.com/jquery-2.2.4.min.js"
          integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
          crossorigin="anonymous"></script>

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

What are the rules for calling the superclass constructor?

If you have a constructor without arguments it will be called before the derived class constructor gets executed.

If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:

class base
{
  public:
  base (int arg)
  {
  }
};

class derived : public base
{
  public:
  derived () : base (number)
  {
  }
};

You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.

Symfony - generate url with parameter in controller

make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;

you should also check app/console debug:router in terminal to see what name symfony has named the route

in my case it used a minus instead of an underscore

i.e blog-show

$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);

How can one grab a stack trace in C?

For the past few years I have been using Ian Lance Taylor's libbacktrace. It is much cleaner than the functions in the GNU C library which require exporting all the symbols. It provides more utility for the generation of backtraces than libunwind. And last but not least, it is not defeated by ASLR as are approaches requiring external tools such as addr2line.

Libbacktrace was initially part of the GCC distribution, but it is now made available by the author as a standalone library under a BSD license:

https://github.com/ianlancetaylor/libbacktrace

At the time of writing, I would not use anything else unless I need to generate backtraces on a platform which is not supported by libbacktrace.

How to round to 2 decimals with Python?

float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

How to prevent downloading images and video files from my website?

If you are using PHP, the best way is to control it the .htaccess, you need to put your files, images and videos under consideration in a separate folder/directory, and create a new .htaccess file in this directory with the below:

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(mp4|mp3|avi)$ [NC]
RewriteCond %{HTTP_REFERER} !^http://sample.com/.*$ [NC]
RewriteRule ^.* - [F,L]

The first line %{REQUEST_URI} will prevent getting the file through the web browser or through curl. The second line %{HTTP_REFERER} will prevent accessing the image/video using HTML tags <img> or <video> from any website except the exception ! you provide instead of http://sample.com/ which usually should be your website itself.

You can also have a look at my question and the accepted answer here for more tricks on the browser side.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Found 2 issues in our case.

  1. The Memory was halting and we where mandatory to set the startup perm size to higher value. I guess it was using memory faster then able to allocate it. In our case. -XX:PermSize=256m -XX:MaxPermSize=256m

  2. We are using Clearcase and the plugin from Rational Clearcase SCM (7.0.0.2) was used in Eclipse. The plugin was the case of why Eclipse crashed. And at the moment we do not know why, but could be good to know for others. Was forced to disable it.

Check if string ends with certain pattern

You can test if a string ends with work followed by one character like this:

theString.matches(".*work.$");

If the trailing character is optional you can use this:

theString.matches(".*work.?$");

To make sure the last character is a period . or a slash / you can use this:

theString.matches(".*work[./]$");

To test for work followed by an optional period or slash you can use this:

theString.matches(".*work[./]?$");

To test for work surrounded by periods or slashes, you could do this:

theString.matches(".*[./]work[./]$");

If the tokens before and after work must match each other, you could do this:

theString.matches(".*([./])work\\1$");

Your exact requirement isn't precisely defined, but I think it would be something like this:

theString.matches(".*work[,./]?$");

In other words:

  • zero or more characters
  • followed by work
  • followed by zero or one , . OR /
  • followed by the end of the input

Explanation of various regex items:

.               --  any character
*               --  zero or more of the preceeding expression
$               --  the end of the line/input
?               --  zero or one of the preceeding expression
[./,]           --  either a period or a slash or a comma
[abc]           --  matches a, b, or c
[abc]*          --  zero or more of (a, b, or c)
[abc]?          --  zero or one of (a, b, or c)

enclosing a pattern in parentheses is called "grouping"

([abc])blah\\1  --  a, b, or c followed by blah followed by "the first group"

Here's a test harness to play with:

class TestStuff {

    public static void main (String[] args) {

        String[] testStrings = { 
                "work.",
                "work-",
                "workp",
                "/foo/work.",
                "/bar/work",
                "baz/work.",
                "baz.funk.work.",
                "funk.work",
                "jazz/junk/foo/work.",
                "funk/punk/work/",
                "/funk/foo/bar/work",
                "/funk/foo/bar/work/",
                ".funk.foo.bar.work.",
                ".funk.foo.bar.work",
                "goo/balls/work/",
                "goo/balls/work/funk"
        };

        for (String t : testStrings) {
            print("word: " + t + "  --->  " + matchesIt(t));
        }
    }

    public static boolean matchesIt(String s) {
        return s.matches(".*([./,])work\\1?$");
    }

    public static void print(Object o) {
        String s = (o == null) ? "null" : o.toString();
        System.out.println(o);
    }

}

C# DropDownList with a Dictionary as DataSource

Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind();

Disable button in angular with two conditions?

Is this possible in angular 2?

Yes, it is possible.

If both of the conditions are true, will they enable the button?

No, if they are true, then the button will be disabled. disabled="true".

I try the above code but it's not working well

What did you expect? the button will be disabled when valid is false and the angular formGroup, SAForm is not valid.

A recommendation here as well, Please make the button of type button not a submit because this may cause the whole form to submit and you would need to use invalidate and listen to (ngSubmit).

How to convert/parse from String to char in java?

 String string = "This is Yasir Shabbir ";
 for(char ch : string.toCharArray()){

 }

or If you want individually then you can as

char ch = string.charAt(1);

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

In my case this error was raised because table date column is not null-able

As below:

Create Table #TempTable(
 ...
 ApprovalDate datatime not null.
 ...)

To avoid this error just make it null-able

 Create Table #TempTable(
 ...
 ApprovalDate datatime null.
 ...)

Maximum and minimum values in a textbox

I would typically do something like this (onblur), but it could be attached to any of the events:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript">
function CheckNo(sender){
    if(!isNaN(sender.value)){
        if(sender.value > 100 )
            sender.value = 100;
        if(sender.value < 0 )
            sender.value = 0;
    }else{
          sender.value = 0;
    }
}

</script>
</head>

<body>
<input type="text" onblur="CheckNo(this)" />
</body>
</html>

How do I position an image at the bottom of div?

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Is it possible to decrypt SHA1

Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.

It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.

Eloquent - where not equal to

While this seems to work

Code::query()
    ->where('to_be_used_by_user_id', '!=' , 2)
    ->orWhereNull('to_be_used_by_user_id')
    ->get();

you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"

enter image description here enter image description here

Instead, try Union

$first = Code::whereNull('to_be_used_by_user_id');

$code = Code::where('to_be_used_by_user_id', '!=' , 2)
        ->union($first)
        ->get();

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Android video streaming example

Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.

Setting max-height for table cell contents

I've solved just using this plugin: http://dotdotdot.frebsite.nl/

it automatically sets a max height to the target and adds three dots

List of IP Space used by Facebook

The list from 2020-05-23 is:

31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22

The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

whois -h whois.radb.net -- '-i origin AS32934' | grep ^route

less than 10 add 0 to number

A single regular expression replace should do it:

var stringWithSmallIntegers = "4° 7' 34"W, 168° 1' 23"N";

var paddedString = stringWithSmallIntegers.replace(
    /\d+/g,
    function pad(digits) {
        return digits.length === 1 ? '0' + digits : digits;
    });

alert(paddedString);

shows the expected output.

Converting XDocument to XmlDocument and vice versa

If you need a Win 10 UWP compatible variant:

using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new DomXmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.LoadXml(xmlReader.ReadOuterXml());
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    xmlDocument.WriteContentTo(w);
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }

        public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    w.WriteRaw(xmlDocument.GetXml());
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }
    }

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

_x000D_
_x000D_
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  },_x000D_
  handleChange(e) {_x000D_
    this.setState({email: e.target.value})_x000D_
  },_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!this.state.email}>Button</button>_x000D_
    </div>_x000D_
  }_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
_x000D_
_x000D_

What is Cache-Control: private?

To answer your question about why caching is working, even though the web-server didn't include the headers:

  • Expires: [a date]
  • Cache-Control: max-age=[seconds]

The server kindly asked any intermediate proxies to not cache the contents (i.e. the item should only be cached in a private cache, i.e. only on your own local machine):

  • Cache-Control: private

But the server forgot to include any sort of caching hints:

  • they forgot to include Expires, so the browser knows to use the cached copy until that date
  • they forgot to include Max-Age, so the browser knows how long the cached item is good for
  • they forgot to include E-Tag, so the browser can do a conditional request

But they did include a Last-Modified date in the response:

Last-Modified: Tue, 16 Oct 2012 03:13:38 GMT

Because the browser knows the date the file was modified, it can perform a conditional request. It will ask the server for the file, but instruct the server to only send the file if it has been modified since 2012/10/16 3:13:38:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

The server receives the request, realizes that the client has the most recent version already. Rather than sending the client 200 OK, followed by the contents of the page, instead it tells you that your cached version is good:

304 Not Modified

Your browser did have to suffer the delay of sending a request to the server, and wait for a response, but it did save having to re-download the static content.

Why Max-Age? Why Expires?

Because Last-Modified sucks.

Not everything on the server has a date associated with it. If I'm building a page on the fly, there is no date associated with it - it's now. But I'm perfectly willing to let the user cache the homepage for 15 seconds:

200 OK
Cache-Control: max-age=15

If the user hammers F5, they'll keep getting the cached version for 15 seconds. If it's a corporate proxy, then all 67198 users hitting the same page in the same 15-second window will all get the same contents - all served from close cache. Performance win for everyone.

The virtue of adding Cache-Control: max-age is that the browser doesn't even have to perform a conditional request.

  • if you specified only Last-Modified, the browser has to perform a request If-Modified-Since, and watch for a 304 Not Modified response
  • if you specified max-age, the browser won't even have to suffer the network round-trip; the content will come right out of the caches

The difference between "Cache-Control: max-age" and "Expires"

Expires is a legacy equivalent of the modern (c. 1998) Cache-Control: max-age header:

  • Expires: you specify a date (yuck)
  • max-age: you specify seconds (goodness)
  • And if both are specified, then the browser uses max-age:

    200 OK
    Cache-Control: max-age=60
    Expires: 20180403T192837 
    

Any web-site written after 1998 should not use Expires anymore, and instead use max-age.

What is ETag?

ETag is similar to Last-Modified, except that it doesn't have to be a date - it just has to be a something.

If I'm pulling a list of products out of a database, the server can send the last rowversion as an ETag, rather than a date:

200 OK
ETag: "247986"

My ETag can be the SHA1 hash of a static resource (e.g. image, js, css, font), or of the cached rendered page (i.e. this is what the Mozilla MDN wiki does; they hash the final markup):

200 OK
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

And exactly like in the case of a conditional request based on Last-Modified:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

304 Not Modified

I can perform a conditional request based on the ETag:

GET / HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

304 Not Modified

An ETag is superior to Last-Modified because it works for things besides files, or things that have a notion of date. It just is

Java compiler level does not match the version of the installed Java project facet

In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

enter image description here

XML string to XML document

This code sample is taken from csharp-examples.net, written by Jan Slama:

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

XML:

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

CODE:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

Change drive in git bash for windows

In order to navigate to a different drive just use

cd /E/Study/Codes

It will solve your problem.

Draw an X in CSS

Check & and Cross:

<span class='act-html-check'></span>
<span class='act-html-cross'><span class='act-html-cross'></span></span>

<style type="text/css">
span.act-html-check {
                display: inline-block;
                width: 12px;
                height: 18px;
                border: solid limegreen;
                border-width: 0 5px 5px 0;
                transform: rotate( 45deg);
            }


            span.act-html-cross {
                display: inline-block;
                width: 10px;
                height: 10px;
                border: solid red;
                border-width: 0 5px 5px 0;
                transform: rotate( 45deg);
                position: relative;
            }

            span.act-html-cross > span { {
                transform: rotate( -180deg);
                position: absolute;
                left: 9px;
                top: 9px;
            }
</style>

Defining and using a variable in batch file

input location.bat

@echo off
cls

set /p "location"="bob"
echo We're working with %location%
pause

output

We're working with bob

(mistakes u done : space and " ")

Java, List only subdirectories from a directory, not files

This will literally list (that is, print) all subdirectories. It basically is a loop kind of where you don’t need to store the items in between to a list. This is what one most likely needs, so I leave it here.

Path directory = Paths.get("D:\\directory\\to\\list");

Files.walk(directory, 1).filter(entry -> !entry.equals(directory))
    .filter(Files::isDirectory).forEach(subdirectory ->
{
    // do whatever you want with the subdirectories
    System.out.println(subdirectory.getFileName());
});

How can I change image tintColor in iOS and WatchKit

Now i use this method based in Duncan Babbage response:

+ (UIImageView *) tintImageView: (UIImageView *)imageView withColor: (UIColor*) color{
    imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [imageView setTintColor:color];
    return imageView;
}

Is there a constraint that restricts my generic method to numeric types?

If all you want is use one numeric type, you could consider creating something similar to an alias in C++ with using.

So instead of having the very generic

T ComputeSomething<T>(T value1, T value2) where T : INumeric { ... }

you could have

using MyNumType = System.Double;
T ComputeSomething<MyNumType>(MyNumType value1, MyNumType value2) { ... }

That might allow you to easily go from double to int or others if needed, but you wouldn't be able to use ComputeSomething with double and int in the same program.

But why not replace all double to int then? Because your method may want to use a double whether the input is double or int. The alias allows you to know exactly which variable uses the dynamic type.

What is an uber jar?

For Java Developers who use SpringBoot, ÜBER/FAT JAR is normally the final result of the package phase of maven (or build task if you use gradle).

Inside the Fat JAR one can find a META-INF directory inside which the MANIFEST.MF file lives with all the info regarding the Main class. More importantly, at the same level of META-INF directory you find the BOOT-INF directory inside which the directory lib lives and contains all the .jar files that are the dependencies of your application.

Python - IOError: [Errno 13] Permission denied:

This happened to me when I was using 'shutil.copyfile' instead of 'shutil.copy'. The permissions were messed up.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

How can INSERT INTO a table 300 times within a loop in SQL?

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

.ps1 cannot be loaded because the execution of scripts is disabled on this system

You need to run Set-ExecutionPolicy:

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Let's say you have the DLLs build for both platforms, and they are in the following location:

C:\whatever\x86\whatever.dll
C:\whatever\x64\whatever.dll

You simply need to edit your .csproj file from this:

<HintPath>C:\whatever\x86\whatever.dll</HintPath>

To this:

<HintPath>C:\whatever\$(Platform)\whatever.dll</HintPath>

You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.

Replace multiple whitespaces with single whitespace in JavaScript string

I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:

  • I want to replace multiple occurences of whitespace inside the string with a single space
  • ...and... I do not want whitespaces in the beginnin or end of the string (trim)

For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):

s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');

The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD^

then the modified files should show up.

You could move the modified files into a new branch

use,

git checkout -b newbranch

git checkout commit -m "files modified"

git push origin newbranch

git checkout master

then you should be on a clean branch, and your changes should be stored in newbranch. You could later just merge this change into the master branch

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

Plotly is missing in this list. I've linked the python binding page. It definitively has animated and interative 3D Charts. And since it is Open Source most of that is available offline. Of course it is working with Jupyter

Jackson with JSON: Unrecognized field, not marked as ignorable

In my case it was simple: the REST-service JSON Object was updated (a property was added), but the REST-client JSON Object wasn't. As soon as i've updated JSON client object the 'Unrecognized field ...' exception has vanished.

The import org.apache.commons cannot be resolved in eclipse juno

You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

Sending simple message body + file attachment using Linux Mailx

The usual way is to use uuencode for the attachments and echo for the body:

(uuencode output.txt output.txt; echo "Body of text") | mailx -s 'Subject' [email protected]

For Solaris and AIX, you may need to put the echo statement first:

(echo "Body of text"; uuencode output.txt output.txt) | mailx -s 'Subject' [email protected]

SQL Server SELECT INTO @variable?

you can do this:

SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email
INTO #tempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

then later

SELECT CustomerId FROM #tempCustomer

you doesn't need to declare the structure of #tempCustomer

Image change every 30 seconds - loop

I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.

function changeImage() {
    var img = document.getElementById("img");
    img.src = images[x];
    x++;        
    if(x >= images.length) {
        x = 0;
    } 
    fadeImg(img, 100, true);
    setTimeout("changeImage()", 30000);
}

function fadeImg(el, val, fade) {
    if(fade === true) {
        val--;
    } else {
        val ++;
    }       
    if(val > 0 && val < 100) {
        el.style.opacity = val / 100;
        setTimeout(function(){ fadeImg(el, val, fade); }, 10);
    }
}

var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

How much RAM is SQL Server actually using?

Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.

refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx

Generating random numbers in Objective-C

Same as C, you would do

#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;

(assuming you meant including 0 but excluding 74, which is what your Java example does)

Edit: Feel free to substitute random() or arc4random() for rand() (which is, as others have pointed out, quite sucky).

How to stop execution after a certain time in Java?

Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.

With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

psql: FATAL: database "<user>" does not exist

Try using-

psql -d postgres

I was also facing the same issue when I ran psql

Loop in react-native

render() {
var myloop = [];

for (let i = 0; i < 10; i++) {
  myloop.push(
    <View key={i}>
    <Text>{i}</Text>
    </View>
  );
}

 return (

        <View >
          <Text >Welcome to React Native!</Text>
           {myloop}
        </View>


    );
  }
}

How to rebuild docker container in docker-compose.yml?

This should fix your problem:

docker-compose ps # lists all services (id, name)
docker-compose stop <id/name> #this will stop only the selected container
docker-compose rm <id/name> # this will remove the docker container permanently 
docker-compose up # builds/rebuilds all not already built container 

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

How to read a file byte by byte in Python and how to print a bytelist as a binary?

The code you've shown will read 8 bytes. You could use

with open(filename, 'rb') as f:
   while 1:
      byte_s = f.read(1)
      if not byte_s:
         break
      byte = byte_s[0]
      ...

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

How to set the thumbnail image on HTML5 video?

Add poster="placeholder.png" to the video tag.

<video width="470" height="255" poster="placeholder.png" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <source src="video.webm" type="video/webm">
    <object data="video.mp4" width="470" height="255">
    <embed src="video.swf" width="470" height="255">
    </object>
</video>

Does that work?

Write HTML to string

I know you asked about C#, but if you're willing to use any .Net language then I highly recommend Visual Basic for this exact problem. Visual Basic has a feature called XML Literals that will allow you to write code like this.

Module Module1

    Sub Main()

        Dim myTitle = "Hello HTML"
        Dim myHTML = <html>
                         <head>
                             <title><%= myTitle %></title>
                         </head>
                         <body>
                             <h1>Welcome</h1>
                             <table>
                                 <tr><th>ID</th><th>Name</th></tr>
                                 <tr><td>1</td><td>CouldBeAVariable</td></tr>
                             </table>
                         </body>
                     </html>

        Console.WriteLine(myHTML)
    End Sub

End Module

This allows you to write straight HTML with expression holes in the old ASP style and makes your code super readable. Unfortunately this feature is not in C#, but you could write a single module in VB and add it as a reference to your C# project.

Writing in Visual Studio also allows proper indentation for most XML Literals and expression wholes. Indentation for the expression holes is better in VS2010.

Align Div at bottom on main Div

I guess you'll need absolute position

.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}

Fade In Fade Out Android Animation in Java

Here is what I used to fade in/out Views, hope this helps someone.

private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
    AnimatorSet mAnimationSet = new AnimatorSet();
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA,  1f, 0f);
    fadeOut.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            fadeOutTarget.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    });
    fadeOut.setInterpolator(new LinearInterpolator());

    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
    fadeIn.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            fadeInTarget.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animator animation) {}

        @Override
        public void onAnimationCancel(Animator animation) {}

        @Override
        public void onAnimationRepeat(Animator animation) {}
    });
    fadeIn.setInterpolator(new LinearInterpolator());
    mAnimationSet.setDuration(duration);
    mAnimationSet.playTogether(fadeOut, fadeIn);
    mAnimationSet.start();
}

Regular expression to detect semi-colon terminated C++ for & while loops

A little late to the party, but I think regular expressions are not the right tool for the job.

The problem is that you'll come across edge cases which would add extranous complexity to the regular expression. @est mentioned an example line:

for (int i = 0; i < 10; doSomethingTo("("));

This string literal contains an (unbalanced!) parenthesis, which breaks the logic. Apparently, you must ignore contents of string literals. In order to do this, you must take the double quotes into account. But string literals itself can contain double quotes. For instance, try this:

for (int i = 0; i < 10; doSomethingTo("\"(\\"));

If you address this using regular expressions, it'll add even more complexity to your pattern.

I think you are better off parsing the language. You could, for instance, use a language recognition tool like ANTLR. ANTLR is a parser generator tool, which can also generate a parser in Python. You must provide a grammar defining the target language, in your case C++. There are already numerous grammars for many languages out there, so you can just grab the C++ grammar.

Then you can easily walk the parser tree, searching for empty statements as while or for loop body.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

You can do

git config http.sslVerify "false"

in your specific repo to disable SSL certificate checking for that repo only.

How to save password when using Subversion from the console

Just to emphasize what Tomasz Gandor and Domain said about having the right version of svn and that it was compiled to enable plain text password storage, you need verify what you have:

svn --version
svn, version 1.9.7 (r1800392)
...
WARNING: Plaintext password storage is enabled!
...

The following authentication credential caches are available:

* Plaintext cache in /gr/home/ffvdqb/.subversion
* GPG-Agent

Versus:

svn --version
svn, version 1.12.2 (r1863366)
...

The following authentication credential caches are available:

* Gnome Keyring
* GPG-Agent
* KWallet (KDE)

Once you see that your version of svn was enabled for plain text password storage, then apply all the rest of the answers here.

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

RegEx pattern any two letters followed by six numbers

Everything you need here can be found in this quickstart guide. A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d or [A-Za-z]{2}\d{6}.

If you want to accept only capital letters then replace [A-Za-z] with [A-Z].

How do I change the JAVA_HOME for ant?

Looking at the shell script for invoking ant, it is possible that the value for $JAVA_HOME set for your shell in .bashrc can be overridden in the files /etc/ant.conf, $HOME/.ant/ant.conf, and $HOME/.antrc. If you execute bash -x <path to ant script> it will emit debugging information which should help you track down where $JAVA_HOME is being overridden.

Invalid default value for 'dateAdded'

mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP

How to hide 'Back' button on navigation bar on iPhone?

Use the code:

 self.navigationItem.backBarButtonItem=nil;

Bootstrap 4 align navbar items to the right

use the flex-row-reverse class

<nav class="navbar navbar-toggleable-md navbar-light">
    <div class="container">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false"
          aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">
            <i class="fa fa-hospital-o fa-2x" aria-hidden="true"></i>
        </a>
        <div class="collapse navbar-collapse flex-row-reverse" id="navbarNavAltMarkup">
            <ul class="navbar-nav">
                <li><a class="nav-item nav-link active" href="#" style="background-color:#666">Home <span class="sr-only">(current)</span></a</li>
                <li><a class="nav-item nav-link" href="#">Doctors</a></li>
                <li><a class="nav-item nav-link" href="#">Specialists</a></li>
                <li><a class="nav-item nav-link" href="#">About</a></li>
            </ul>
        </div>
    </div>
</nav>

SSL InsecurePlatform error when using Requests package

Requests 2.6 introduced this warning for users of python prior to 2.7.9 with only stock SSL modules available.

Assuming you can't upgrade to a newer version of python, this will install more up-to-date python SSL libraries:

pip install --upgrade ndg-httpsclient 

HOWEVER, this may fail on some systems without the build-dependencies for pyOpenSSL. On debian systems, running this before the pip command above should be enough for pyOpenSSL to build:

apt-get install python-dev libffi-dev libssl-dev

Read connection string from web.config

using System.Configuration;


string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();

Remember don't Use ConnectionStrings[index] because you might of Global machine Config and Portability

How to programmatically click a button in WPF?

As Greg D said, I think that an alternative to Automation to click a button using the MVVM pattern (click event raised and command executed) is to call the OnClick method using reflection:

typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);

Download a file from HTTPS using download.file()

You can set global options and try-

options('download.file.method'='curl')
download.file(URL, destfile = "./data/data.csv", method="auto")

For issue refer to link- https://stat.ethz.ch/pipermail/bioconductor/2011-February/037723.html

In Postgresql, force unique on combination of two columns

If, like me, you landed here with:

  • a pre-existing table,
  • to which you need to add a new column, and
  • also need to add a new unique constraint on the new column as well as an old one, AND
  • be able to undo it all (i.e. write a down migration)

Here is what worked for me, utilizing one of the above answers and expanding it:

-- up

ALTER TABLE myoldtable ADD COLUMN newcolumn TEXT;
ALTER TABLE myoldtable ADD CONSTRAINT myoldtable_oldcolumn_newcolumn_key UNIQUE (oldcolumn, newcolumn);

---

ALTER TABLE myoldtable DROP CONSTRAINT myoldtable_oldcolumn_newcolumn_key;
ALTER TABLE myoldtable DROP COLUMN newcolumn;

-- down

How to do what head, tail, more, less, sed do in Powershell?

I got some better solutions:

gc log.txt -ReadCount 5 | %{$_;throw "pipeline end!"} # head
gc log.txt | %{$num=0;}{$num++;"$num $_"}             # cat -n
gc log.txt | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed

C# Call a method in a new thread

Unless you have a special situation that requires a non thread-pool thread, just use a thread pool thread like this:

Action secondFooAsync = new Action(SecondFoo);

secondFooAsync.BeginInvoke(new AsyncCallback(result =>
      {
         (result.AsyncState as Action).EndInvoke(result); 

      }), secondFooAsync); 

Gaurantees that EndInvoke is called to take care of the clean up for you.

Is there a good JavaScript minifier?

JavaScript Minifier gives a good API you can use programatically:

curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw

Or by uploading a file and redirecting to a new file:

curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js

Hope that helps.

Form inline inside a form horizontal in twitter bootstrap?

to make it simple, just add a class="form-inline" before the input.

example:

<div class="col-md-4 form-inline"> //add the class here...
     <label>Lot Size:</label>
     <input type="text" value="" name="" class="form-control" >
 </div>

How do I check CPU and Memory Usage in Java?

Since Java 1.5 the JDK comes with a new tool: JConsole wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

C# - Multiple generic types in one list

public abstract class Metadata
{
}

// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
    private DataType mDataType;
}

Parse String date in (yyyy-MM-dd) format

tl;dr

LocalDate.parse( "2013-09-18" )

… and …

myLocalDate.toString()  // Example: 2013-09-18

java.time

The Question and other Answers are out-of-date. The troublesome old legacy date-time classes are now supplanted by the java.time classes.

ISO 8601

Your input string happens to comply with standard ISO 8601 format, YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing and generating string representations of date-time values. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2013-09-18" );

About java.time

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

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

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

Marquee text in Android

You can use a TextView or your custom TextView. The latter is when the textview cannot get focus all the time.

First, you can use a TextView or a custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Then in case of using CustomTextView, you should define the CustomTextView class:

public class CustomTextView extends TextView {
        public CustomTextView(Context context) {
            super(context);
        }
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);

        }

        public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);

        }


        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            if(focused)
                super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }

        @Override
        public void onWindowFocusChanged(boolean focused) {
            if(focused)
                super.onWindowFocusChanged(focused);
        }


        @Override
        public boolean isFocused() {
            return true;
        }
    }

Hope it will be helpful to you. Cheers!

Java; String replace (using regular expressions)?

Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.

https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)

In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.