Programs & Examples On #Mutation

Mutation refers to a genetic operator used to maintain genetic diversity from one generation of a population to the next. For javascript DOM, use [mutation-observers]. For Java mutators, use [mutators]. For object mutability in general, use [mutability].

What is the use of verbose in Keras while validating the model?

The order of details provided with verbose flag are as

Less details.... More details

0 < 2 < 1

Default is 1

For production environment, 2 is recommended

Vuex - Computed property "name" was assigned to but it has no setter

I was facing exact same error

Computed property "callRingtatus" was assigned to but it has no setter

here is a sample code according to my scenario

computed: {

callRingtatus(){
            return this.$store.getters['chat/callState']===2
      }

}

I change the above code into the following way

computed: {

callRingtatus(){
       return this.$store.state.chat.callState===2
    }
}

fetch values from vuex store state instead of getters inside the computed hook

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

vue.js 2 how to watch store values from vuex

I tried literally everything to get this working.

Theory

I found that for some reason, changes to objects from $store don't necessarily trigger a .watch method. My workaround was to

  • Store
    • Create a complex data set which should but doesn't propagate changes to a Component
    • Create an incrementing counter in the state to act as a flag, which does propagate changes to a Component when watched
    • Create a method in $store.mutators to alter the complex dataset and increment the counter flag
  • Component
    • Watch for changes in the $store.state flag. When change is detected, update locally relevant reactive changes from the $store.state complex data set
    • Make changes to the $store.state's dataset using our $store.mutators method

Implementation

This is implemented something like this:

Store

let store = Vuex.Store({
  state: {
    counter: 0,
    data: { someKey: 0 }
  },
  mutations: {
    updateSomeKey(state, value) {
      update the state.data.someKey = value;
      state.counter++;
    }
  }
});

Component

  data: {
    dataFromStoreDataSomeKey: null,
    someLocalValue: 1
  },
  watch: {
    '$store.state.counter': {
        immediate: true,
        handler() {
           // update locally relevant data
           this.someLocalValue = this.$store.state.data.someKey;
        }
     }
  },
  methods: {
    updateSomeKeyInStore() { 
       this.$store.commit('updateSomeKey', someLocalValue);
  }

Runnable demo

It's convoluted but basically here we are watching for a flag to change and then updating local data to reflect important changes in an object that's stored in the $state

_x000D_
_x000D_
Vue.config.devtools = false

const store = new Vuex.Store({
  state: {
    voteCounter: 0,
    // changes to objectData trigger a watch when keys are added,
    // but not when values are modified?
    votes: {
      'people': 0,
      'companies': 0,
      'total': 0,
    },
  },
  mutations: {
    vote(state, position) {
      state.votes[position]++;
      state.voteCounter++;
    }
  },
});


app = new Vue({
  el: '#app',
  store: store,
  data: {
    votesForPeople: null,
    votesForCompanies: null,
    pendingVote: null,
  },
  computed: {
    totalVotes() {
      return this.votesForPeople + this.votesForCompanies
    },
    peoplePercent() {
      if (this.totalVotes > 0) {
        return 100 * this.votesForPeople / this.totalVotes
      } else {
        return 0
      }
    },
    companiesPercent() {
      if (this.totalVotes > 0) {
        return 100 * this.votesForCompanies / this.totalVotes
      } else {
        return 0
      }
    },
  },
  watch: {
    '$store.state.voteCounter': {
        immediate: true,
        handler() {
          // clone relevant data locally
          this.votesForPeople = this.$store.state.votes.people
          this.votesForCompanies = this.$store.state.votes.companies
        }
     }
  },
  methods: {
    vote(event) {
      if (this.pendingVote) {
        this.$store.commit('vote', this.pendingVote)
      }
    }
  }
  
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">


<div id="app">
   <form @submit.prevent="vote($event)">
      <div class="form-check">
         <input
           class="form-check-input" 
           type="radio" 
           name="vote" 
           id="voteCorps"
           value="companies"
           v-model="pendingVote"
          >
         <label class="form-check-label" for="voteCorps">
         Equal rights for companies
         </label>
      </div>
      <div class="form-check">
         <input
           class="form-check-input" 
           type="radio" 
           name="vote"
           id="votePeople" 
           value="people"
           v-model="pendingVote"
         >
         <label class="form-check-label" for="votePeople">
         Equal rights for people
         </label>
      </div>
      <button
        class="btn btn-primary"
        :disabled="pendingVote==null"
      >Vote</button>
   </form>
   <div
     class="progress mt-2"
     v-if="totalVotes > 0"
    >
      <div class="progress-bar"
        role="progressbar"
        aria-valuemin="0"
        :style="'width: ' + peoplePercent + '%'"
        :aria-aluenow="votesForPeople"
        :aria-valuemax="totalVotes"
      >People</div>
      <div
        class="progress-bar bg-success"
        role="progressbar"
        aria-valuemin="0"
        :style="'width: ' + companiesPercent + '%'"
        :aria-valuenow="votesForCompanies"
        :aria-valuemax="totalVotes"
      >Companies</div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

Spring security CORS Filter

In my case, I just added this class and use @EnableAutConfiguration:

@Component
public class SimpleCORSFilter extends GenericFilterBean {
    /**
     * The Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        logger.info("> doFilter");

        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, resp);

        logger.info("< doFilter");
    }
}

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

Why is setState in reactjs Async instead of Sync?

Imagine incrementing a counter in some component:

  class SomeComponent extends Component{

    state = {
      updatedByDiv: '',
      updatedByBtn: '',
      counter: 0
    }

    divCountHandler = () => {
      this.setState({
        updatedByDiv: 'Div',
        counter: this.state.counter + 1
      });
      console.log('divCountHandler executed');
    }

    btnCountHandler = () => {
      this.setState({
        updatedByBtn: 'Button',
        counter: this.state.counter + 1
      });
      console.log('btnCountHandler executed');
    }
    ...
    ...
    render(){
      return (
        ...
        // a parent div
        <div onClick={this.divCountHandler}>
          // a child button
          <button onClick={this.btnCountHandler}>Increment Count</button>
        </div>
        ...
      )
    }
  }

There is a count handler attached to both the parent and the child components. This is done purposely so we can execute the setState() twice within the same click event bubbling context, but from within 2 different handlers.

As we would imagine, a single click event on the button would now trigger both these handlers since the event bubbles from target to the outermost container during the bubbling phase.

Therefore the btnCountHandler() executes first, expected to increment the count to 1 and then the divCountHandler() executes, expected to increment the count to 2.

However the count only increments to 1 as you can inspect in React Developer tools.

This proves that react

  • queues all the setState calls

  • comes back to this queue after executing the last method in the context(the divCountHandler in this case)

  • merges all the object mutations happening within multiple setState calls in the same context(all method calls within a single event phase is same context for e.g.) into one single object mutation syntax (merging makes sense because this is why we can update the state properties independently in setState() in the first place)

  • and passes it into one single setState() to prevent re-rendering due to multiple setState() calls (this is a very primitive description of batching).

Resultant code run by react:

this.setState({
  updatedByDiv: 'Div',
  updatedByBtn: 'Button',
  counter: this.state.counter + 1
})

To stop this behaviour, instead of passing objects as arguments to the setState method, callbacks are passed.

    divCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByDiv: 'Div',
              counter: prevState.counter + 1
            };
          });
          console.log('divCountHandler executed');
        }

    btnCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByBtn: 'Button',
              counter: prevState.counter + 1
            };
          });
      console.log('btnCountHandler executed');
    }

After the last method finishes execution and when react returns to process the setState queue, it simply calls the callback for each setState queued, passing in the previous component state.

This way react ensures that the last callback in the queue gets to update the state that all of its previous counterparts have laid hands on.

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

What does numpy.random.seed(0) do?

As noted, numpy.random.seed(0) sets the random seed to 0, so the pseudo random numbers you get from random will start from the same point. This can be good for debuging in some cases. HOWEVER, after some reading, this seems to be the wrong way to go at it, if you have threads because it is not thread safe.

from differences-between-numpy-random-and-random-random-in-python:

For numpy.random.seed(), the main difficulty is that it is not thread-safe - that is, it's not safe to use if you have many different threads of execution, because it's not guaranteed to work if two different threads are executing the function at the same time. If you're not using threads, and if you can reasonably expect that you won't need to rewrite your program this way in the future, numpy.random.seed() should be fine for testing purposes. If there's any reason to suspect that you may need threads in the future, it's much safer in the long run to do as suggested, and to make a local instance of the numpy.random.Random class. As far as I can tell, random.random.seed() is thread-safe (or at least, I haven't found any evidence to the contrary).

example of how to go about this:

from numpy.random import RandomState
prng = RandomState()
print prng.permutation(10)
prng = RandomState()
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)

may give:

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

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

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

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

Lastly, note that there might be cases where initializing to 0 (as opposed to a seed that has not all bits 0) may result to non-uniform distributions for some few first iterations because of the way xor works, but this depends on the algorithm, and is beyond my current worries and the scope of this question.

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

jQuery "on create" event for dynamically-created elements

create a <select> with id , append it to document.. and call .combobox

  var dynamicScript='<select id="selectid"><option value="1">...</option>.....</select>'
  $('body').append(dynamicScript); //append this to the place your wanted.
  $('#selectid').combobox();  //get the id and add .combobox();

this should do the trick.. you can hide the select if you want and after .combobox show it..or else use find..

 $(document).find('select').combobox() //though this is not good performancewise

case in sql stored procedure on SQL Server

Try this

If @NewStatus  = 'InOffice' 
BEGIN
     Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'OutOffice'
BEGIN
    Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'Home'
BEGIN
    Update tblEmployee set Home = -1 where EmpID = @EmpID
END

DataTables fixed headers misaligned with columns in wide tables

If you want to use scrollY use:

$('.DataTables_sort_wrapper').trigger("click");

Permutations between two lists of unequal length

Or the KISS answer for short lists:

[(i, j) for i in list1 for j in list2]

Not as performant as itertools but you're using python so performance is already not your top concern...

I like all the other answers too!

Why does AngularJS include an empty option in select?

Angular < 1.4

For anyone out there that treat "null" as valid value for one of the options (so imagine that "null" is a value of one of the items in typeOptions in example below), I found that simplest way to make sure that automatically added option is hidden is to use ng-if.

<select ng-options="option.value as option.name for option in typeOptions">
    <option value="" ng-if="false"></option>
</select>

Why ng-if and not ng-hide? Because you want css selectors that would target first option inside above select to target "real" option, not the one that's hidden. It gets useful when you're using protractor for e2e testing and (for whatever reason) you use by.css() to target select options.

Angular >= 1.4

Due to the refactoring of the select and options directives, using ng-if is no longer a viable option so you gotta turn to ng-show="false" to make it work again.

How to convert any date format to yyyy-MM-dd

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Here, SourceDate is variable in which you will get selected date.

fetch in git doesn't get all branches

I had a similar problem, however in my case I could pull/push to the remote branch but git status didn't show the local branch state w.r.t the remote ones.

Also, in my case git config --get remote.origin.fetch didn't return anything

The problem is that there was a typo in the .git/config file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)

So, check if your remote entry in the .git/config file is correct, e.g.:

[remote "origin"]
    url = https://[server]/[user or organization]/[repo].git
    fetch = +refs/heads/*:refs/remotes/origin/*

C++ -- expected primary-expression before ' '

You should not be repeating the string part when sending parameters.

int wordLength = wordLengthFunction(word); //you do not put string word here.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

Permutations in JavaScript?

Here is another "more recursive" solution.

_x000D_
_x000D_
function perms(input) {
  var data = input.slice();
  var permutations = [];
  var n = data.length;

  if (n === 0) {
    return [
      []
    ];
  } else {
    var first = data.shift();
    var words = perms(data);
    words.forEach(function(word) {
      for (var i = 0; i < n; ++i) {
        var tmp = word.slice();
        tmp.splice(i, 0, first)
        permutations.push(tmp);
      }
    });
  }

  return permutations;
}

var str = 'ABC';
var chars = str.split('');
var result = perms(chars).map(function(p) {
  return p.join('');
});

console.log(result);

var output = window.document.getElementById('output');
output.innerHTML = result;
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Output:

[ 'ABC', 'BAC', 'BCA', 'ACB', 'CAB', 'CBA' ]

Google Android USB Driver and ADB

  1. modify android_winusb.inf
  2. Sign the driver
  3. modify adb

I also instaled generic adb driver from http://adbdriver.com/ and it works.

How to print a string at a fixed width?

>>> print(f"{'123':<4}56789")
123 56789

Finding all possible permutations of a given string in python

The itertools module has a useful method called permutations(). The documentation says:

itertools.permutations(iterable[, r])

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

You'll have to join your permuted letters as strings though.

>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> perms

['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta', 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']

If you find yourself troubled by duplicates, try fitting your data into a structure with no duplicates like a set:

>>> perms = [''.join(p) for p in permutations('stacks')]
>>> len(perms)
720
>>> len(set(perms))
360

Thanks to @pst for pointing out that this is not what we'd traditionally think of as a type cast, but more of a call to the set() constructor.

How to calculate combination and permutation in R?

The function combn is in the standard utils package (i.e. already installed)

choose is also already available in the Special {base}

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Is it possible to select the last n items with nth-child?

Because of the definition of the semantics of nth-child, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child gives you.

Unresolved Import Issues with PyDev and Eclipse

I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, I just add a new empty line in the files that had the import errors and saved them and the error was resolved.

Better way to shuffle two numpy arrays in unison

Your can use NumPy's array indexing:

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = numpy.random.permutation(len(a))
    return a[p], b[p]

This will result in creation of separate unison-shuffled arrays.

Using {% url ??? %} in django templates

The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

url(r'^/logout/' , logout_view, name='logout_view')

Upper memory limit?

(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.

Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.

As others have pointed out, your MemoryError problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.

Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.

Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.

To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.

try:
    from itertools import izip_longest
except ImportError:    # Python 3
    from itertools import zip_longest as izip_longest

GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
                    "A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w')  # left in, but nothing written

for file_name in input_file_names:
    with open(file_name, 'r') as input_file:
        print('processing file: {}'.format(file_name))

        totals = []
        for count, fields in enumerate((line.split('\t') for line in input_file), 1):
            totals = [sum(values) for values in
                        izip_longest(totals, map(float, fields), fillvalue=0)]
        averages = [total/count for total in totals]

        for print_counter, average in enumerate(averages):
            print('  {:9.4f}'.format(average))
            if print_counter % GROUP_SIZE == 0:
                file_write.write(str(average)+'\n')

file_write.write('\n')
file_write.close()
mutation_average.close()

Generating all permutations of a given string

Improved Code for the same

    static String permutationStr[];
    static int indexStr = 0;

    static int factorial (int i) {
        if (i == 1)
            return 1;
        else
            return i * factorial(i-1);
    }

    public static void permutation(String str) {
        char strArr[] = str.toLowerCase().toCharArray();
        java.util.Arrays.sort(strArr);

        int count = 1, dr = 1;
        for (int i = 0; i < strArr.length-1; i++){
            if ( strArr[i] == strArr[i+1]) {
                count++;
            } else {
                dr *= factorial(count);
                count = 1;
            }       
        }
        dr *= factorial(count);

        count = factorial(strArr.length) / dr;

        permutationStr = new String[count];

        permutation("", str);

        for (String oneStr : permutationStr){
            System.out.println(oneStr);
        }
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) {
            for (int i = 0; i < indexStr; i++){
                if(permutationStr[i].equals(prefix))
                    return;
            }        
            permutationStr[indexStr++] = prefix;
        } else {
            for (int i = 0; i < n; i++) {
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
            }
        }
    }

Permutation of array

Here is an implementation of the Permutation in Java:

Permutation - Java

You should have a check on it!

Edit: code pasted below to protect against link-death:

// Permute.java -- A class generating all permutations

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;

public class Permute implements Iterator {

   private final int size;
   private final Object [] elements;  // copy of original 0 .. size-1
   private final Object ar;           // array for output,  0 .. size-1
   private final int [] permutation;  // perm of nums 1..size, perm[0]=0

   private boolean next = true;

   // int[], double[] array won't work :-(
   public Permute (Object [] e) {
      size = e.length;
      elements = new Object [size];    // not suitable for primitives
      System.arraycopy (e, 0, elements, 0, size);
      ar = Array.newInstance (e.getClass().getComponentType(), size);
      System.arraycopy (e, 0, ar, 0, size);
      permutation = new int [size+1];
      for (int i=0; i<size+1; i++) {
         permutation [i]=i;
      }
   }

   private void formNextPermutation () {
      for (int i=0; i<size; i++) {
         // i+1 because perm[0] always = 0
         // perm[]-1 because the numbers 1..size are being permuted
         Array.set (ar, i, elements[permutation[i+1]-1]);
      }
   }

   public boolean hasNext() {
      return next;
   }

   public void remove() throws UnsupportedOperationException {
      throw new UnsupportedOperationException();
   }

   private void swap (final int i, final int j) {
      final int x = permutation[i];
      permutation[i] = permutation [j];
      permutation[j] = x;
   }

   // does not throw NoSuchElement; it wraps around!
   public Object next() throws NoSuchElementException {

      formNextPermutation ();  // copy original elements

      int i = size-1;
      while (permutation[i]>permutation[i+1]) i--;

      if (i==0) {
         next = false;
         for (int j=0; j<size+1; j++) {
            permutation [j]=j;
         }
         return ar;
      }

      int j = size;

      while (permutation[i]>permutation[j]) j--;
      swap (i,j);
      int r = size;
      int s = i+1;
      while (r>s) { swap(r,s); r--; s++; }

      return ar;
   }

   public String toString () {
      final int n = Array.getLength(ar);
      final StringBuffer sb = new StringBuffer ("[");
      for (int j=0; j<n; j++) {
         sb.append (Array.get(ar,j).toString());
         if (j<n-1) sb.append (",");
      }
      sb.append("]");
      return new String (sb);
   }

   public static void main (String [] args) {
      for (Iterator i = new Permute(args); i.hasNext(); ) {
         final String [] a = (String []) i.next();
         System.out.println (i);
      }
   }
}

Algorithm to generate all possible permutations of a list?

Here is a recursive solution in PHP. WhirlWind's post accurately describes the logic. It's worth mentioning that generating all permutations runs in factorial time, so it might be a good idea to use an iterative approach instead.

public function permute($sofar, $input){
  for($i=0; $i < strlen($input); $i++){
    $diff = strDiff($input,$input[$i]);
    $next = $sofar.$input[$i]; //next contains a permutation, save it
    $this->permute($next, $diff);
  }
}

The strDiff function takes two strings, s1 and s2, and returns a new string with everything in s1 without elements in s2 (duplicates matter). So, strDiff('finish','i') => 'fnish' (the second 'i' is not removed).

Understanding the order() function

To sort a 1D vector or a single column of data, just call the sort function and pass in your sequence.

On the other hand, the order function is necessary to sort data two-dimensional data--i.e., multiple columns of data collected in a matrix or dataframe.

Stadium Home Week Qtr Away Off Def Result       Kicker Dist
751     Out  PHI   14   4  NYG PHI NYG   Good      D.Akers   50
491     Out   KC    9   1  OAK OAK  KC   Good S.Janikowski   32
702     Out  OAK   15   4  CLE CLE OAK   Good     P.Dawson   37
571     Out   NE    1   2  OAK OAK  NE Missed S.Janikowski   43
654     Out  NYG   11   2  PHI NYG PHI   Good      J.Feely   26
307     Out  DEN   14   2  BAL DEN BAL   Good       J.Elam   48
492     Out   KC   13   3  DEN  KC DEN   Good      L.Tynes   34
691     Out  NYJ   17   3  BUF NYJ BUF   Good     M.Nugent   25
164     Out  CHI   13   2   GB CHI  GB   Good      R.Gould   25
80      Out  BAL    1   2  IND IND BAL   Good M.Vanderjagt   20

Here is an excerpt of data for field goal attempts in the 2008 NFL season, a dataframe i've called 'fg'. suppose that these 10 data points represent all of the field goals attempted in 2008; further suppose you want to know the the distance of the longest field goal attempted that year, who kicked it, and whether it was good or not; you also want to know the second-longest, as well as the third-longest, etc.; and finally you want the shortest field goal attempt.

Well, you could just do this:

sort(fg$Dist, decreasing=T)

which returns: 50 48 43 37 34 32 26 25 25 20

That is correct, but not very useful--it does tell us the distance of the longest field goal attempt, the second-longest,...as well as the shortest; however, but that's all we know--eg, we don't know who the kicker was, whether the attempt was successful, etc. Of course, we need the entire dataframe sorted on the "Dist" column (put another way, we want to sort all of the data rows on the single attribute Dist. that would look like this:

Stadium Home Week Qtr Away Off Def Result       Kicker Dist
751     Out  PHI   14   4  NYG PHI NYG   Good      D.Akers   50
307     Out  DEN   14   2  BAL DEN BAL   Good       J.Elam   48
571     Out   NE    1   2  OAK OAK  NE Missed S.Janikowski   43
702     Out  OAK   15   4  CLE CLE OAK   Good     P.Dawson   37
492     Out   KC   13   3  DEN  KC DEN   Good      L.Tynes   34
491     Out   KC    9   1  OAK OAK  KC   Good S.Janikowski   32
654     Out  NYG   11   2  PHI NYG PHI   Good      J.Feely   26
691     Out  NYJ   17   3  BUF NYJ BUF   Good     M.Nugent   25
164     Out  CHI   13   2   GB CHI  GB   Good      R.Gould   25
80      Out  BAL    1   2  IND IND BAL   Good M.Vanderjagt   20

This is what order does. It is 'sort' for two-dimensional data; put another way, it returns a 1D integer index comprised of the row numbers such that sorting the rows according to that vector, would give you a correct row-oriented sort on the column, Dist

Here's how it works. Above, sort was used to sort the Dist column; to sort the entire dataframe on the Dist column, we use 'order' exactly the same way as 'sort' is used above:

ndx = order(fg$Dist, decreasing=T)

(i usually bind the array returned from 'order' to the variable 'ndx', which stands for 'index', because i am going to use it as an index array to sort.)

that was step 1, here's step 2:

'ndx', what is returned by 'sort' is then used as an index array to re-order the dataframe, 'fg':

fg_sorted = fg[ndx,]

fg_sorted is the re-ordered dataframe immediately above.

In sum, 'sort' is used to create an index array (which specifies the sort order of the column you want sorted), which then is used as an index array to re-order the dataframe (or matrix).

What does O(log n) mean exactly?

If you had a function that takes:

1 millisecond to complete if you have 2 elements.
2 milliseconds to complete if you have 4 elements.
3 milliseconds to complete if you have 8 elements.
4 milliseconds to complete if you have 16 elements.
...
n milliseconds to complete if you have 2^n elements.

Then it takes log2(n) time. The Big O notation, loosely speaking, means that the relationship only needs to be true for large n, and that constant factors and smaller terms can be ignored.

How to decrypt an encrypted Apple iTunes iPhone backup?

Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.

http://www.elcomsoft.com/eppb.html

Listing all permutations of a string/integer

    //Generic C# Method
            private static List<T[]> GetPerms<T>(T[] input, int startIndex = 0)
            {
                var perms = new List<T[]>();

                var l = input.Length - 1;

                if (l == startIndex)
                    perms.Add(input);
                else
                {

                    for (int i = startIndex; i <= l; i++)
                    {
                        var copy = input.ToArray(); //make copy

                        var temp = copy[startIndex];

                        copy[startIndex] = copy[i];
                        copy[i] = temp;

                        perms.AddRange(GetPerms(copy, startIndex + 1));

                    }
                }

                return perms;
            }

            //usages
            char[] charArray = new char[] { 'A', 'B', 'C' };
            var charPerms = GetPerms(charArray);


            string[] stringArray = new string[] { "Orange", "Mango", "Apple" };
            var stringPerms = GetPerms(stringArray);


            int[] intArray = new int[] { 1, 2, 3 };
            var intPerms = GetPerms(intArray);

How to generate all permutations of a list?

I used an algorithm based on the factorial number system- For a list of length n, you can assemble each permutation item by item, selecting from the items left at each stage. You have n choices for the first item, n-1 for the second, and only one for the last, so you can use the digits of a number in the factorial number system as the indices. This way the numbers 0 through n!-1 correspond to all possible permutations in lexicographic order.

from math import factorial
def permutations(l):
    permutations=[]
    length=len(l)
    for x in xrange(factorial(length)):
        available=list(l)
        newPermutation=[]
        for radix in xrange(length, 0, -1):
            placeValue=factorial(radix-1)
            index=x/placeValue
            newPermutation.append(available.pop(index))
            x-=index*placeValue
        permutations.append(newPermutation)
    return permutations

permutations(range(3))

output:

[[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]

This method is non-recursive, but it is slightly slower on my computer and xrange raises an error when n! is too large to be converted to a C long integer (n=13 for me). It was enough when I needed it, but it's no itertools.permutations by a long shot.

Generate list of all possible permutations of a string

Recursive Approach

func StringPermutations(inputStr string) (permutations []string) {
    for i := 0; i < len(inputStr); i++ {
        inputStr = inputStr[1:] + inputStr[0:1]
        if len(inputStr) <= 2 {
            permutations = append(permutations, inputStr)
            continue
        }
        leftPermutations := StringPermutations(inputStr[0 : len(inputStr)-1])
        for _, leftPermutation := range leftPermutations {
            permutations = append(permutations, leftPermutation+inputStr[len(inputStr)-1:])
        }
    }
    return
}

C++: constructor initializer for arrays

You can do it, but it's not pretty:

#include <iostream>

class A {
    int mvalue;
public:
    A(int value) : mvalue(value) {}
    int value() { return mvalue; }
};

class B {
    // TODO: hack that respects alignment of A.. maybe C++14's alignof?
    char _hack[sizeof(A[3])];
    A* marr;
public:
    B() : marr(reinterpret_cast<A*>(_hack)) {
        new (&marr[0]) A(5);
        new (&marr[1]) A(6);
        new (&marr[2]) A(7);
    }

    A* arr() { return marr; }
};

int main(int argc, char** argv) {
    B b;
    A* arr = b.arr();
    std::cout << arr[0].value() << " " << arr[1].value() << " " << arr[2].value() << "\n";
    return 0;
}

If you put this in your code, I hope you have a VERY good reason.

Python: How do I make a subclass from a superclass?

You use:

class DerivedClassName(BaseClassName):

For details, see the Python docs, section 9.5.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

geom_smooth() what are the methods available?

The se argument from the example also isn't in the help or online documentation.

When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible

How to view file diff in git before commit

Did you try -v (or --verbose) option for git commit? It adds the diff of the commit in the message editor.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

$watch an object

The form object isn't changing, only the name property is

updated fiddle

function MyController($scope) {
$scope.form = {
    name: 'my name',
}

$scope.changeCount = 0;
$scope.$watch('form.name', function(newVal, oldVal){
    console.log('changed');
    $scope.changeCount++;
});
}

Select Last Row in the Table

Laravel collections has method last

Model::all() -> last(); // last element 
Model::all() -> last() -> pluck('name'); // extract value from name field. 

This is the best way to do it.

File Explorer in Android Studio

I am in Android 3.6.1, and the way " Top Menu > View > Tools Window > Device File Manager" doesn't work.Because there is no the "Device File Manager" option in Tools Window.

But I resolve the problem with another way:

1?Find the magnifier icon on the top right toobar. enter image description here

2?Click it and search "device" in the search bar, and you can see it. enter image description here

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

Table row and column number in jQuery

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

Angular cli generate a service and include the provider in one step

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module

Passing data through intent using Serializable

1- You are using android.graphics.Bitmap which doesn't implements Serializable class so you have to remove that class then it will work.

2- for brief you can visit how to pass data between intents.

JSON to TypeScript class instance?

Why could you not just do something like this?

class Foo {
  constructor(myObj){
     Object.assign(this, myObj);
  }
  get name() { return this._name; }
  set name(v) { this._name = v; }
}

let foo = new Foo({ name: "bat" });
foo.toJSON() //=> your json ...

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

Count textarea characters

_x000D_
_x000D_
var maxchar = 10;_x000D_
$('#message').after('<span id="count" class="counter"></span>');_x000D_
$('#count').html(maxchar+' of '+maxchar);_x000D_
$('#message').attr('maxlength', maxchar);_x000D_
$('#message').parent().addClass('wrap-text');_x000D_
$('#message').on("keydown", function(e){_x000D_
 var len =  $('#message').val().length;_x000D_
 if (len >= maxchar && e.keyCode != 8)_x000D_
     e.preventDefault();_x000D_
 else if(len <= maxchar && e.keyCode == 8){_x000D_
  if(len <= maxchar && len != 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len +1));_x000D_
     else if(len == 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len));_x000D_
 }else_x000D_
   $('#count').html(maxchar+' of '+(maxchar - len-1)); _x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="message" name="text"></textarea>
_x000D_
_x000D_
_x000D_

Oracle insert from select into table with more columns

just select '0' as the value for the desired column

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

What is the role of the package-lock.json?

package-lock.json is written to when a numerical value in a property such as the "version" property, or a dependency property is changed in package.json.

If these numerical values in package.json and package-lock.json match, package-lock.json is read from.

If these numerical values in package.json and package-lock.json do not match, package-lock.json is written to with those new values, and new modifiers such as the caret and tilde if they are present. But it is the numeral that is triggering the change to package-lock.json.

To see what I mean, do the following. Using package.json without package-lock.json, run npm install with:

{
  "name": "test",
  "version": "1.0.0",
  ...
  "devDependencies": {
    "sinon": "7.2.2"
  }
}

package-lock.json will now have:

"sinon": {
  "version": "7.2.2",

Now copy/paste both files to a new directory. Change package.json to (only adding caret):

{
  "name": "test",
  "version": "1.0.0",
  ...
  "devDependencies": {
    "sinon": "^7.2.2"
  }
}

run npm install. If there were no package-lock.json file, [email protected] would be installed. npm install is reading from package-lock.json and installing 7.2.2.

Now change package.json to:

{
  "name": "test",
  "version": "1.0.0",
  ...
  "devDependencies": {
    "sinon": "^7.3.0"
  }
}

run npm install. package-lock.json has been written to, and will now show:

"sinon": {
  "version": "^7.3.0",

Create list of object from another using Java 8 Streams

An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping does the same in one step:

//...
List<Employee> employees = persons.stream()
  .filter(p -> p.getLastName().equals("l1"))
  .collect(
    Collectors.mapping(
      p -> new Employee(p.getName(), p.getLastName(), 1000),
      Collectors.toList()));

Detailed example can be found here

How to show PIL Image in ipython notebook

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

Random float number generation

In my opinion the above answer do give some 'random' float, but none of them is truly a random float (i.e. they miss a part of the float representation). Before I will rush into my implementation lets first have a look at the ANSI/IEEE standard format for floats:

|sign (1-bit)| e (8-bits) | f (23-bit) |

the number represented by this word is (-1 * sign) * 2^e * 1.f

note the the 'e' number is a biased (with a bias of 127) number thus ranging from -127 to 126. The most simple (and actually most random) function is to just write the data of a random int into a float, thus

int tmp = rand();
float f = (float)*((float*)&tmp);

note that if you do float f = (float)rand(); it will convert the integer into a float (thus 10 will become 10.0).

So now if you want to limit the maximum value you can do something like (not sure if this works)

int tmp = rand();
float f = *((float*)&tmp);
tmp = (unsigned int)f       // note float to int conversion!
tmp %= max_number;
f -= tmp;

but if you look at the structure of the float you can see that the maximum value of a float is (approx) 2^127 which is way larger as the maximum value of an int (2^32) thus ruling out a significant part of the numbers that can be represented by a float. This is my final implementation:

/**
 * Function generates a random float using the upper_bound float to determine 
 * the upper bound for the exponent and for the fractional part.
 * @param min_exp sets the minimum number (closest to 0) to 1 * e^min_exp (min -127)
 * @param max_exp sets the maximum number to 2 * e^max_exp (max 126)
 * @param sign_flag if sign_flag = 0 the random number is always positive, if 
 *              sign_flag = 1 then the sign bit is random as well
 * @return a random float
 */
float randf(int min_exp, int max_exp, char sign_flag) {
    assert(min_exp <= max_exp);

    int min_exp_mod = min_exp + 126;

    int sign_mod = sign_flag + 1;
    int frac_mod = (1 << 23);

    int s = rand() % sign_mod;  // note x % 1 = 0
    int e = (rand() % max_exp) + min_exp_mod;
    int f = rand() % frac_mod;

    int tmp = (s << 31) | (e << 23) | f;

    float r = (float)*((float*)(&tmp));

    /** uncomment if you want to see the structure of the float. */
//    printf("%x, %x, %x, %x, %f\n", (s << 31), (e << 23), f, tmp, r);

    return r;
}

using this function randf(0, 8, 0) will return a random number between 0.0 and 255.0

What is the correct syntax of ng-include?

This worked for me:

ng-include src="'views/templates/drivingskills.html'"

complete div:

<div id="drivivgskills" ng-controller="DrivingSkillsCtrl" ng-view ng-include src="'views/templates/drivingskills.html'" ></div>

Default interface methods are only supported starting with Android N

My project use ButterKnife and Retro lambda, setting JavaVersion.VERSION_1_8 will not work. It always blames at ButterKnife static interface function until I found this Migrate from Retrolambda

TL;DR

Just add JavaVersion.VERSION_1_8 and completely REMOVE retrolambda from your project. It will build successfully.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Since you are explicitly also asking to handle columns that haven't yet been filled out, and I assume also don't want to mess with them if they have a word instead of a number, you might consider this:

=If(IsNumber(K23), If(K23 > 0, ........., 0), 0)

This just says... If K23 is a number; And if that number is greater than zero; Then do something ......... Otherwise, return zero.

In ........., you might put your division equation there, such as A1/K23, and you can rest assured that K23 is a number which is greater than zero.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

You can transfer those (simply by adding a remote to a GitHub repo and by pushing them)

  • create an empty repo on GitHub
  • git remote add github https://[email protected]/yourLogin/yourRepoName.git
  • git push --mirror github

The history will be the same.

But you will loose the access control (teams defined in GitLab with specific access rights on your repo)

If you facing any issue with the https URL of the GitHub repo:

The requested URL returned an error: 403

All you need to do is to enter your GitHub password, but the OP suggests:

Then you might need to push it the ssh way. You can read more on how to do it here.

See "Pushing to Git returning Error Code 403 fatal: HTTP request failed".

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How to print Unicode character in C++?

If you use Windows (note, we are using printf(), not cout):

//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
    SetConsoleOutputCP(65001); 
    printf("?\n");
}

Not Unicode but working - 1251 instead of UTF8:

//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
    SetConsoleOutputCP(1251); 
    cout << "?" << endl;
}

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

insert data into database with codeigniter

It will be better for you to write your code like this.

In your Controller Write this code.

    function new_blank_order_summary() {
     $query = $this->sales_model->order_summary_insert();
     if($query) {
        $this->load->view('sales/new_blank_order_summary'); 
    } else {
        $this->load->view('sales/data_insertion_failed');
    }
  }

and in your Model

function order_summary_insert() {
    $orderLines = trim(xss_clean($this->input->post('orderlines')));
    $customerName = trim(xss_clean($this->input->post('customer')));
    $data = array(
        'OrderLines'=>$orderLines,
        'CustomerName'=>$customerName
    );

    $this->db->insert('Customer_Orders',$data);
    return ($this->db->affected_rows() != 1) ? false : true;
}

How to check date of last change in stored procedure or function in SQL server

This is the correct solution for finding a function:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'fn'
AND name = 'fn_NAME'

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

javascript: using a condition in switch case

That's a case where you should use if clauses.

How to change legend size with matplotlib.pyplot

There are also a few named fontsizes, apart from the size in points:

xx-small
x-small
small
medium
large
x-large
xx-large

Usage:

pyplot.legend(loc=2, fontsize = 'x-small')

Search for a particular string in Oracle clob column

ok, you may use substr in correlation to instr to find the starting position of your string

select 
  dbms_lob.substr(
       product_details, 
       length('NEW.PRODUCT_NO'), --amount
       dbms_lob.instr(product_details,'NEW.PRODUCT_NO') --offset
       ) 
from my_table
where dbms_lob.instr(product_details,'NEW.PRODUCT_NO')>=1;

Custom HTTP headers : naming conventions

RFC6648 recommends that you assume that your custom header "might become standardized, public, commonly deployed, or usable across multiple implementations." Therefore, it recommends not to prefix it with "X-" or similar constructs.

However, there is an exception "when it is extremely unlikely that [your header] will ever be standardized." For such "implementation-specific and private-use" headers, the RFC says a namespace such as a vendor prefix is justified.

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

How do I redirect to the previous action in ASP.NET MVC?

If you want to redirect from a button in the View you could use:

@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})

How do I install a pip package globally instead of locally?

Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

How do I assert my exception message with JUnit Test annotation?

I never liked the way of asserting exceptions with Junit. If I use the "expected" in the annotation, seems from my point of view we're violating the "given, when, then" pattern because the "then" is placed at the top of the test definition.

Also, if we use "@Rule", we have to deal with so much boilerplate code. So, if you can install new libraries for your tests, I'd suggest to have a look to the AssertJ (that library now comes with SpringBoot)

Then a test which is not violating the "given/when/then" principles, and it is done using AssertJ to verify:

1 - The exception is what we're expecting. 2 - It has also an expected message

Will look like this:

 @Test
void should_throwIllegalUse_when_idNotGiven() {

    //when
    final Throwable raisedException = catchThrowable(() -> getUserDAO.byId(null));

    //then
    assertThat(raisedException).isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("Id to fetch is mandatory");
}

Can I change the scroll speed using css or jQuery?

Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.

https://github.com/nathco/jQuery.scrollSpeed

Here's a Demo

You can also try this. Here's a demo

The input is not a valid Base-64 string as it contains a non-base 64 character

And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file

string string64 = string64.Replace(@"""", string.Empty);
byte[] bytes = Convert.ToBase64String(string64);

Subtracting 2 lists in Python

I'd have to recommend NumPy as well

Not only is it faster for doing vector math, but it also has a ton of convenience functions.

If you want something even faster for 1d vectors, try vop

It's similar to MatLab, but free and stuff. Here's an example of what you'd do

from numpy import matrix
a = matrix((2,2,2))
b = matrix((1,1,1))
ret = a - b
print ret
>> [[1 1 1]]

Boom.

Import SQL file into mysql

For localhost on XAMPP. Open a cmd window and type

cd C:\xampp\mysql\bin
mysql.exe -u root -p

Attention! No semi-colon after -p Enter your password and type

use database_name;

to select the database you need.

Check if your table is there

show tables;

Import from your sql file

source sqlfile.sql;

I have put my file on C:\xampp\mysql\bin location in order to don't mix up with locations of sql file.

Python Replace \\ with \

In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print statement to see what the string actually looks like.

This example shows the difference:

>>> '\\'
'\\'
>>> print '\\'
\

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Why does the jquery change event not trigger when I set the value of a select using val()?

$(":input#single").trigger('change');

This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this

$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');

And the first event worked.

Jenkins/Hudson - accessing the current build number?

As per Jenkins Documentation,

BUILD_NUMBER

is used. This number is identify how many times jenkins run this build process $BUILD_NUMBER is general syntax for it.

What is a good regular expression to match a URL?

I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.

http://jsfiddle.net/nMVDS/1/

$(function () {
  $('#whitelist_add').keyup(function () {
    if ($(this).val() == '') { //Check to see if there is any text entered
        //If there is no text within the input, disable the button
        $('.whitelistCheck').attr('disabled', 'disabled');
    } else {
        // Domain name regular expression
        var regex = new RegExp("^([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
        if (regex.test($(this).val())) {
            // Domain looks OK
            //alert("Successful match");
            $('.whitelistCheck').removeAttr('disabled');
        } else {
            // Domain is NOT OK
            //alert("No match");
            $('.whitelistCheck').attr('disabled', 'disabled');
        }
    }
  });
});

HTML FORM:

<form action="domain_management.php" method="get">
    <input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
    <button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>

C++ getters/setters coding style

As an aside, in C++, it is somewhat odd to have a const reference member. You have to assign it in the constructor list. Who owns the actually memory of that object and what is it's lifetime?

As for style, I agree with the others that you don't want to expose your privates. :-) I like this pattern for setters/getters

class Foo
{
public:
  const string& FirstName() const;
  Foo& FirstName(const string& newFirstName);

  const string& LastName() const;
  Foo& LastName(const string& newLastName);

  const string& Title() const;
  Foo& Title(const string& newTitle);
};

This way you can do something like:

Foo f;
f.FirstName("Jim").LastName("Bob").Title("Programmer");

Get a filtered list of files in a directory

glob.glob() is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match(), something like so:

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]

More flexible, but as you note, less efficient.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

The existing answers have quite broken code. The DNS method does not work at all. Here is code that I used to configure my NIC:

public static class NetworkConfigurator
{
    /// <summary>
    /// Set's a new IP Address and it's Submask of the local machine
    /// </summary>
    /// <param name="ipAddress">The IP Address</param>
    /// <param name="subnetMask">The Submask IP Address</param>
    /// <param name="gateway">The gateway.</param>
    /// <param name="nicDescription"></param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask))
                        {
                            if (ipAddresses != null)
                            {
                                newIP["IPAddress"] = ipAddresses;
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask);
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Set's the DNS Server of the local machine
    /// </summary>
    /// <param name="nic">NIC address</param>
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public static void SetNameservers(string nicDescription, string[] dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers;
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

jQuery .attr("disabled", "disabled") not working in Chrome

It's an old post but I none of this solution worked for me so I'm posting my solution if anyone find this helpful.

I just had the same problem.

In my case the control I needed to disable was a user control with child dropdowns which I could disable in IE but not in chrome.

my solution was to disable each child object, not just the usercontrol, with that code:

$('#controlName').find('*').each(function () { $(this).attr("disabled", true); })

It's working for me in chrome now.

How to create a checkbox with a clickable label?

This should help you: W3Schools - Labels

<form>
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" />
  <br />
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" />
</form>

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

Add and remove attribute with jquery

If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.

var el = $("#page_navigation1");

$("#add").click(function(){
  el.attr("id","page_navigation1");
});     

$("#remove").click(function(){
  el.removeAttr("id");
});     

How to convert HTML file to word?

A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

I ran into this error message today and wanted to post the resolution to my particular my case. It turns out that my problem was that one of my css files was missing a closing brace and this was causing the file to not be compiled. It may be harder to notice this if you have an automated process that sets everything up (including the asset precompile) for your production environment.

How to increment a JavaScript variable using a button press event

Use type = "button" instead of "submit", then add an onClick handler for it.

For example:

<input type="button" value="Increment" onClick="myVar++;" />

Truncating long strings with CSS: feasible yet?

Update: text-overflow: ellipsis is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the innerHTML property in Firefox. See the end of this post for a workaround.

CSS

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

ellipsis.xml file contents

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
        <content>
            <xul:window>
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
            </xul:window>
        </content>
    </binding>
</bindings>

Updating node content

To update the content of a node in a way that works in Firefox use the following:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if (YAHOO.env.ua.gecko) {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);
    }
};

See Matt Snider's post for an explanation of how this works.

Make Bootstrap 3 Tabs Responsive

I have created a directive in agularJS supported with ng-bootStrap components

https://angular-ui.github.io/bootstrap/#!#tabs

here I share the code that I implemented

[https://jsfiddle.net/k1r02/u6gpv4dc/][1]

  [1]: https://jsfiddle.net/k1r02/u6gpv4dc/

SQL Server : fetching records between two dates?

The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <)

select * 
from xxx 
where dates >= '20121026'
  and dates <  '20121028'

If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.

select * 
from xxx 
where CAST(dates as DATE) between '20121026' and '20121027'

This explicitly tells SQL Server that you are only interested in the DATE portion of the dates column for comparison against the BETWEEN range.

how to access iFrame parent page using jquery?

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

How can I make setInterval also work when a tab is inactive in Chrome?

Playing an audio file ensures full background Javascript performance for the time being

For me, it was the simplest and least intrusive solution - apart from playing a faint / almost-empty sound, there are no other potential side effects

You can find the details here: https://stackoverflow.com/a/51191818/914546

(From other answers, I see that some people use different properties of the Audio tag, I do wonder whether it's possible to use the Audio tag for full performance, without actually playing something)

c++ array - expression must have a constant value

C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.

C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.

And I almost missed it - you need to declare a variable name, not just the array dimensions.

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

Installing TensorFlow on Windows (Python 3.6.x)

Just found Tensorflow 1.1 for python 3.6 on windows x64 (including GPU version, but i tested only cpu): http://www.lfd.uci.edu/~gohlke/pythonlibs/#tensorflow. Unofficial apparently, but worked for me when I import tensorflow or tflearn in my code. They have scipy for windows there and bunch of other packages.

For some reason pip install URL returns code 404, so the installation would be the following:

1) Download protobuf whl package from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/vu0h7y4r/protobuf-3.3.0-py3-none-any.whl

2) pip install {DownloadFolder}\protobuf-3.3.0-py3-none-any.whl

3) Download TF whl file: http://www.lfd.uci.edu/~gohlke/pythonlibs/vu0h7y4r/tensorflow-1.1.0-cp36-cp36m-win_amd64.whl

4) pip install {DownloadFolder}\tensorflow-1.1.0-cp36-cp36m-win_amd64.whl

It worked for me.

How do I access Configuration in any class in ASP.NET Core?

I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

  1. My startup class is as default
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
  1. My appsettings.json is like this
{
  "CompanySettings": {
    "name": "Fake Co"
  }
}

  1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;

public class EmployeeController 
{
    private IConfiguration _configuration;
    public EmployeeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
    var companyName = configuration.GetValue<string>("CompanySettings:name");
    // companyName = "Fake Co"
}

How to parse data in JSON format?

Can use either json or ast python modules:

Using json :
=============

import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")

Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2




Using ast:
==========

import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")

Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2

Spring Boot access static resources missing scr/main/resources

To get the files in the classpath :

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();

To read the file onStartup use @PostConstruct:

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}

Here is a Small example for reading an XML File on Spring Boot App startup.

Trim last character from a string

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }

What is "String args[]"? parameter in main method Java

I would break up

public static void main(String args[])

in parts.

"public" means that main() can be called from anywhere.

"static" means that main() doesn't belong to a specific object

"void" means that main() returns no value

"main" is the name of a function. main() is special because it is the start of the program.

"String[]" means an array of String.

"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

How can I check if a single character appears in a string?

I'm not sure what the original poster is asking exactly. Since indexOf(...) and contains(...) both probably use loops internally, perhaps he's looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

The other is far less elegant, but completeness...:

/**
 * Works for strings of up to 5 characters
 */
public boolean containsChar(String s, char search) {
    if (s.length() > 5) throw IllegalArgumentException();

    try {
        if (s.charAt(0) == search) return true;
        if (s.charAt(1) == search) return true;
        if (s.charAt(2) == search) return true;
        if (s.charAt(3) == search) return true;
        if (s.charAt(4) == search) return true;
    } catch (IndexOutOfBoundsException e) {
        // this should never happen...
        return false;
    }
    return false;
}

The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you're concerned that that length() uses a loop.

What is the use of the %n format specifier in C?

The argument associated with the %n will be treated as an int* and is filled with the number of total characters printed at that point in the printf.

How to detect control+click in Javascript from an onclick div attribute?

You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.

How to set a default value in react-select

If your options are like this

var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two' }
];

Your {props.input.value} should match one of the 'value' in your {props.options}

Meaning, props.input.value should be either 'one' or 'two'

Why use 'virtual' for class properties in Entity Framework model definitions?

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:

public virtual double Area() 
{
    return x * y;
}

You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The following example shows a virtual property:

class MyBaseClass
{
    // virtual auto-implemented property. Overrides can only
    // provide specialized behavior if they implement get and set accessors.
    public virtual string Name { get; set; }

    // ordinary virtual property with backing field
    private int num;
    public virtual int Number
    {
        get { return num; }
        set { num = value; }
    }
}


class MyDerivedClass : MyBaseClass
{
    private string name;

    // Override auto-implemented property with ordinary property
    // to provide specialized accessor behavior.
    public override string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (value != String.Empty)
            {
                name = value;
            }
            else
            {
                name = "Unknown";
            }
        }
    }
}

Swing vs JavaFx for desktop applications

As stated by Oracle, JavaFX is the next step in their Java based rich client strategy. Accordingly, this is what I recommend for your situation:

What would be easier and cleaner to maintain

  • JavaFX has introduced several improvements over Swing, such as, possibility to markup UIs with FXML, and theming with CSS. It has great potential to write a modular, clean & maintainable code.

What would be faster to build from scratch

  • This is highly dependent on your skills and the tools you use.
    • For swing, various IDEs offer tools for rapid development. The best I personally found is the GUI builder in NetBeans.
    • JavaFX has support from various IDEs as well, though not as mature as the support Swing has at the moment. However, its support for markup in FXML & CSS make GUI development on JavaFX intuitive.

MVC Pattern Support

  • JavaFX is very friendly with MVC pattern, and you can cleanly separate your work as: presentation (FXML, CSS), models(Java, domain objects) and logic(Java).
  • IMHO, the MVC support in Swing isn't very appealing. The flow you'll see across various components lacks consistency.

For more info, please take a look these FAQ post by Oracle regarding JavaFX here.

How to add spacing between columns?

    <div class="col-md-12 no_padding header_row"></div>



    <div class="second_row">
        <div class="col-md-4 box_shadow"></div>
        <div class="col-md-8 no_padding_right">
            <div class="col-md-12 box_shadow"></div>
        </div>
    </div>


    body{
    background:#F0F0F0;
}

.main_holder{
    min-height: 600px;
    margin-top: 40px;
    height: 600px;
}
.box_shadow{
    box-shadow: 0 1px 2px rgba(0,0,0,.1);
    background: white;
    height: auto;
    min-height: 500px;
}

.no_padding{
    padding: 0px !important;
}

.no_padding_right{
    padding-right: 0px !important;
}

.header_row{
    height: 60px;
    background: #00796B;
    -webkit-box-shadow: 0px 0px 9px 1px rgba(143,140,143,1);
    -moz-box-shadow: 0px 0px 9px 1px rgba(143,140,143,1);
    box-shadow: 0px 0px 9px 1px rgba(143,140,143,1); 
}

.second_row{
    position: relative;
    width: 100% !important;
    top: 20px;
}

How do I work with dynamic multi-dimensional arrays in C?

// use new instead of malloc as using malloc leads to memory leaks `enter code here

    int **adj_list = new int*[rowsize];       
    for(int i = 0; i < rowsize; ++i)    
    {

        adj_list[i] = new int[colsize];

    }

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

What is "entropy and information gain"?

I assume entropy was mentioned in the context of building decision trees.

To illustrate, imagine the task of learning to classify first-names into male/female groups. That is given a list of names each labeled with either m or f, we want to learn a model that fits the data and can be used to predict the gender of a new unseen first-name.

name       gender
-----------------        Now we want to predict 
Ashley        f              the gender of "Amro" (my name)
Brian         m
Caroline      f
David         m

First step is deciding what features of the data are relevant to the target class we want to predict. Some example features include: first/last letter, length, number of vowels, does it end with a vowel, etc.. So after feature extraction, our data looks like:

# name    ends-vowel  num-vowels   length   gender
# ------------------------------------------------
Ashley        1         3           6        f
Brian         0         2           5        m
Caroline      1         4           8        f
David         0         2           5        m

The goal is to build a decision tree. An example of a tree would be:

length<7
|   num-vowels<3: male
|   num-vowels>=3
|   |   ends-vowel=1: female
|   |   ends-vowel=0: male
length>=7
|   length=5: male

basically each node represent a test performed on a single attribute, and we go left or right depending on the result of the test. We keep traversing the tree until we reach a leaf node which contains the class prediction (m or f)

So if we run the name Amro down this tree, we start by testing "is the length<7?" and the answer is yes, so we go down that branch. Following the branch, the next test "is the number of vowels<3?" again evaluates to true. This leads to a leaf node labeled m, and thus the prediction is male (which I happen to be, so the tree predicted the outcome correctly).

The decision tree is built in a top-down fashion, but the question is how do you choose which attribute to split at each node? The answer is find the feature that best splits the target class into the purest possible children nodes (ie: nodes that don't contain a mix of both male and female, rather pure nodes with only one class).

This measure of purity is called the information. It represents the expected amount of information that would be needed to specify whether a new instance (first-name) should be classified male or female, given the example that reached the node. We calculate it based on the number of male and female classes at the node.

Entropy on the other hand is a measure of impurity (the opposite). It is defined for a binary class with values a/b as:

Entropy = - p(a)*log(p(a)) - p(b)*log(p(b))

This binary entropy function is depicted in the figure below (random variable can take one of two values). It reaches its maximum when the probability is p=1/2, meaning that p(X=a)=0.5 or similarlyp(X=b)=0.5 having a 50%/50% chance of being either a or b (uncertainty is at a maximum). The entropy function is at zero minimum when probability is p=1 or p=0 with complete certainty (p(X=a)=1 or p(X=a)=0 respectively, latter implies p(X=b)=1).

https://en.wikipedia.org/wiki/File:Binary_entropy_plot.svg

Of course the definition of entropy can be generalized for a discrete random variable X with N outcomes (not just two):

entropy

(the log in the formula is usually taken as the logarithm to the base 2)


Back to our task of name classification, lets look at an example. Imagine at some point during the process of constructing the tree, we were considering the following split:

     ends-vowel
      [9m,5f]          <--- the [..,..] notation represents the class
    /          \            distribution of instances that reached a node
   =1          =0
 -------     -------
 [3m,4f]     [6m,1f]

As you can see, before the split we had 9 males and 5 females, i.e. P(m)=9/14 and P(f)=5/14. According to the definition of entropy:

Entropy_before = - (5/14)*log2(5/14) - (9/14)*log2(9/14) = 0.9403

Next we compare it with the entropy computed after considering the split by looking at two child branches. In the left branch of ends-vowel=1, we have:

Entropy_left = - (3/7)*log2(3/7) - (4/7)*log2(4/7) = 0.9852

and the right branch of ends-vowel=0, we have:

Entropy_right = - (6/7)*log2(6/7) - (1/7)*log2(1/7) = 0.5917

We combine the left/right entropies using the number of instances down each branch as weight factor (7 instances went left, and 7 instances went right), and get the final entropy after the split:

Entropy_after = 7/14*Entropy_left + 7/14*Entropy_right = 0.7885

Now by comparing the entropy before and after the split, we obtain a measure of information gain, or how much information we gained by doing the split using that particular feature:

Information_Gain = Entropy_before - Entropy_after = 0.1518

You can interpret the above calculation as following: by doing the split with the end-vowels feature, we were able to reduce uncertainty in the sub-tree prediction outcome by a small amount of 0.1518 (measured in bits as units of information).

At each node of the tree, this calculation is performed for every feature, and the feature with the largest information gain is chosen for the split in a greedy manner (thus favoring features that produce pure splits with low uncertainty/entropy). This process is applied recursively from the root-node down, and stops when a leaf node contains instances all having the same class (no need to split it further).

Note that I skipped over some details which are beyond the scope of this post, including how to handle numeric features, missing values, overfitting and pruning trees, etc..

how to remove time from datetime

SELECT DATE('2012-11-12 00:00:00');

returns

2012-11-12

Python String and Integer concatenation

I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

    myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
        No_ofposition=[]
        mynewlist_2=[]
        for i in xrange(0,4,1):
            mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
            if len(mynewlist_2[i])>0:
                No_ofposition.append(i)
mynewlist_2
No_ofposition

Fix footer to bottom of page

This code working for me :

footer{
    background-color: #333;
    color: #EEE;
    padding: 20px;
    left: 0;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Important thing you should added bottom:0; and position: fixed;

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

JRE installation directory in Windows

Following on from my other comment, here's a batch file which displays the current JRE or JDK based on the registry values.

It's different from the other solutions in instances where java is installed, but not on the PATH.

@ECHO off

SET KIT=JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

ECHO Failed to find Java
GOTO :EOF

:FoundJRE
call:ReadRegValue JAVAPATH "HKLM\Software\%KIT%\%VER%" "JavaHome"
ECHO %JAVAPATH%
GOTO :EOF

:ReadRegValue
SET key=%2%
SET name=%3%
SET "%~1="
SET reg=reg
IF DEFINED ProgramFiles(x86) (
  IF EXIST %WINDIR%\sysnative\reg.exe SET reg=%WINDIR%\sysnative\reg.exe
)
FOR /F "usebackq tokens=3* skip=1" %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET "%~1=%%A %%B"
GOTO :EOF

How to find the statistical mode?

Here are several ways you can do it in Theta(N) running time

from collections import defaultdict

def mode1(L):
    counts = defaultdict(int)
    for v in L:
        counts[v] += 1
    return max(counts,key=lambda x:counts[x])

def mode2(L):
    vals = set(L)
    return max(vals,key=lambda x: L.count(x))
def mode3(L):
    return max(set(L), key=lambda x: L.count(x))

What is the best Java library to use for HTTP POST, GET etc.?

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

some highlight features:

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
    • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • Granular non-standards configuration and tracking.
    • Transparent connections through HTTP proxies.
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • Plug-in mechanism for custom authentication methods.
    • Multi-Part form POST for uploading large files.
    • Pluggable secure sockets implementations, making it easier to use third party solutions
    • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
    • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
    • Plug-in mechanism for custom cookie policies.
    • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
    • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
    • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
    • Direct access to the response code and headers sent by the server.
    • The ability to set connection timeouts.
    • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
    • Source code is freely available under the Apache Software License.

Insert variable into Header Location PHP

There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.

You need to concatenate multiple variables:

header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

get and set in TypeScript

TypeScript uses getter/setter syntax that is like ActionScript3.

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty() feature.

var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (value) {
            this._bar = value;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

So to use it,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target flag like this;

tsc --target ES5

If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:

As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.

How to remove all .svn directories from my application directories

Try this:

find . -name .svn -exec rm -v {} \;

Read more about the find command at developerWorks.

How to filter rows in pandas by regex

Use contains instead:

In [10]: df.b.str.contains('^f')
Out[10]: 
0    False
1     True
2     True
3    False
Name: b, dtype: bool

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

How to save to local storage using Flutter?

I was looking for the same, simple local storage but also with a reasonable level of security. The two solutions I've found that make the most sense are flutter_secure_storage (as mentioned by Raouf) for the small stuff, and hive for larger datasets.

'NOT NULL constraint failed' after adding to models.py

Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

Compilation error: stray ‘\302’ in program etc

I got the same with a character that visibly appeared as an asterisk, but was a UTF-8 sequence instead.

Encoder * st;

When compiled returned:

g.c:2:1: error: stray ‘\342’ in program
g.c:2:1: error: stray ‘\210’ in program
g.c:2:1: error: stray ‘\227’ in program

342 210 227 turns out to be UTF-8 for ASTERISK OPERATOR.

Deleting the '*' and typing it again fixed the problem.

How to create a windows service from java app

Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.

Require .NET runtime installed.

Style input type file?

use uniform js plugin to style input of any type, select, textarea.

The URL is http://uniformjs.com/

Getting title and meta tags from external website

Improved answer from @shamittomar above to get the meta tags (or the specified one from html source)

Can be improved further... the difference from php's default get_meta_tags is that it works even when there is unicode string

function getMetaTags($html, $name = null)
{
    $doc = new DOMDocument();
    try {
        @$doc->loadHTML($html);
    } catch (Exception $e) {

    }

    $metas = $doc->getElementsByTagName('meta');

    $data = [];
    for ($i = 0; $i < $metas->length; $i++)
    {
        $meta = $metas->item($i);

        if (!empty($meta->getAttribute('name'))) {
            // will ignore repeating meta tags !!
            $data[$meta->getAttribute('name')] = $meta->getAttribute('content');
        }
    }

    if (!empty($name)) {
        return !empty($data[$name]) ? $data[$name] : false;
    }

    return $data;
}

How do I handle Database Connections with Dapper in .NET?

Best practice is a real loaded term. I like a DbDataContext style container like Dapper.Rainbow promotes. It allows you to couple the CommandTimeout, transaction and other helpers.

For example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

using Dapper;

// to have a play, install Dapper.Rainbow from nuget

namespace TestDapper
{
    class Program
    {
        // no decorations, base class, attributes, etc 
        class Product 
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public DateTime? LastPurchase { get; set; }
        }

        // container with all the tables 
        class MyDatabase : Database<MyDatabase>
        {
            public Table<Product> Products { get; set; }
        }

        static void Main(string[] args)
        {
            var cnn = new SqlConnection("Data Source=.;Initial Catalog=tempdb;Integrated Security=True");
            cnn.Open();

            var db = MyDatabase.Init(cnn, commandTimeout: 2);

            try
            {
                db.Execute("waitfor delay '00:00:03'");
            }
            catch (Exception)
            {
                Console.WriteLine("yeah ... it timed out");
            }


            db.Execute("if object_id('Products') is not null drop table Products");
            db.Execute(@"create table Products (
                    Id int identity(1,1) primary key, 
                    Name varchar(20), 
                    Description varchar(max), 
                    LastPurchase datetime)");

            int? productId = db.Products.Insert(new {Name="Hello", Description="Nothing" });
            var product = db.Products.Get((int)productId);

            product.Description = "untracked change";

            // snapshotter tracks which fields change on the object 
            var s = Snapshotter.Start(product);
            product.LastPurchase = DateTime.UtcNow;
            product.Name += " World";

            // run: update Products set LastPurchase = @utcNow, Name = @name where Id = @id
            // note, this does not touch untracked columns 
            db.Products.Update(product.Id, s.Diff());

            // reload
            product = db.Products.Get(product.Id);


            Console.WriteLine("id: {0} name: {1} desc: {2} last {3}", product.Id, product.Name, product.Description, product.LastPurchase);
            // id: 1 name: Hello World desc: Nothing last 12/01/2012 5:49:34 AM

            Console.WriteLine("deleted: {0}", db.Products.Delete(product.Id));
            // deleted: True 


            Console.ReadKey();
        }
    }
}

Print line numbers starting at zero using awk

NR starts at 1, so use

awk '{print NR-1 "," $0}'

How to bring a window to the front?

There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.

But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:

"If this Window is visible, brings this Window to the front and may make it the focused Window."

Copy folder recursively, excluding some folders

Use tar along with a pipe.

cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )

You can even use this technique across ssh.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Maven does not find JUnit tests to run

Such problem might occur when you use surfire plugin 3.x.x+ with JUnit5 and by mistake annotate the test class with @Test annotation from JUnit4.

Use: org.junit.jupiter.api.Test (JUnit5) instead of org.junit.Test (Junit4)

NOTE: this might be hard to notice as the IDE might run this wihout problems just as JUnit4 test.

"Permission Denied" trying to run Python on Windows 10

This issue is far too common to still be persistent. And most answers and instructions fail to address it. Here's what to do on Windows 10:

  1. Type environment variables in the start search bar, and open Edit the System Environment Variables.

  2. Click Environment Variables...

  3. In the System Variables section, locate the variable with the key Path and double click it.

  4. Look for paths pointing to python files. Likely there are none. If there are, select and delete them.

  5. Create a new variable set to the path to your python executable. Normally this is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Python38. Ensure this by checking via your File Explorer.

    Note: If you can't see AppData, it's because you've not enabled viewing of hidden items: click the View tab and tick the Hidden Items checkbox.

  6. Create another variable pointing to the Scripts directory. Typically it is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Scripts.

  7. Restart your terminal and try typing py, python, python3, or python.exe.

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

How to create unique keys for React elements?

I am using this:

<div key={+new Date() + Math.random()}>

"Operation must use an updateable query" error in MS Access

You have to remove the IMEX=1 if you want to update. ;)

"IMEX=1; tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative." https://www.connectionstrings.com/excel/

Input type for HTML form for integer

You should change your type to number If you accept decimals first and remove them on keyUp, you might solve this...

$("#state").on('keyup', function(){
    $(this).val($(this).val().replace(".", ''));
})

or

$("#state").on('keyup', function(){
    $(this).val(parseInt($(this).val()));
})

This will remove the period, but there is no 'Integer Type'.

Print a list in reverse order with range()?

range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Save bitmap to location

Make sure the directory is created before you call bitmap.compress:

new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();

jQuery DataTables: control table width

Just to say I've had exactly the same problem as you, although I was just apply JQuery to a normal table without any Ajax. For some reason Firefox doesn't expand the table out after revealing it. I fixed the problem by putting the table inside a DIV, and applying the effects to the DIV instead.

When is it appropriate to use C# partial classes?

One great use is separating generated code from hand-written code that belong in the same class.

For example since LINQ to SQL uses partial classes you can write your own implementation of certain pieces of functionality (like Many-to-Many relationships) and those pieces of custom code won't get overwritten when you re-generate the code.

The same goes for WinForms code. All the Designer generated code goes in one file that you generally don't touch. Your hand-written code goes in another file. That way, when you change something in Designer, your changes don't get blown away.

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

This is concerning "Build Solution" option only.

I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.

Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:

enter image description here

In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.

How to use Oracle ORDER BY and ROWNUM correctly?

Use ROW_NUMBER() instead. ROWNUM is a pseudocolumn and ROW_NUMBER() is a function. You can read about difference between them and see the difference in output of below queries:

SELECT * FROM (SELECT rownum, deptno, ename
           FROM scott.emp
        ORDER BY deptno
       )
 WHERE rownum <= 3
 /

ROWNUM    DEPTNO    ENAME
---------------------------
 7        10    CLARK
 14       10    MILLER
 9        10    KING


 SELECT * FROM 
 (
  SELECT deptno, ename
       , ROW_NUMBER() OVER (ORDER BY deptno) rno
  FROM scott.emp
 ORDER BY deptno
 )
WHERE rno <= 3
/

DEPTNO    ENAME    RNO
-------------------------
10    CLARK        1
10    MILLER       2
10    KING         3

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

Do Facebook Oauth 2.0 Access Tokens Expire?

Yes, they do expire. There is an 'expires' value that is passed along with the 'access_token', and from what I can tell it's about 2 hours. I've been searching, but I don't see a way to request a longer expiration time.

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

Inject service in app.config

Easiest way: $injector = angular.element(document.body).injector()

Then use that to run invoke() or get()

Convert Mongoose docs to json

I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:

UserModel.find({}, function (err, users) {
    console.log(users.save);    // { [Function] numAsyncPres: 0 }
    var json = JSON.stringify(users);
    users = users.map(function (user) {
        return user.toObject();
    }
    console.log(user.save);    // undefined
    console.log(json == JSON.stringify(users));    // true
}

doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.

How to draw a line in android

If you want to have a simple Line in your Layout to separate two views you can use a generic View with the height and width you want the line to have and a set background color.

With this approach you don't need to override a View or use a Canvas yourself just simple and clean add the line in xml.

<View
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="@android:color/black" />

The example code I provided will generate a line that fills the screen in width and has a height of one dp.

If you have problems with the drawing of the line on small screens consider to change the height of the line to px. The problem is that on a ldpi screen the line will be 0.75 pixel high. Sometimes this may result in a rounding that makes the line vanish. If this is a problem for your layout define the width of the line a ressource file and create a separate ressource file for small screens that sets the value to 1px instead of 1dp.

This approach is only usable if you want horizontal or vertical lines that are used to divide layout elements. If you want to achieve something like a cross that is drawn into an image my approach will not work.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Check my solution, It will work.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) Download link ( https://www.visualsvn.com/downloads/ )

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the pic:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

java.net.SocketException: Connection reset

There are several possible causes.

  1. The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.

  2. More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.

  3. It can also be caused by closing a socket when there is unread data in the socket receive buffer.

  4. In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.

What are enums and why are they useful?

It is useful to know that enums are just like the other classes with Constant fields and a private constructor.

For example,

public enum Weekday
{
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
} 

The compiler compiles it as follows;

class Weekday extends Enum
{
  public static final Weekday MONDAY  = new Weekday( "MONDAY",   0 );
  public static final Weekday TUESDAY = new Weekday( "TUESDAY ", 1 );
  public static final Weekday WEDNESDAY= new Weekday( "WEDNESDAY", 2 );
  public static final Weekday THURSDAY= new Weekday( "THURSDAY", 3 );
  public static final Weekday FRIDAY= new Weekday( "FRIDAY", 4 );
  public static final Weekday SATURDAY= new Weekday( "SATURDAY", 5 );
  public static final Weekday SUNDAY= new Weekday( "SUNDAY", 6 );

  private Weekday( String s, int i )
  {
    super( s, i );
  }

  // other methods...
}

Call ASP.NET function from JavaScript?

The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.

I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:

Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))

Then you can do things like:

<Ajax.AjaxMethod()> _
Public Function Get5() AS Integer
    Return 5
End Function

Then, you can call it on your page as:

PageClassName.Get5(javascriptCallbackFunction);

The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned.

Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:

import re

myfile = "path/test.xml"

with open(myfile, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
    f.truncate()

The other way is to read the file then open it again with open(myfile, 'w'):

with open(myfile, "r") as f:
    data = f.read()

with open(myfile, "w") as f:
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))

Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).

By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html

How to change FontSize By JavaScript?

Please never do this in real projects:

_x000D_
_x000D_
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
_x000D_
_x000D_

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Git push/clone to new server

remote server> cd /home/ec2-user
remote server> git init --bare --shared  test
add ssh pub key to remote server
local> git remote add aws ssh://ec2-user@<hostorip>:/home/ec2-user/dev/test
local> git push aws master

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Somehow I had the wrong versions of the DLLs registered in my project.

  • I removed the three references to the Crystal Report dlls from my project. Crystal DLLs
  • I right click References, and click Add Reference
  • In the popup window, I click the Browse menu on the left and the Browse button Reference Manager
  • In the Directory window where your DLLs reside (perhaps your application's bin directory), select the three Crystal Reports DLLs and then click Add. DLLs
  • Back at the Reference Manager window, click in the first column to the left of the three Crystal dlls, and then click OK enter image description here
  • At this point your Crystal Reports should work again.

accepting HTTPS connections with self-signed certificates

Maybe this will helpful... it works on java clients using self-signed certificates (there is no check of the certificate). Be careful and use it only for development cases because that is no secure at all!!

How to ignore SSL certificate errors in Apache HttpClient 4.0

Hope it will works on Android just adding HttpClient library... good luck!!

Conditional Logic on Pandas DataFrame

In this specific example, where the DataFrame is only one column, you can write this elegantly as:

df['desired_output'] = df.le(2.5)

le tests whether elements are less than or equal 2.5, similarly lt for less than, gt and ge.

Add CSS or JavaScript files to layout head from views or partial views

Try the out-of-the-box solution (ASP.NET MVC 4 or later):

@{
    var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");

    bundle.Include("~/Scripts/myFile.js");
}

Send POST request using NSURLSession

You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server.

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
                     @"IOS TYPE", @"typemap",
                     nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];

Hope this helps (I'm trying to sort a CSRF authenticity issue with the above - but it does send the params in the NSDictionary).

Process.start: how to get the output?

You can log process output using below code:

ProcessStartInfo pinfo = new ProcessStartInfo(item);
pinfo.CreateNoWindow = false;
pinfo.UseShellExecute = true;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = true;
pinfo.RedirectStandardError = true;
pinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
var p = Process.Start(pinfo);
p.WaitForExit();
Process process = Process.Start(new ProcessStartInfo((item + '>' + item + ".txt"))
{
    UseShellExecute = false,
    RedirectStandardOutput = true
});
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0) { 
}

Convert SVG to image (JPEG, PNG, etc.) in the browser

jbeard4 solution worked beautifully.

I'm using Raphael SketchPad to create an SVG. Link to the files in step 1.

For a Save button (id of svg is "editor", id of canvas is "canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});

How to know the size of the string in bytes?

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

Drop all tables command

rm db/development.sqlite3

How to write multiple conditions of if-statement in Robot Framework

Just make sure put single space before and after "and" Keyword..

converting multiple columns from character to numeric format in r

You could use convert from the hablar package:

library(dplyr)
library(hablar)

# Sample df (stolen from the solution by Luca Braglia)
df <- tibble("a" = as.character(0:5),
                 "b" = paste(0:5, ".1", sep = ""),
                 "c" = letters[1:6])

# insert variable names in num()
df %>% convert(num(a, b))

Which gives you:

# A tibble: 6 x 3
      a     b c    
  <dbl> <dbl> <chr>
1    0. 0.100 a    
2    1. 1.10  b    
3    2. 2.10  c    
4    3. 3.10  d    
5    4. 4.10  e    
6    5. 5.10  f   

Or if you are lazy, let retype() from hablar guess the right data type:

df %>% retype()

which gives you:

# A tibble: 6 x 3
      a     b c    
  <int> <dbl> <chr>
1     0 0.100 a    
2     1 1.10  b    
3     2 2.10  c    
4     3 3.10  d    
5     4 4.10  e    
6     5 5.10  f   

Binding List<T> to DataGridView in WinForm

Every time you add a new element to the List you need to re-bind your Grid. Something like:

List<Person> persons = new List<Person>();
persons.Add(new Person() { Name = "Joe", Surname = "Black" });
persons.Add(new Person() { Name = "Misha", Surname = "Kozlov" });
dataGridView1.DataSource = persons;

// added a new item
persons.Add(new Person() { Name = "John", Surname = "Doe" });
// bind to the updated source
dataGridView1.DataSource = persons;

How to convert Rows to Columns in Oracle?

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns:

CREATE TABLE doc_tab (
  loan_number VARCHAR2(20),
  document_type VARCHAR2(20),
  document_id VARCHAR2(20)
);

INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');

COMMIT;

SELECT
    loan_number,
    MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
    MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
    MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;

Output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     

You can achieve the same using Oracle PIVOT clause, introduced in 11g:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);

SQLFiddle example with both solutions: SQLFiddle example

Read more about pivoting here: Pivot In Oracle by Tim Hall

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

How to fill the whole canvas with specific color?

If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

Format decimal for percentage values?

If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.

For example, to get a decimal value with a trailing "%" and no space between the value and the "%":

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

More complete example:

using System.Globalization; 

...

decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692

public void setAttributeValue(WebElement elem, String value){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
        elem, "value", value
    );
}

this takes advantage of selenium findElementBy function where xpath can be used also.

Best practices for adding .gitignore file for Python projects?

Github has a great boilerplate .gitignore

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Rope
.ropeproject

# Django stuff:
*.log
*.pot

# Sphinx documentation
docs/_build/

Why do I get an error instantiating an interface?

Imagine if one went into a store and asked for a device with a power switch. You didn't say whether you wanted a copier, television, vacuum cleaner, desk lamp, waffle maker, or anything. You asked for a device with a power switch. Would you expect the clerk to offer you something that could only be described as "a device with a power switch"?

A typical interface would be analogous to the description "a device with a power switch". Knowing that a piece of equipment is " a device with a power switch" would allow one to do some operations with it (i.e. turn it on and off), and one might plausibly want a list of e.g. "devices with power switches that will need to be turned off at the end of the day", without the devices having to share any characteristic beyond having a power switch, but such situations generally only apply when applying some common operation to devices that were created for some more specific purpose. When creating something from scratch, one would more likely wand a "copier", "television", "vacuum cleaner", or other particular type of device, than some random "device with a power switch".

There are some circumstances where one may want a vaguely-defined object, and really not care about what exactly it is. "Give me your cheapest device that can boil water". It would be nice if one could specify that when someone asks for an arbitrary object with "water boiling" ability, they should be offered an Acme 359 Electric Teakettle, and indeed when using classes it's possible to do that. Note, however, that someone who asks for a "device to boil water" would not be given a "device to boil water", but an "Acme 359 Electric Teakettle".

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

Listing files in a specific "folder" of a AWS S3 bucket

you can check the type. s3 has a special application/x-directory

bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }

Swift - Integer conversion to Hours/Minutes/Seconds

Another way would be convert seconds to date and take the components i.e seconds, minutes and hour from date itself. This solution has limitation only till 23:59:59

Difference between $(this) and event.target?

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

Making a list of evenly spaced numbers in a certain range in python

You can use the following approach:

[lower + x*(upper-lower)/length for x in range(length)]

lower and/or upper must be assigned as floats for this approach to work.

Check free disk space for current partition in bash

Yes:

df -k .

for the current directory.

df -k /some/dir

if you want to check a specific directory.

You might also want to check out the stat(1) command if your system has it. You can specify output formats to make it easier for your script to parse. Here's a little example:

$ echo $(($(stat -f --format="%a*%S" .)))

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

With arrays, why is it the case that a[5] == 5[a]?

Well, this is a feature that is only possible because of the language support.

The compiler interprets a[i] as *(a+i) and the expression 5[a] evaluates to *(5+a). Since addition is commutative it turns out that both are equal. Hence the expression evaluates to true.

How to hide element label by element id in CSS?

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

simple vba code gives me run time error 91 object variable or with block not set

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

Android Studio doesn't recognize my device

I am sorry that i bothered you all. The problem was my device is cloned in different places in device manager. It was gone when I tried to update driver for my phone in "Other devices" list, and before i have been updating it in wrong sections. Thank you all.

compareTo with primitives -> Integer / int

They're already ints. Why not just use subtraction?

compare = a - b;

Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.

CSS: Fix row height

You can also try this, if this is what you need:

<style type="text/css">
   ....
   table td div {height:20px;overflow-y:hidden;}
   table td.col1 div {width:100px;}
   table td.col2 div {width:300px;}
</style>


<table>
<tbody>
    <tr><td class="col1"><div>test</div></td></tr>
    <tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

What do we mean by org.hibernate.exception.SQLGrammarException?

Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).

and in my words there is a kind of Grammar mistake inside of your hibernate.cfg.xml configuration file,

it happens when you write wrong schema defination property name inside, like below example:

<property name="hibernate.connection.hbm2ddl.auto">create</property>

which supposed to be like:

<property name="hibernate.hbm2ddl.auto">create</property>

I'm getting favicon.ico error

The accepted answer didn't work for me, I had to add a value to the href attribute:

<link rel="shortcut icon" href="#" />

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

Modular multiplicative inverse function in Python

You might also want to look at the gmpy module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:

>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)

Updated answer

As noted by @hyh , the gmpy.invert() returns 0 if the inverse does not exist. That matches the behavior of GMP's mpz_invert() function. gmpy.divm(a, b, m) provides a general solution to a=bx (mod m).

>>> gmpy.divm(1, 1234567, 1000000007)
mpz(989145189)
>>> gmpy.divm(1, 0, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 9)
mpz(7)

divm() will return a solution when gcd(b,m) == 1 and raises an exception when the multiplicative inverse does not exist.

Disclaimer: I'm the current maintainer of the gmpy library.

Updated answer 2

gmpy2 now properly raises an exception when the inverse does not exists:

>>> import gmpy2

>>> gmpy2.invert(0,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: invert() no inverse exists

How to find all links / pages on a website

function getalllinks($url) {
    $links = array();
    if ($fp = fopen($url, 'r')) {
        $content = '';
        while ($line = fread($fp, 1024)) {
            $content. = $line;
        }
    }
    $textLen = strlen($content);
    if ($textLen > 10) {
        $startPos = 0;
        $valid = true;
        while ($valid) {
            $spos = strpos($content, '<a ', $startPos);
            if ($spos < $startPos) $valid = false;
            $spos = strpos($content, 'href', $spos);
            $spos = strpos($content, '"', $spos) + 1;
            $epos = strpos($content, '"', $spos);
            $startPos = $epos;
            $link = substr($content, $spos, $epos - $spos);
            if (strpos($link, 'http://') !== false) $links[] = $link;
        }
    }
    return $links;
}

try this code....

How to call a button click event from another method

You can perform different approaches to work around this. The best approach is, if your both buttons are suppose to do the same job, you can define a third function to do the job. for example :

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
    myJob()  
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
    myJob()
}

private void myJob()
{
    // Your code here
}

but if you are still persisting on doing it in your way, the best action is :

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
   SubGraphButton_Click.PerformClick();
}

Website screenshots

LAST EDIT: after 7 years I'm still getting upvotes for this answer, but I guess this one is now much more accurate.


Sure you can, but you'll need to render the page with something. If you really want to only use php, I suggest you HTMLTOPS, which renders the page and outputs it in a ps file (ghostscript), then, convert it in a .jpg, .png, .pdf.. can be little slower with complex pages (and don't support all the CSS).

Else, you can use wkhtmltopdf to output a html page in pdf, jpg, whatever.. Accept CSS2.0, use the webkit (safari's wrapper) to render the page.. so should be fine. You have to install it on your server, as well..

UPDATE Now, with new HTML5 and JS feature, is also possible to render the page into a canvas object using JavaScript. Here a nice library to do that: Html2Canvas and here is an implementation by the same author to get a feedback like G+. Once you have rendered the dom into the canvas, you can then send to the server via ajax and save it as a jpg.

EDIT: You can use the imagemagick tool for transforming pdf to png. My version of wkhtmltopdf does not support images. E.g. convert html.pdf -append html.png.

EDIT: This small shell script gives a simple / but working usage example on linux with php5-cli and the tools mentioned above.

EDIT: i noticed now that the wkhtmltopdf team is working on another project: wkhtmltoimage, that gives you the jpg directly

Excel how to fill all selected blank cells with text

Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!

What's the proper way to compare a String to an enum value?

My idea:

public enum SomeKindOfEnum{
    ENUM_NAME("initialValue");

    private String value;

    SomeKindOfEnum(String value){
        this.value = value;
    }

    public boolean equalValue(String passedValue){
        return this.value.equals(passedValue);
    }
}

And if u want to check Value u write:

SomeKindOfEnum.ENUM_NAME.equalValue("initialValue")

Kinda looks nice for me :). Maybe somebody will find it useful.

Define a struct inside a class in C++

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the virtual machine Java code executes on

JRE is the environment (standard libraries and JVM) required to run Java applications

JDK is the JRE with developer tools and documentations

OpenJDK is an open-source version of the JDK, unlike the common JDK owned by Oracle

What is the difference between getText() and getAttribute() in Selenium WebDriver?

getText(): Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

getAttribute(String attrName): Get the value of a the given attribute of the element. Will return the current value, even if this has been modified after the page has been loaded. More exactly, this method will return the value of the given attribute, unless that attribute is not present, in which case the value of the property with the same name is returned (for example for the "value" property of a textarea element). If neither value is set, null is returned. The "style" attribute is converted as best can be to a text representation with a trailing semi-colon. The following are deemed to be "boolean" attributes, and will return either "true" or null: async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, selected, spellcheck, truespeed, willvalidate Finally, the following commonly mis-capitalized attribute/property names are evaluated as expected: "class" "readonly"

getText() return the visible text of the element.

getAttribute(String attrName) returns the value of the attribute passed as parameter.

center a row using Bootstrap 3

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</div>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</div>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</div>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}