Programs & Examples On #Adam

Active Directory Application Mode (ADAM) is an LDAP-compliant directory service.

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

verbose: Integer. 0, 1, or 2. Verbosity mode.

Verbose=0 (silent)

Verbose=1 (progress bar)

Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: 
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: 
0.8071 - val_loss: 0.4617 - val_acc: 0.8168

Verbose=2 (one line per epoch)

Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046

Display/Print one column from a DataFrame of Series in Pandas

By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy

How to save final model using keras?

you can save the model and load in this way.

from keras.models import Sequential, load_model
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss':crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

It's really interesting case. Actually in your setup the following statement is true:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

This means that up to a constant multiplication factor your losses are equivalent. The weird behaviour that you are observing during a training phase might be an example of a following phenomenon:

  1. At the beginning the most frequent class is dominating the loss - so network is learning to predict mostly this class for every example.
  2. After it learnt the most frequent pattern it starts discriminating among less frequent classes. But when you are using adam - the learning rate has a much smaller value than it had at the beginning of training (it's because of the nature of this optimizer). It makes training slower and prevents your network from e.g. leaving a poor local minimum less possible.

That's why this constant factor might help in case of binary_crossentropy. After many epochs - the learning rate value is greater than in categorical_crossentropy case. I usually restart training (and learning phase) a few times when I notice such behaviour or/and adjusting a class weights using the following pattern:

class_weight = 1 / class_frequency

This makes loss from a less frequent classes balancing the influence of a dominant class loss at the beginning of a training and in a further part of an optimization process.

EDIT:

Actually - I checked that even though in case of maths:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

should hold - in case of keras it's not true, because keras is automatically normalizing all outputs to sum up to 1. This is the actual reason behind this weird behaviour as in case of multiclassification such normalization harms a training.

How to get element-wise matrix multiplication (Hadamard product) in numpy?

Try this:

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

#This would result a 'numpy.ndarray'
result = np.array(a) * np.array(b)

Here, np.array(a) returns a 2D array of type ndarray and multiplication of two ndarray would result element wise multiplication. So the result would be:

result = [[5, 12], [21, 32]]

If you wanna get a matrix, the do it with this:

result = np.mat(result)

Find the number of employees in each department - SQL Oracle

select count(e.empno), d.deptno, d.dname 
from emp e, dep d
where e.DEPTNO = d.DEPTNO 
group by d.deptno, d.dname;

Tensorflow: Using Adam optimizer

FailedPreconditionError: Attempting to use uninitialized value is one of the most frequent errors related to tensorflow. From official documentation, FailedPreconditionError

This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.

In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading

Basically to initialize the variable you have 3 options:

I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables and check is_variable_initialized.

LoDash: Get an array of values from an array of object properties

Since version v4.x you should use _.map:

_.map(users, 'id'); // [12, 14, 16, 18]

this way it is corresponds to native Array.prototype.map method where you would write (ES2015 syntax):

users.map(user => user.id); // [12, 14, 16, 18]

Before v4.x you could use _.pluck the same way:

_.pluck(users, 'id'); // [12, 14, 16, 18]

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

MySQL does not start when upgrading OSX to Yosemite or El Capitan

My Mac decided to restart itself randomly; causing a whole slew of errors. One of which, was mysql refusing to start up properly. I went through many SO questions/answers as well as other sites.

Ultimately what ended up resolving MY issue was this:

1) Creating the file (/usr/local/mysql/data/.local.pid

2) chmod 777 on that file

3) executing mysql.server start (mine was located in/usr/local/bin/mysql.server)

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

How to set the 'selected option' of a select dropdown list with jquery

Set the value it will set it as selected option for dropdown:

$("#salesrep").val("Bruce Jones");

Here is working Demo

If it still not working:

  1. Please check JavaScript errors on console.
  2. Make sure you included jquery files
  3. your network is not blocking jquery file if using externally.
  4. Check your view source some time exact copy of element stop jquery to work correctly

List all employee's names and their managers by manager name using an inner join

select a.empno,a.ename,a.job,a.mgr,B.empno,B.ename as MGR_name, B.job as MGR_JOB from 
    emp a, emp B where a.mgr=B.empno ;

Html Agility Pack get all elements by class

I used this extension method a lot in my project. Hope it will help one of you guys.

public static bool HasClass(this HtmlNode node, params string[] classValueArray)
    {
        var classValue = node.GetAttributeValue("class", "");
        var classValues = classValue.Split(' ');
        return classValueArray.All(c => classValues.Contains(c));
    }

String comparison in bash. [[: not found

I had this problem when installing Heroku Toolbelt

This is how I solved the problem

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 ago 15  2012 /bin/sh -> dash

As you can see, /bin/sh is a link to "dash" (not bash), and [[ is bash syntactic sugarness. So I just replaced the link to /bin/bash. Careful using rm like this in your system!

$ sudo rm /bin/sh
$ sudo ln -s /bin/bash /bin/sh

Writing to a file in a for loop

That is because you are opening , writing and closing the file 10 times inside your for loop

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

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

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

Remove duplicate values from JS array

Nested loop method for removing duplicates in array and preserving original order of elements.

var array = [1, 3, 2, 1, [5], 2, [4]]; // INPUT

var element = 0;
var decrement = array.length - 1;
while(element < array.length) {
  while(element < decrement) {
    if (array[element] === array[decrement]) {
      array.splice(decrement, 1);
      decrement--;
    } else {
      decrement--;
    }
  }
  decrement = array.length - 1;
  element++;
}

console.log(array);// [1, 3, 2, [5], [4]]

Explanation: Inner loop compares first element of array with all other elements starting with element at highest index. Decrementing towards the first element a duplicate is spliced from the array.

When inner loop is finished the outer loop increments to the next element for comparison and resets the new length of the array.

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

How to remove carriage returns and new lines in Postgresql?

select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )

I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.

Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:

select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

In the context definition, define only two DbSet contexts per context class.

How to get the employees with their managers

TRY THIS

SELECT E.ename,E.empno,ISNULL(E.ename,'NO MANAGER') AS MANAGER FROM emp e
INNER JOIN emp M
ON  M.empno=E.empno

Instaed of subquery use self join

How do I install imagemagick with homebrew?

Answering old thread here (and a bit off-topic) because it's what I found when I was searching how to install Image Magick on Mac OS to run on the local webserver. It's not enough to brew install Imagemagick. You have to also PECL install it so the PHP module is loaded.

From this SO answer:

brew install php
brew install imagemagick
brew install pkg-config
pecl install imagick

And you may need to sudo apachectl restart. Then check your phpinfo() within a simple php script running on your web server.

If it's still not there, you probably have an issue with running multiple versions of PHP on the same Mac (one through the command line, one through your web server). It's beyond the scope of this answer to resolve that issue, but there are some good options out there.

Create code first, many to many, with additional fields in association table

TLDR; (semi-related to an EF editor bug in EF6/VS2012U5) if you generate the model from DB and you cannot see the attributed m:m table: Delete the two related tables -> Save .edmx -> Generate/add from database -> Save.

For those who came here wondering how to get a many-to-many relationship with attribute columns to show in the EF .edmx file (as it would currently not show and be treated as a set of navigational properties), AND you generated these classes from your database table (or database-first in MS lingo, I believe.)

Delete the 2 tables in question (to take the OP example, Member and Comment) in your .edmx and add them again through 'Generate model from database'. (i.e. do not attempt to let Visual Studio update them - delete, save, add, save)

It will then create a 3rd table in line with what is suggested here.

This is relevant in cases where a pure many-to-many relationship is added at first, and the attributes are designed in the DB later.

This was not immediately clear from this thread/Googling. So just putting it out there as this is link #1 on Google looking for the issue but coming from the DB side first.

Pass in an array of Deferreds to $.when()

When calling multiple parallel AJAX calls, you have two options for handling the respective responses.

  1. Use Synchronous AJAX call/ one after another/ not recommended
  2. Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.

Example

_x000D_
_x000D_
function ajaxRequest(capitalCity) {_x000D_
   return $.ajax({_x000D_
        url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,_x000D_
        success: function(response) {_x000D_
        },_x000D_
        error: function(response) {_x000D_
          console.log("Error")_x000D_
        }_x000D_
    });_x000D_
}_x000D_
$(function(){_x000D_
   var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];_x000D_
   $('#capitals').text(capitalCities);_x000D_
_x000D_
   function getCountryCapitals(){ //do multiple parallel ajax requests_x000D_
      var promises = [];   _x000D_
      for(var i=0,l=capitalCities.length; i<l; i++){_x000D_
            var promise = ajaxRequest(capitalCities[i]);_x000D_
            promises.push(promise);_x000D_
      }_x000D_
  _x000D_
      $.when.apply($, promises)_x000D_
        .done(fillCountryCapitals);_x000D_
   }_x000D_
  _x000D_
   function fillCountryCapitals(){_x000D_
        var countries = [];_x000D_
        var responses = arguments;_x000D_
        for(i in responses){_x000D_
            console.dir(responses[i]);_x000D_
            countries.push(responses[i][0][0].nativeName)_x000D_
        }  _x000D_
        $('#countries').text(countries);_x000D_
   }_x000D_
  _x000D_
   getCountryCapitals()_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <h4>Capital Cities : </h4> <span id="capitals"></span>_x000D_
  <h4>Respective Country's Native Names : </h4> <span id="countries"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert php array to Javascript

Spudley's answer is fine.

Security Notice: The following should not be necessary any longer for you

If you don't have PHP 5.2 you can use something like this:

function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';

R: Select values from data table in range

One should also consider another intuitive way to do this using filter() from dplyr. Here are some examples:

set.seed(123)
df <- data.frame(name = sample(letters, 100, TRUE),
                 date = sample(1:500, 100, TRUE))
library(dplyr)
filter(df, date < 50) # date less than 50
filter(df, date %in% 50:100) # date between 50 and 100
filter(df, date %in% 1:50 & name == "r") # date between 1 and 50 AND name is "r"
filter(df, date %in% 1:50 | name == "r") # date between 1 and 50 OR name is "r"

# You can also use the pipe (%>%) operator
df %>% filter(date %in% 1:50 | name == "r")

Collection that allows only unique items in .NET?

You may look into something kind of Unique List as follows

public class UniqueList<T>
{
    public List<T> List
    {
        get;
        private set;
    }
    List<T> _internalList;

    public static UniqueList<T> NewList
    {
        get
        {
            return new UniqueList<T>();
        }
    }

    private UniqueList()
    {            
        _internalList = new List<T>();
        List = new List<T>();
    }

    public void Add(T value)
    {
        List.Clear();
        _internalList.Add(value);
        List.AddRange(_internalList.Distinct());
        //return List;
    }

    public void Add(params T[] values)
    {
        List.Clear();
        _internalList.AddRange(values);
        List.AddRange(_internalList.Distinct());
       // return List;
    }

    public bool Has(T value)
    {
        return List.Contains(value);
    }
}

and you can use it like follows

var uniquelist = UniqueList<string>.NewList;
uniquelist.Add("abc","def","ghi","jkl","mno");
uniquelist.Add("abc","jkl");
var _myList = uniquelist.List;

will only return "abc","def","ghi","jkl","mno" always even when duplicates are added to it

Creating a recursive method for Palindrome

public class palin
{ 
    static boolean isPalin(String s, int i, int j)
    {
        boolean b=true;
        if(s.charAt(i)==s.charAt(j))
        {
            if(i<=j)
                isPalin(s,(i+1),(j-1));
        }
        else
        {
            b=false;
        }
        return b;
    }
    public static void main()
    {
        String s1="madam";
        if(isPalin(s1, 0, s1.length()-1)==true)
            System.out.println(s1+" is palindrome");
        else
            System.out.println(s1+" is not palindrome");
    }
}

How do I copy a hash in Ruby?

Hash can create a new hash from an existing hash:

irb(main):009:0> h1 = {1 => 2}
=> {1=>2}
irb(main):010:0> h2 = Hash[h1]
=> {1=>2}
irb(main):011:0> h1.object_id
=> 2150233660
irb(main):012:0> h2.object_id
=> 2150205060

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

find all the name using mysql query which start with the letter 'a'

I would go for substr() functionality in MySql.

Basically, this function takes account of three parameters i.e. substr(str,pos,len)

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

SELECT * FROM artists 
WHERE lower(substr(name,1,1)) in ('a','b','c');

How to find list of possible words from a letter matrix [Boggle Solver]

Given a Boggle board with N rows and M columns, let's assume the following:

  • N*M is substantially greater than the number of possible words
  • N*M is substantially greater than the longest possible word

Under these assumptions, the complexity of this solution is O(N*M).

I think comparing running times for this one example board in many ways misses the point but, for the sake of completeness, this solution completes in <0.2s on my modern MacBook Pro.

This solution will find all possible paths for each word in the corpus.

#!/usr/bin/env ruby
# Example usage: ./boggle-solver --board "fxie amlo ewbx astu"

autoload :Matrix, 'matrix'
autoload :OptionParser, 'optparse'

DEFAULT_CORPUS_PATH = '/usr/share/dict/words'.freeze

# Functions

def filter_corpus(matrix, corpus, min_word_length)
  board_char_counts = Hash.new(0)
  matrix.each { |c| board_char_counts[c] += 1 }

  max_word_length = matrix.row_count * matrix.column_count
  boggleable_regex = /^[#{board_char_counts.keys.reduce(:+)}]{#{min_word_length},#{max_word_length}}$/
  corpus.select{ |w| w.match boggleable_regex }.select do |w|
    word_char_counts = Hash.new(0)
    w.each_char { |c| word_char_counts[c] += 1 }
    word_char_counts.all? { |c, count| board_char_counts[c] >= count }
  end
end

def neighbors(point, matrix)
  i, j = point
  ([i-1, 0].max .. [i+1, matrix.row_count-1].min).inject([]) do |r, new_i|
    ([j-1, 0].max .. [j+1, matrix.column_count-1].min).inject(r) do |r, new_j|
      neighbor = [new_i, new_j]
      neighbor.eql?(point) ? r : r << neighbor
    end
  end
end

def expand_path(path, word, matrix)
  return [path] if path.length == word.length

  next_char = word[path.length]
  viable_neighbors = neighbors(path[-1], matrix).select do |point|
    !path.include?(point) && matrix.element(*point).eql?(next_char)
  end

  viable_neighbors.inject([]) do |result, point|
    result + expand_path(path.dup << point, word, matrix)
  end
end

def find_paths(word, matrix)
  result = []
  matrix.each_with_index do |c, i, j|
    result += expand_path([[i, j]], word, matrix) if c.eql?(word[0])
  end
  result
end

def solve(matrix, corpus, min_word_length: 3)
  boggleable_corpus = filter_corpus(matrix, corpus, min_word_length)
  boggleable_corpus.inject({}) do |result, w|
    paths = find_paths(w, matrix)
    result[w] = paths unless paths.empty?
    result
  end
end

# Script

options = { corpus_path: DEFAULT_CORPUS_PATH }
option_parser = OptionParser.new do |opts|
  opts.banner = 'Usage: boggle-solver --board <value> [--corpus <value>]'

  opts.on('--board BOARD', String, 'The board (e.g. "fxi aml ewb ast")') do |b|
    options[:board] = b
  end

  opts.on('--corpus CORPUS_PATH', String, 'Corpus file path') do |c|
    options[:corpus_path] = c
  end

  opts.on_tail('-h', '--help', 'Shows usage') do
    STDOUT.puts opts
    exit
  end
end
option_parser.parse!

unless options[:board]
  STDERR.puts option_parser
  exit false
end

unless File.file? options[:corpus_path]
  STDERR.puts "No corpus exists - #{options[:corpus_path]}"
  exit false
end

rows = options[:board].downcase.scan(/\S+/).map{ |row| row.scan(/./) }

raw_corpus = File.readlines(options[:corpus_path])
corpus = raw_corpus.map{ |w| w.downcase.rstrip }.uniq.sort

solution = solve(Matrix.rows(rows), corpus)
solution.each_pair do |w, paths|
  STDOUT.puts w
  paths.each do |path|
    STDOUT.puts "\t" + path.map{ |point| point.inspect }.join(', ')
  end
end
STDOUT.puts "TOTAL: #{solution.count}"

Why is it not advisable to have the database and web server on the same machine?

On the other hand, referring to a different blogging Scott (Watermasyck, of Telligent) - they found that most users could speed up the websites (using Telligent's Community Server), by putting the database on the same machine as the web site. However, in their customer's case, usually the db & web server are the only applications on that machine, and the website isn't straining the machine that much. Then, the efficiency of not having to send data across the network more that made up for the increased strain.

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

H?llo from 2020. Let me bring String.prototype.matchAll() to your attention:

let regexp = /(?:&|&amp;)?([^=]+)=([^&]+)/g;
let str = '1111342=Adam%20Franco&348572=Bob%20Jones';

for (let match of str.matchAll(regexp)) {
    let [full, key, value] = match;
    console.log(key + ' => ' + value);
}

Outputs:

1111342 => Adam%20Franco
348572 => Bob%20Jones

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

Java - Abstract class to contain variables?

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

    private String source;

    public void setSource(String file) {
        source = file;
    }

    public String getSource() {
        return source;
    }
}

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

  • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
  • If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

Compare two MySQL databases

From the feature comparison list... MySQL Workbench offers Schema Diff and Schema Synchronization in their community edition.

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

Best way to encode text data for XML

In the past I have used HttpUtility.HtmlEncode to encode text for xml. It performs the same task, really. I havent ran into any issues with it yet, but that's not to say I won't in the future. As the name implies, it was made for HTML, not XML.

You've probably already read it, but here is an article on xml encoding and decoding.

EDIT: Of course, if you use an xmlwriter or one of the new XElement classes, this encoding is done for you. In fact, you could just take the text, place it in a new XElement instance, then return the string (.tostring) version of the element. I've heard that SecurityElement.Escape will perform the same task as your utility method as well, but havent read much about it or used it.

EDIT2: Disregard my comment about XElement, since you're still on 2.0

How do I get the current location of an iframe?

Does this help?

http://www.quirksmode.org/js/iframe.html

I only tested this in firefox, but if you have something like this:

<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>

You can get its address by using:

document.getElementById('myframe').src

Not sure if I understood your question correctly but anyways :)

What are some resources for getting started in operating system development?

I've toyed with Cosmos, which is "an operating system project implemented completely in CIL compliant languages." It's written in C#, so that was right up my alley. For someone like myself who has never attempted to build an operating system, it was actually pretty cool to be able to get a "Hello World" operating system running in no time.

Laravel Blade html image

In Laravel 5.x, you can also do like this .

<img class="img-responsive" src="{{URL::to('/')}}/img/stuvi-logo.png" alt=""/>

How to connect android emulator to the internet

Make sure Airplane mode is OFF. I kept trying to connect to the internet for a long time before realising what was wrong.

Convert string to a variable name

strsplit to parse your input and, as Greg mentioned, assign to assign the variables.

original_string <- c("x=123", "y=456")
pairs <- strsplit(original_string, "=")
lapply(pairs, function(x) assign(x[1], as.numeric(x[2]), envir = globalenv()))
ls()

Strange Jackson exception being thrown when serializing Hibernate object

I had the same problem. See if you are using hibernatesession.load(). If so, try converting to hibernatesession.get(). This solved my problem.

Python class inherits object

Yes, this is a 'new style' object. It was a feature introduced in python2.2.

New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), @property and descriptors. See this article for a good description of what a new style class is.

SO link for a description of the differences: What is the difference between old style and new style classes in Python?

add/remove active class for ul list with jquery?

you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Tower of Hanoi: Recursive Algorithm

As some of our friends suggested, I removed previous two answers and I consolidate here.

This gives you the clear understanding.

What the general algorithm is....

Algorithm:

solve(n,s,i,d) //solve n discs from s to d, s-source i-intermediate d-destination
{
    if(n==0)return;
    solve(n-1,s,d,i); // solve n-1 discs from s to i Note:recursive call, not just move
    move from s to d; // after moving n-1 discs from s to d, a left disc in s is moved to d
    solve(n-1,i,s,d); // we have left n-1 disc in 'i', so bringing it to from i to d (recursive call)
}

here is the working example Click here

"ImportError: no module named 'requests'" after installing with pip

I had this error before when I was executing a python3 script, after this:

sudo pip3 install requests

the problem solved, If you are using python3, give a shot.

Jackson - How to process (deserialize) nested JSON?

Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.

Given this JSON:

{
    "list": [
        {
            "wrapper": {
                "name": "Jack"
            }
        },
        {
            "wrapper": {
                "name": "Jane"
            }
        }
    ]
}

And these model objects:

public class RootObject {
    @JsonProperty("list")
    @JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
    @SkipWrapperObject("wrapper")
    public InnerObject[] innerObjects;
}

and

public class InnerObject {
    @JsonProperty("name")
    public String name;
}

Where the Jackson voodoo is implemented like:

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
    String value();
}

and

public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
        ContextualDeserializer {
    private Class<?> wrappedType;
    private String wrapperKey;

    public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
            BeanProperty property) throws JsonMappingException {
        SkipWrapperObject skipWrapperObject = property
                .getAnnotation(SkipWrapperObject.class);
        wrapperKey = skipWrapperObject.value();
        JavaType collectionType = property.getType();
        JavaType collectedType = collectionType.containedType(0);
        wrappedType = collectedType.getRawClass();
        return this;
    }

    @Override
    public Object deserialize(JsonParser parser, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = mapper.readTree(parser);
        JsonNode wrapped = objectNode.get(wrapperKey);
        Object mapped = mapIntoObject(wrapped);
        return mapped;
    }

    private Object mapIntoObject(JsonNode node) throws IOException,
            JsonProcessingException {
        JsonParser parser = node.traverse();
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(parser, wrappedType);
    }
}

Hope this is useful to someone!

How to use HTML to print header and footer on every printed page of a document?

Based on some post, i think position: fixed works for me.

_x000D_
_x000D_
body {_x000D_
  background: #eaeaed;_x000D_
  -webkit-print-color-adjust: exact;_x000D_
}_x000D_
_x000D_
.my-footer {_x000D_
  background: #2db34a;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}_x000D_
_x000D_
.my-header {_x000D_
  background: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset=utf-8 />_x000D_
  <title>Header & Footer</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <div class="my-header">Fixed Header</div>_x000D_
    <div class="my-footer">Fixed Footer</div>_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th>TH 1</th>_x000D_
          <th>TH 2</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Press Ctrl+P in chrome see the header & footer text on each page. Hope it helps

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

How to search JSON tree with jQuery

I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angular project. They have taken care of every possible cases.

/* Seach in Object */

var comparator = function(obj, text) {
if (obj && text && typeof obj === 'object' && typeof text === 'object') {
    for (var objKey in obj) {
        if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
                comparator(obj[objKey], text[objKey])) {
            return true;
        }
    }
    return false;
}
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};

var search = function(obj, text) {
if (typeof text == 'string' && text.charAt(0) === '!') {
    return !search(obj, text.substr(1));
}
switch (typeof obj) {
    case "boolean":
    case "number":
    case "string":
        return comparator(obj, text);
    case "object":
        switch (typeof text) {
            case "object":
                return comparator(obj, text);
            default:
                for (var objKey in obj) {
                    if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
                        return true;
                    }
                }
                break;
        }
        return false;
    case "array":
        for (var i = 0; i < obj.length; i++) {
            if (search(obj[i], text)) {
                return true;
            }
        }
        return false;
    default:
        return false;
}
};

Get a pixel from HTML Canvas?

Note that getImageData returns a snapshot. Implications are:

  • Changes will not take effect until subsequent putImageData
  • getImageData and putImageData calls are relatively slow

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

Since Java 11 has removed JavaEE you'll need to download some jars and add to the classpath:

JAXB: https://javaee.github.io/jaxb-v2/

JAF: https://www.oracle.com/technetwork/articles/java/index-135046.html

Then edit sdkmanager.bat so that set CLASSPATH=... ends with ;%CLASSPATH%

Set CLASSPATH to include JAXB and JAF:

set CLASSPATH=jaxb-core.jar;jaxb-impl.jar;jaxb-api.jar;activation.jar

Then sdkmanager.bat will work.

String representation of an Enum

Enum.GetName(typeof(MyEnum), (int)MyEnum.FORMS)
Enum.GetName(typeof(MyEnum), (int)MyEnum.WINDOWSAUTHENTICATION)
Enum.GetName(typeof(MyEnum), (int)MyEnum.SINGLESIGNON)

outputs are:

"FORMS"

"WINDOWSAUTHENTICATION"

"SINGLESIGNON"

Base64 Java encode and decode a string

The following is a good solution -

import android.util.Base64;

String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);

String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));

That's it. A single line encoding and decoding.

Zookeeper connection error

Check the zookeeper logs (/var/log/zookeeper). It looks like a connection is established, which should mean there is a record of it.

I had the same situation and it was because a process opened connections and failed to close them. This eventually exceeded the per-host connection limit and my logs were overflowing with

2016-08-03 15:21:13,201 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@188] - Too many connections from /172.31.38.64 - max is 50

Assuming zookeeper is on the usual port, you could do a check for that with:

lsof -i -P | grep 2181

Convert text into number in MySQL query

You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS INTEGER);

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

What does -z mean in Bash?

test -z returns true if the parameter is empty (see man sh or man test).

How to set the width of a RaisedButton in Flutter?

we use Row or Column, Expanded, Container and the element to use example RaisedButton

 body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.blue,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Copy'),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.green,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Paste'),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

HTTPS using Jersey Client

Construct your client as such

HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
ClientConfig config = new DefaultClientConfig();
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, myTrustManager, null);
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx));
Client client = Client.create(config);

Ripped from this blog post with more details: http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

For information on setting up your certs, see this nicely answered SO question: Using HTTPS with REST in Java

In PowerShell, how do I test whether or not a specific variable exists in global scope?

$myvar = if ($env:variable) { $env:variable } else { "default_value" } 

How to call codeigniter controller function from view

it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('script');
        $this->load->model('alert');

    }public function pledge_ph(){
        $this->script->phpledge();
    }
}
?>

This is the controller class Iris.php and the model class with the function pointed to from the controller class.

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
    public function __construct() {
        parent::__construct();
        // Your own constructor code
    }public function ghpledge(){
        $gh_id = uniqid(rand(1,11));
        $date=date("y-m-d");
        $gh_member = $_SESSION['member_id'];
        $amount= 10000;
        $data = array(
            'gh_id'=> $gh_id,
            'gh_member'=> $gh_member,
            'amount'=> $amount,
            'date'=> $date
        );
        $this->db->insert('iris_gh',$data);
    } 
}
?>

On the view instead of a button just use the anchor link with the controller name and method name.

<html>
    <head></head>
    <body>
        <a href="<?php echo base_url(); ?>index.php/iris/pledge_ph" class="btn btn-success">PLEDGE PH</a>
    </body>
</html>

Adding days to $Date in PHP

All you have to do is use days instead of day like this:

<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>

And it outputs correctly:

2010-09-18
2010-09-19

Find html label associated with a given input

I know this is old, but I had trouble with some solutions and pieced this together. I have tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and believe this is the simplest solution. It works with these three style of attaching a label.

<label><input type="checkbox" class="c123" id="cb1" name="item1">item1</label>

<input type="checkbox" class="c123" id="cb2" name="item2">item2</input>

<input type="checkbox" class="c123" id="cb3" name="item3"><label for="cb3">item3</label>

Using jQuery:

$(".c123").click(function() {
    $cb = $(this);
    $lb = $(this).parent();
    alert( $cb.attr('id') + ' = ' + $lb.text() );
});

My JSFiddle: http://jsfiddle.net/pnosko/6PQCw/

Changing ViewPager to enable infinite page scrolling

Its hacked by CustomPagerAdapter:

MainActivity.java:

import android.content.Context;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<String> numberList = new ArrayList<String>();
    private CustomPagerAdapter mCustomPagerAdapter;
    private ViewPager mViewPager;
    private Handler handler;
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        numberList.clear();
        for (int i = 0; i < 10; i++) {
        numberList.add(""+i);
        }

        mViewPager = (ViewPager)findViewById(R.id.pager);
        mCustomPagerAdapter = new CustomPagerAdapter(MainActivity.this);
        EndlessPagerAdapter mAdapater = new EndlessPagerAdapter(mCustomPagerAdapter);
        mViewPager.setAdapter(mAdapater);


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int modulo = position%numberList.size();
                Log.i("Current ViewPager View's Position", ""+modulo);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
                handler.postDelayed(runnable, 1000);
            }
        };

        handler.post(runnable);

    }

    @Override
    protected void onDestroy() {
        if(handler!=null){
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    private class CustomPagerAdapter extends PagerAdapter {

        Context mContext;
        LayoutInflater mLayoutInflater;

        public CustomPagerAdapter(Context context) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return numberList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((LinearLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View itemView = mLayoutInflater.inflate(R.layout.row_item_viewpager, container, false);

            TextView textView = (TextView) itemView.findViewById(R.id.txtItem);
            textView.setText(numberList.get(position));
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((LinearLayout) object);
        }
    }

    private class EndlessPagerAdapter extends PagerAdapter {

        private static final String TAG = "EndlessPagerAdapter";
        private static final boolean DEBUG = false;

        private final PagerAdapter mPagerAdapter;

        EndlessPagerAdapter(PagerAdapter pagerAdapter) {
            if (pagerAdapter == null) {
                throw new IllegalArgumentException("Did you forget initialize PagerAdapter?");
            }
            if ((pagerAdapter instanceof FragmentPagerAdapter || pagerAdapter instanceof FragmentStatePagerAdapter) && pagerAdapter.getCount() < 3) {
                throw new IllegalArgumentException("When you use FragmentPagerAdapter or FragmentStatePagerAdapter, it only supports >= 3 pages.");
            }
            mPagerAdapter = pagerAdapter;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (DEBUG) Log.d(TAG, "Destroy: " + getVirtualPosition(position));
            mPagerAdapter.destroyItem(container, getVirtualPosition(position), object);

            if (mPagerAdapter.getCount() < 4) {
                mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
            }
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            mPagerAdapter.finishUpdate(container);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE; // this is the magic that we can scroll infinitely.
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mPagerAdapter.getPageTitle(getVirtualPosition(position));
        }

        @Override
        public float getPageWidth(int position) {
            return mPagerAdapter.getPageWidth(getVirtualPosition(position));
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return mPagerAdapter.isViewFromObject(view, o);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (DEBUG) Log.d(TAG, "Instantiate: " + getVirtualPosition(position));
            return mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
        }

        @Override
        public Parcelable saveState() {
            return mPagerAdapter.saveState();
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
            mPagerAdapter.restoreState(state, loader);
        }

        @Override
        public void startUpdate(ViewGroup container) {
            mPagerAdapter.startUpdate(container);
        }

        int getVirtualPosition(int realPosition) {
            return realPosition % mPagerAdapter.getCount();
        }

        PagerAdapter getPagerAdapter() {
            return mPagerAdapter;
        }

    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="180dp">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

row_item_viewpager.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtItem"
        android:textAppearance="@android:style/TextAppearance.Large"/>

</LinearLayout>

Done

Why javascript getTime() is not a function?

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);

Create a List of primitive int?

Is there a way to convert an Integer[] array to an int[] array?

This gross omission from the Java core libraries seems to come up on pretty much every project I ever work on. And as convenient as the Trove library might be, I am unable to parse the precise requirements to meet LPGL for an Android app that statically links an LGPL library (preamble says ok, body does not seem to say the same). And it's just plain inconvenient to go rip-and-stripping Apache sources to get these classes. There has to be a better way.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

Reading file using relative path in python project

For Python 3.4+:

import csv
from pathlib import Path

base_path = Path(__file__).parent
file_path = (base_path / "../data/test.csv").resolve()

with open(file_path) as f:
    test = [line for line in csv.reader(f)]

The type or namespace name 'DbContext' could not be found

Visual Studio Express SP1 Right click in Solution Explorer > References > Add Library Package Reference > EntityFramework

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

How to plot two histograms together in R?

Plotly's R API might be useful for you. The graph below is here.

library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
         name = "Carrots",
         type='histogramx',
         opacity = 0.8)

data1 = list(x=x1,
         name = "Cukes",
         type='histogramx',
         opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
               plot_bgcolor = 'rgba(249,249,251,.85)')  
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))

url = response$url
filename = response$filename

browseURL(response$url)

Full disclosure: I'm on the team.

Graph

IntelliJ shortcut to show a popup of methods in a class that can be searched

On linux distributions (@least on Debian with plasma) the default shortcut is

Ctrl + 0

How to find top three highest salary in emp table in oracle?

solution for to find top 5 salary in sq l server

select top(1) name, salary from salary where salary in(select distinct top(3) salary from salary order by salary disc)

Why is the Android emulator so slow? How can we speed up the Android emulator?

The current (May 2011) version of the emulator is slow particularly with Android 3.0 (Honeycomb) primarily because the emulator does not support hardware GL -- this means that the GL code gets translated into software (ARM software, in fact) which then gets emulated in software in QEMU. This is crazy-slow. They're working on this problem and have it partially solved, but not with any sort of release quality.

Check out the video Google I/O 2011: Android Development Tools to see it in action -- jump to about 44 minutes.

How to connect from windows command prompt to mysql command line

Go to your MySQL directory. As in my case its...

cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -uroot -p

root can be changed to your user whatever MySQL user you've set.

It will ask for your password. If you have a password, Type your password and press "Enter", If no password set just press Enter without typing. You will be connected to MySQL.

There is another way to directly connect to MySQL without every time, going to the directory and typing down the commands.

Create a .bat file. First, add your path to MySQL. In my case it was,

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

Then add these two lines

net start MySQL 
mysql -u root -p

If you don't want to type password every time you can simply add password with -p e.g. -proot (in case root was the password) but that is not recommended.

Also, If you want to connect to other host than local (staging/production server). You can also add -h22.345.80.09 E.g. 22.345.80.09 is your server ip.

net start MySQL 
mysql -u root -p -h22.345.80.0

Save the file. Just double click to open and connect directly to MySQL.

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

Assembly Language - How to do Modulo?

If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b is a power of two, a % b == a & (b - 1).

For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63, because 63 is 111111 in binary.

The masked, higher digits are not of interest to us. Try it out!

Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!

How to draw rounded rectangle in Android UI?

I think, this is you exactly needed.

Here drawable(xml) file that creates rounded rectangle. round_rect_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ffffff" />

    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />

</shape>

Here layout file: my_layout.xml

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/round_rect_shape"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Something text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff0000" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>
</LinearLayout>

-> In the above code, LinearLayout having the background(That is the key role to place to create rounded rectangle). So you can place any view like TextView, EditText... in that LinearLayout to see background as round rectangle for all.

Convert DateTime to String PHP

The simplest way I found is:

$date   = new DateTime(); //this returns the current date time
$result = $date->format('Y-m-d-H-i-s');
echo $result . "<br>";
$krr    = explode('-', $result);
$result = implode("", $krr);
echo $result;

I hope it helps.

Add 10 seconds to a Date

There's a setSeconds method as well:

var t = new Date();
t.setSeconds(t.getSeconds() + 10);

For a list of the other Date functions, you should check out MDN


setSeconds will correctly handle wrap-around cases:

_x000D_
_x000D_
var d;_x000D_
d = new Date('2014-01-01 10:11:55');_x000D_
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55_x000D_
d.setSeconds(d.getSeconds() + 10);_x000D_
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
_x000D_
_x000D_
_x000D_

Difference between decimal, float and double in .NET?

For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!

How to print formatted BigDecimal values?

public static String currencyFormat(BigDecimal n) {
    return NumberFormat.getCurrencyInstance().format(n);
}

It will use your JVM’s current default Locale to choose your currency symbol. Or you can specify a Locale.

NumberFormat.getInstance(Locale.US)

For more info, see NumberFormat class.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used this tutorial to create my maven web project http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and eclipse did not create src/main/java folder for me. When i tired to create the source folder src/main/java eclipse did not let me. So i created the folder outside eclipse in the project directly and then src/main/java appeared in eclipse.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

java: use StringBuilder to insert at the beginning

As an alternative solution you can use a LIFO structure (like a stack) to store all the strings and when you are done just take them all out and put them into the StringBuilder. It naturally reverses the order of the items (strings) placed in it.

Stack<String> textStack = new Stack<String>();
// push the strings to the stack
while(!isReadingTextDone()) {
    String text = readText();
    textStack.push(text);
}
// pop the strings and add to the text builder
String builder = new StringBuilder(); 
while (!textStack.empty()) {
      builder.append(textStack.pop());
}
// get the final string
String finalText =  builder.toString();

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

Android: Scale a Drawable or background image?

To customize background image scaling create a resource like this:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:src="@drawable/list_bkgnd" />

Then it will be centered in the view if used as background. There are also other flags: http://developer.android.com/guide/topics/resources/drawable-resource.html

How to get a list of sub-folders and their files, ordered by folder-names

In command prompt go to the main directory you want the list for ... and type the command tree /f

What's a simple way to get a text input popup dialog box on an iPhone

In Xamarin and C#:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();

possible EventEmitter memory leak detected

Thanks to RLaaa for giving me an idea how to solve the real problem/root cause of the warning. Well in my case it was MySQL buggy code.

Providing you wrote a Promise with code inside like this:

pool.getConnection((err, conn) => {

  if(err) reject(err)

  const q = 'SELECT * from `a_table`'

  conn.query(q, [], (err, rows) => {

    conn.release()

    if(err) reject(err)

    // do something
  })

  conn.on('error', (err) => {

     reject(err)
  })
})

Notice there is a conn.on('error') listener in the code. That code literally adding listener over and over again depends on how many times you call the query. Meanwhile if(err) reject(err) does the same thing.

So I removed the conn.on('error') listener and voila... solved! Hope this helps you.

clear javascript console in Google Chrome

If you use console.clear(), that seems to work in chrome. Note, it will output a "Console was cleared" message.

I tested this by racking up a ton of Javascript errors.

Note, I got an error right after clearing the console, so it doesn't disable the console, only clears it. Also, I have only tried this in chrome, so I dont know how cross-browser it is.

EDIT: I tested this in Chrome, IE, Firefox, and Opera. It works in Chrome, MSIE and Opera's default consoles, but not in Firefox's, however, it does work in Firebug.

Update a submodule to the latest commit

My project should use the 'latest' for the submodule. On Mac OSX 10.11, git version 2.7.1, I did not need to go 'into' my submodule folder in order to collect its commits. I merely did a regular

git pull --rebase 

at the top level, and it correctly updated my submodule.

How to run Spyder in virtual environment?

The above answers are correct but I calling spyder within my virtualenv would still use my PATH to look up the version of spyder in my default anaconda env. I found this answer which gave the following workaround:

source activate my_env            # activate your target env with spyder installed
conda info -e                     # look up the directory of your conda env
find /path/to/my/env -name spyder # search for the spyder executable in your env
/path/to/my/env/then/to/spyder    # run that executable directly

I chose this over modifying PATH or adding a link to the executable at a higher priority in PATH since I felt this was less likely to break other programs. However, I did add an alias to the executable in ~/.bash_aliases.

Python: pandas merge multiple dataframes

Look at this pandas three-way joining multiple dataframes on columns

filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])

how to use free cloud database with android app?

Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.

Here are some providers which have a "free-tier" (may change in future):

  1. Firebase (Google) - https://firebase.google.com/
  2. AWS Mobile (Amazon) - https://aws.amazon.com/mobile/
  3. Azure Mobile (Microsoft) - https://azure.microsoft.com/en-in/services/app-service/mobile/
  4. MongoDB Realm (MongoDB) - https://www.mongodb.com/realm
  5. Back4app (Popular) - https://www.back4app.com/

Open source solutions:

  1. Parse - http://parseplatform.org/
  2. Apache User Grid - https://usergrid.apache.org/
  3. SupaBase (under development) - https://supabase.io/

Header set Access-Control-Allow-Origin in .htaccess doesn't work

After spending half a day with nothing working. Using a header check service though everything was working. The firewall at work was stripping them

Importing a GitHub project into Eclipse

Using the command line is an option, and would remove the need for an Eclipse Plugin. First, create a directory to hold the project.

mkdir myGitRepo
cd myGitRepo

Clone the desired repository in the directory you just created.

git clone https://github.com/JonasHelming/gitTutorial.git

Then open Eclipse and select the directory you created (myGitRepo) as the Eclipse Workspace.

Don't worry that the Project Explorer is empty, Eclipse can't recognize the source files yet.

Lastly, create a new Java project with the exact same name as the project you pulled. In this case, it was 'gitTutorial'.

File -> New -> Java Project

At this point, the project's sub directories should contain the files pulled from Github. Take a look at the following post in my blog for a more detailed explanation.

http://brianredd.com/application/pull-java-project-from-github

vuejs update parent data from child component

In child component:

this.$emit('eventname', this.variable)

In parent component:

<component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

Leaving another way here

git branch newbranch
git checkout master 
git merge newbranch 

How To Accept a File POST

The ASP.NET Core way is now here:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

jQuery - Getting form values for ajax POST

you can use val function to collect data from inputs:

jQuery("#myInput1").val();

http://api.jquery.com/val/

Complexities of binary tree traversals

O(n), because you traverse each node once. Or rather - the amount of work you do for each node is constant (does not depend on the rest of the nodes).

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

Injecting Mockito mocks into a Spring bean

Looking at Springockito pace of development and number of open issues, I would be little bit worried to introduce it into my test suite stack nowadays. Fact that last release was done before Spring 4 release brings up questions like "Is it possible to easily integrate it with Spring 4?". I don't know, because I didn't try it. I prefer pure Spring approach if I need to mock Spring bean in integration test.

There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profile and @ActiveProfiles annotations for it. I wrote a blog post on the topic.

CSS two div width 50% in one line with line break in file

Sorry but all the answers I see here are either hacky or fail if you sneeze a little harder.

If you use a table you can (if you wish) add a space between the divs, set borders, padding...

<table width="100%" cellspacing="0">
    <tr>
        <td style="width:50%;">A</td>
        <td style="width:50%;">B</td>            
    </tr>
</table>

Check a more complete example here: http://jsfiddle.net/qPduw/5/

How to view/delete local storage in Firefox?

As 'localStorage' is just another object, you can: create, view, and edit it in the 'Console'. Simply enter 'localStorage' as a command and press enter, it'll display a string containing the key-value pairs of localStorage (Tip: Click on that string for formatted output, i.e. to display each key-value pair in each line).

MySQL Database won't start in XAMPP Manager-osx

After trying all possible options, the below trick worked for me:

  1. Navigate to /Applications/XAMPP/xamppfiles/etc/ and open the files my.conf
  2. Search for

    "# The MySQL server"

    [mysqld]

    user = mysql

    port=3308

and change the port number.

  1. Start the mysql database again.

launch sms application with an intent

Intent sendIntent = new Intent(Intent.ACTION_SEND); 
//CHANGE YOUR MESSAGING ACTIVITY HERE IF REQUIRED 
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body",msgbody); 
sendIntent.putExtra("address",phonenumber);
//FOR MMS
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/mms.png"));
sendIntent.setType("image/png");
startActivity(sendIntent);

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I faced this problem

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

Some help about this:

First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.

Follow these steps.

  1. Open your wamp\bin\mysql directory
  2. Check if in this folder there is another folder of mysql with different name, if exists delete it.
  3. enter to remain mysql folder and delete files with duplication.
  4. start your wamp server again. Wamp will be working.

How do I get a list of files in a directory in C++?

Here's what I use:

/* Returns a list of files in a directory (except the ones that begin with a dot) */

void GetFilesInDirectory(std::vector<string> &out, const string &directory)
{
#ifdef WINDOWS
    HANDLE dir;
    WIN32_FIND_DATA file_data;

    if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
        return; /* No files found */

    do {
        const string file_name = file_data.cFileName;
        const string full_file_name = directory + "/" + file_name;
        const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

        if (file_name[0] == '.')
            continue;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    } while (FindNextFile(dir, &file_data));

    FindClose(dir);
#else
    DIR *dir;
    class dirent *ent;
    class stat st;

    dir = opendir(directory);
    while ((ent = readdir(dir)) != NULL) {
        const string file_name = ent->d_name;
        const string full_file_name = directory + "/" + file_name;

        if (file_name[0] == '.')
            continue;

        if (stat(full_file_name.c_str(), &st) == -1)
            continue;

        const bool is_directory = (st.st_mode & S_IFDIR) != 0;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    }
    closedir(dir);
#endif
} // GetFilesInDirectory

What is the difference between synchronous and asynchronous programming (in node.js)

Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.

Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).

Orginal Posted on Github: Link

Recommended way to insert elements into map

map[key] = value is provided for easier syntax. It is easier to read and write.

The reason for which you need to have default constructor is that map[key] is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[].

unexpected T_VARIABLE, expecting T_FUNCTION

check that you entered a variable as argument with the '$' symbol

android get all contacts

public class MyActivity extends Activity 
                        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int CONTACTS_LOADER_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(CONTACTS_LOADER_ID,
                                      null,
                                      this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.

        if (id == CONTACTS_LOADER_ID) {
            return contactsLoader();
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //The framework will take care of closing the
        // old cursor once we return.
        List<String> contacts = contactsFromCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
    }

    private  Loader<Cursor> contactsLoader() {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts

        String[] projection = {                                  // The columns to return for each row
                ContactsContract.Contacts.DISPLAY_NAME
        } ;

        String selection = null;                                 //Selection criteria
        String[] selectionArgs = {};                             //Selection criteria
        String sortOrder = null;                                 //The sort order for the returned rows

        return new CursorLoader(
                getApplicationContext(),
                contactsUri,
                projection,
                selection,
                selectionArgs,
                sortOrder);
    }

    private List<String> contactsFromCursor(Cursor cursor) {
        List<String> contacts = new ArrayList<String>();

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contacts.add(name);
            } while (cursor.moveToNext());
        }

        return contacts;
    }

}

and do not forget

<uses-permission android:name="android.permission.READ_CONTACTS" />

How do I run a Java program from the command line on Windows?

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they're in the same directory

If you're having an issue resulting with "could not find or load main class" you may not have jre in your path. Have a look at this question: Could not find or load main class

Download an SVN repository?

Install svn, navigate to your directory then run the command svn checkout <url-to-repostitory> ..

Please provide us with some details like your operating system and what/where you want to download.

How can I uninstall npm modules in Node.js?

In npm v6+ npm uninstall <package_name> removes it both in folder node_modules and file package.json.

hash function for string

There are a number of existing hashtable implementations for C, from the C standard library hcreate/hdestroy/hsearch, to those in the APR and glib, which also provide prebuilt hash functions. I'd highly recommend using those rather than inventing your own hashtable or hash function; they've been optimized heavily for common use-cases.

If your dataset is static, however, your best solution is probably to use a perfect hash. gperf will generate a perfect hash for you for a given dataset.

Hive: Convert String to Integer

It would return NULL but if taken as BIGINT would show the number

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

C++ Boost: undefined reference to boost::system::generic_category()

You should link in the libboost_system library. I am not sure about codeblocks, but the g++ command-line option on your platform would be

-lboost_system

Understanding __getitem__ method

__getitem__ can be used to implement "lazy" dict subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.

As a simple example, suppose you have two lists, keys and values, whereby {k:v for k,v in zip(keys, values)} is the dictionary that you need, which must be made lazy for speed or efficiency purposes:

class LazyDict(dict):
    
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values
        super().__init__()
        
    def __getitem__(self, key):
        if key not in self:
            try:
                i = self.keys.index(key)
                self.__setitem__(self.keys.pop(i), self.values.pop(i))
            except ValueError, IndexError:
                raise KeyError("No such key-value pair!!")
        return super().__getitem__(key)

Usage:

>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])

How to execute a file within the python interpreter?

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

Regular expression for checking if capital letters are found consecutively in a string?

Whenever one writes [A-Z] or [a-z], one explicitly commits to processing nothing but 7-bit ASCII data from the 1960s. If that’s really ok, then fine. But if it’s not ok, then Unicode character properties exist to help you with handling modern character data.

There are three cases in Unicode, not two. Furthermore, you also have noncased letters. Letters in general are specified by the \pL property, and each of these also belongs to exactly one of five subcategories:

  1. uppercase letters, specified with \p{Lu}; eg: AÇ?ÞSSS??ST
  2. titlecase letters, specified with \p{Lt}; eg: ??Ss?St (actually Ss and St are an upper- and then a lowercase letter, but they are what you get if you ask for the titlecase of ß and ?, respectively)
  3. lowercase letters, specified with \p{Ll}; eg: aaç??sþß??
  4. modifier letters, specified with \p{Lm}; eg: ????"'???
  5. other letters, specified with \p{Lo}; eg: ?????

You can take the complement of any of these, but do be careful, because something like \P{Lu} does not mean a letter that isn’t uppercase! It means any character that isn’t an uppercase letter.

For a letter that’s either of uppercase or titlecase, use [\p{Lu}\p{Lt}]. So you could use for your pattern:

 ^([\p{Lu}\p{Lt}]\p{Ll}+)+$

If you don’t mean to limit the letters following the first to the “casing” letters alone, then you might prefer:

 ^([\p{Lu}\p{Lt}][\p{Ll}\p{Lm}\p{Lo}]+)+$

If you’re trying to match so-called “CamelCase” identifiers, then the actual rules depend on the programming language, but usually include the underscore character and the decimal numbers (\p{Nd}), and may also include a literal dollar sign and other language-dependent characters. If so, you may wish to add some of these to one or the other of the two character classes provided above.

For example, you may wish to add underscore to both but digits only to the second, leaving you with:

 ^([_\p{Lu}\p{Lt}][_\p{Nd}\p{Ll}\p{Lm}\p{Lo}]+)+$

If, though, you are dealing with certain “words” from various RFCs and ISO standards, these are often specified as containing ASCII only. If so, you can get by with the literal [A-Z] idea. It’s just not kind to impose that restriction if it doesn’t actually exist.

How to ping multiple servers and return IP address and Hostnames using batch script?

I worked on the code given earlier by Eitan-T and reworked to output to CSV file. Found the results in earlier code weren't always giving correct values as well so i've improved it.

testservers.txt

SOMESERVER
DUDSERVER

results.csv

HOSTNAME    LONGNAME                    IPADDRESS   STATE 
SOMESERVER  SOMESERVER.DOMAIN.SUF       10.1.1.1    UP 
DUDSERVER   UNRESOLVED                  UNRESOLVED  DOWN 

pingtest.bat

 @echo off
    setlocal enabledelayedexpansion
    set OUTPUT_FILE=result.csv

    >nul copy nul %OUTPUT_FILE%
    echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
    for /f %%i in (testservers.txt) do (
        set SERVER_ADDRESS_I=UNRESOLVED
        set SERVER_ADDRESS_L=UNRESOLVED
        for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS_L=%%y
        if %%x==Pinging set SERVER_ADDRESS_I=%%z
            if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
        )
        echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
        echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
    )

The entity cannot be constructed in a LINQ to Entities query

You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO:

public class ProductDTO
{
    public string Name { get; set; }
    // Other field you may need from the Product entity
}

And your method will return a List of DTO's.

public List<ProductDTO> GetProducts(int categoryID)
{
    return (from p in db.Products
            where p.CategoryID == categoryID
            select new ProductDTO { Name = p.Name }).ToList();
}

assign function return value to some variable using javascript

The result is undefined since $.ajax runs an asynchronous operation. Meaning that return status gets executed before the $.ajax operation finishes with the request.

You may use Promise to have a syntax which feels synchronous.

function doSomething() { 
    return new Promise((resolve, reject) => {
        $.ajax({
            url:'action.php',
            type: "POST",
            data: dataString,
            success: function (txtBack) { 
                if(txtBack==1) {
                    resolve(1);
                } else {
                    resolve(0);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                reject(textStatus);
            }
        });
    });
}

You can call the promise like this

doSomething.then(function (result) {
    console.log(result);
}).catch(function (error) {
    console.error(error);
});

or this

(async () => {
    try {
        let result = await doSomething();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();

HTML input field hint

the best way to give a hint is placeholder like this:

<input.... placeholder="hint".../>

How to install Selenium WebDriver on Mac OS

Mac already has Python and a package manager called easy_install, so open Terminal and type

sudo easy_install selenium

UICollectionView auto scroll to cell at IndexPath

New, Edited Answer:

Add this in viewDidLayoutSubviews

SWIFT

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let indexPath = IndexPath(item: 12, section: 0)
    self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: true)
}

Normally, .centerVertically is the case

ObjC

-(void)viewDidLayoutSubviews {
   [super viewDidLayoutSubviews];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:12 inSection:0];
   [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically | UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

Old answer working for older iOS

Add this in viewWillAppear:

[self.view layoutIfNeeded];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];

MySQL - ERROR 1045 - Access denied

I had the same error, but it was because password_expired was set to Y. You can fix that issue by following the same approach as the currently accepted answer, but instead executing the MySQL query:

UPDATE mysql.user SET password_expired = 'N' WHERE User='root';

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

How do I choose grid and block dimensions for CUDA kernels?

The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see

CUDA Pro Tip: Occupancy API Simplifies Launch Configuration

One of the useful functions is cudaOccupancyMaxPotentialBlockSize which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.

#include <stdio.h>

/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N) 
{ 
    int idx = threadIdx.x + blockIdx.x * blockDim.x; 

    if (idx < N) { c[idx] = a[idx] + b[idx]; } 
} 

/********/
/* MAIN */
/********/
void main() 
{ 
    const int N = 1000000;

    int blockSize;      // The launch configurator returned block size 
    int minGridSize;    // The minimum grid size needed to achieve the maximum occupancy for a full device launch 
    int gridSize;       // The actual grid size needed, based on input size 

    int* h_vec1 = (int*) malloc(N*sizeof(int));
    int* h_vec2 = (int*) malloc(N*sizeof(int));
    int* h_vec3 = (int*) malloc(N*sizeof(int));
    int* h_vec4 = (int*) malloc(N*sizeof(int));

    int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
    int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
    int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));

    for (int i=0; i<N; i++) {
        h_vec1[i] = 10;
        h_vec2[i] = 20;
        h_vec4[i] = h_vec1[i] + h_vec2[i];
    }

    cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);

    float time;
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);

    cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N); 

    // Round up according to array size 
    gridSize = (N + blockSize - 1) / blockSize; 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Occupancy calculator elapsed time:  %3.3f ms \n", time);

    cudaEventRecord(start, 0);

    MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N); 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Kernel elapsed time:  %3.3f ms \n", time);

    printf("Blocksize %i\n", blockSize);

    cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i=0; i<N; i++) {
        if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
    }

    printf("Test passed\n");

}

EDIT

The cudaOccupancyMaxPotentialBlockSize is defined in the cuda_runtime.h file and is defined as follows:

template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
    int    *minGridSize,
    int    *blockSize,
    T       func,
    size_t  dynamicSMemSize = 0,
    int     blockSizeLimit = 0)
{
    return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}

The meanings for the parameters is the following

minGridSize     = Suggested min grid size to achieve a full machine launch.
blockSize       = Suggested block size to achieve maximum occupancy.
func            = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit  = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.

Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.

Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize in driver API code in the same way shown for the runtime API in the example above.

How Do I Take a Screen Shot of a UIView?

I created this extension for save a screen shot from UIView

extension UIView {
func saveImageFromView(path path:String) {
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
    drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)

}}

call:

let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
reportView.saveImageFromView(path: pathImage)

If you want to create a png must change:

UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)

by

UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)

convert string array to string

string[] test = new string[2];

test[0] = "Hello ";
test[1] = "World!";

string.Join("", test);

AutoComplete TextBox Control

You could attach to the KeyDown event and then query the database for that portion of the text that the user has already entered. For example, if the user enters "T", search for things that start with "T". Then, when they enter the next letter, for example "e", search for things in the table that start with "Te".

The available items could be displayed in a "floating" ListBox, for example. You would need to place the ListBox just beneath the TextBox so that they can see the entries available, then remove the ListBox when they're done typing.

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

Constructors in Go

I am new to go. I have another pattern taken from other languages, that have constructors. And will work in go.

  1. Create an init method.
  2. Make the init method an (object) once routine. It only runs the first time it is called (per object).
func (d *my_struct) Init (){
    //once
    if !d.is_inited {
        d.is_inited = true
        d.value1 = 7
        d.value2 = 6
    }
}
  1. Call init at the top of every method of this class.

This pattern is also useful, when you need late initialisation (constructor is too early).

Advantages: it hides all the complexity in the class, clients don't need to do anything.

Disadvantages: you must remember to call Init at the top of every method of the class.

Ways to save enums in database

We just store the enum name itself - it's more readable.

We did mess around with storing specific values for enums where there are a limited set of values, e.g., this enum that has a limited set of statuses that we use a char to represent (more meaningful than a numeric value):

public enum EmailStatus {
    EMAIL_NEW('N'), EMAIL_SENT('S'), EMAIL_FAILED('F'), EMAIL_SKIPPED('K'), UNDEFINED('-');

    private char dbChar = '-';

    EmailStatus(char statusChar) {
        this.dbChar = statusChar;
    }

    public char statusChar() {
        return dbChar;
    }

    public static EmailStatus getFromStatusChar(char statusChar) {
        switch (statusChar) {
        case 'N':
            return EMAIL_NEW;
        case 'S':
            return EMAIL_SENT;
        case 'F':
            return EMAIL_FAILED;
        case 'K':
            return EMAIL_SKIPPED;
        default:
            return UNDEFINED;
        }
    }
}

and when you have a lot of values you need to have a Map inside your enum to keep that getFromXYZ method small.

How to leave a message for a github.com user

Here is another way:

  • Browse someone's commit history (Click commits which is next to branch to see the whole commit history)

  • Click the commit that with the person's username because there might be so many of them

  • Then you should see the web address has a hash concatenated to the URL. Add .patch to this commit URL

  • You will probably see the person's email address there

Example: https://github.com/[username]/[reponame]/commit/[hash].patch

Source: Chris Herron @ Sourcecon

PHP: How to check if a date is today, yesterday or tomorrow

function getRangeDateString($timestamp) {
    if ($timestamp) {
        $currentTime=strtotime('today');
        // Reset time to 00:00:00
        $timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
        $days=round(($timestamp-$currentTime)/86400);
        switch($days) {
            case '0';
                return 'Today';
                break;
            case '-1';
                return 'Yesterday';
                break;
            case '-2';
                return 'Day before yesterday';
                break;
            case '1';
                return 'Tomorrow';
                break;
            case '2';
                return 'Day after tomorrow';
                break;
            default:
                if ($days > 0) {
                    return 'In '.$days.' days';
                } else {
                    return ($days*-1).' days ago';
                }
                break;
        }
    }
}

Radio button checked event handling

$("#expires1").click(function(){
     if (this.checked)
        alert("testing....");
});

Proper way to restrict text input values (e.g. only numbers)

To catch all the event surrounding model changes, can consider using

<input (ngModelChange)="inputFilter($event)"/>

It will detect copy / paste, keyup, any condition that changes the value of the model.

And then:

inputFilter(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

Get pixel's RGB using PIL

Not PIL, but imageio.imread might still be interesting:

import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So the pixel at position (x, y) is

color = tuple(im[y][x])
r, g, b = color

Outdated

scipy.misc.imread is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)

How to print from Flask @app.route to python console

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask


dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = Flask(__name__)

@app.route('/')
def index():
    return "Hello from Flask's test environment"

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

How to control the width and height of the default Alert Dialog in Android?

I dont know whether you can change the default height/width of AlertDialog but if you wanted to do this, I think you can do it by creating your own custom dialog. You just have to give android:theme="@android:style/Theme.Dialog" in the android manifest.xml for your activity and can write the whole layout as per your requirement. you can set the height and width of your custom dialog from the Android Resource XML.

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

Regular Expression to select everything before and up to a particular text

This matches everything up to ".txt" (without including it):

^.*(?=(\.txt))

Is there a limit on an Excel worksheet's name length?

Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.

Cloud Firestore collection count

Solution using pagination with offset & limit:

public int collectionCount(String collection) {
        Integer page = 0;
        List<QueryDocumentSnapshot> snaps = new ArrayList<>();
        findDocsByPage(collection, page, snaps);
        return snaps.size();
    }

public void findDocsByPage(String collection, Integer page, 
                           List<QueryDocumentSnapshot> snaps) {
    try {
        Integer limit = 26000;
        FieldPath[] selectedFields = new FieldPath[] { FieldPath.of("id") };
        List<QueryDocumentSnapshot> snapshotPage;
        snapshotPage = fireStore()
                        .collection(collection)
                        .select(selectedFields)
                        .offset(page * limit)
                        .limit(limit)
                        .get().get().getDocuments();    
        if (snapshotPage.size() > 0) {
            snaps.addAll(snapshotPage);
            page++;
            findDocsByPage(collection, page, snaps);
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
  • findDocsPage it's a recursive method to find all pages of collection

  • selectedFields for otimize query and get only id field instead full body of document

  • limit max size of each query page

  • page define inicial page for pagination

From the tests I did it worked well for collections with up to approximately 120k records!

How do I change the data type for a column in MySQL?

alter table table_name modify column_name int(5)

PHP check file extension

$file_parts = pathinfo($filename);

$file_parts['extension'];
$cool_extensions = Array('jpg','png');

if (in_array($file_parts['extension'], $cool_extensions)){
    FUNCTION1
} else {
    FUNCTION2
}

HttpClient won't import in Android Studio

For android API 28 and higher in Manifest.xml inside application tag

    <application
    .
    .
    .

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>

What is the best java image processing library/approach?

RoboRealm vision software list mentions JHLabs and NeatVision among lots of other non-Java based libraries.

Bootstrap 3 with remote Modal

For Bootstrap 3

The workflow I had to deal with was loading content with a url context that could change. So by default setup your modal with javascript or the href for the default context you want to show :

$('#myModal').modal({
        show: false,
        remote: 'some/context'
});

Destroying the modal wouldn't work for me because I wasn't loading from the same remote, thus I had to :

$(".some-action-class").on('click', function () {
        $('#myModal').removeData('bs.modal');
        $('#myModal').modal({remote: 'some/new/context?p=' + $(this).attr('buttonAttr') });
        $('#myModal').modal('show');
});

This of course was easily refactored into a js library and gives you a lot of flexibility with loading modals

I hope this saves someone 15 minutes of tinkering.

Check if current directory is a Git repository

Why not using exit codes? If a git repository exists in the current directory, then git branch and git tag commands return exit code of 0; otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:

git tag > /dev/null 2>&1 && [ $? -eq 0 ]

Advantage: Flexibe. It works for both bare and non-bare repositories, and in sh, zsh and bash.

Explanation

  1. git tag: Getting tags of the repository to determine if exists or not.
  2. > /dev/null 2>&1: Preventing from printing anything, including normal and error outputs.
  3. [ $? -eq 0 ]: Check if the previous command returned with exit code 0 or not. As you may know, every non-zero exit means something bad happened. $? gets the exit code of the previous command, and [, -eq and ] perform the comparison.

As an example, you can create a file named check-git-repo with the following contents, make it executable and run it:

#!/bin/sh

if git tag > /dev/null 2>&1 && [ $? -eq 0 ]; then
    echo "Repository exists!";
else
    echo "No repository here.";
fi

How to use document.getElementByName and getElementByTag?

It's getElementsByName() and getElementsByTagName() - note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".

Even if the function only returns one element it will still be in a NodeList of length one. So:

var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.

Assuming your form is the first (or only) form on the page you can do this:

document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements

How to insert element as a first child?

Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

What is the equivalent of the C# 'var' keyword in Java?

In general you can use Object class for any type, but you have do type casting later!

eg:-

Object object = 12;
    Object object1 = "Aditya";
    Object object2 = 12.12;

    System.out.println(Integer.parseInt(object.toString()) + 2);

    System.out.println(object1.toString() + " Kumar");
    System.out.println(Double.parseDouble(object2.toString()) + 2.12);

Seconds CountDown Timer

You need a public class for Form1 to initialize.

See this code:

namespace TimerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int counter = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            //Insert your code from before
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Again insert your code
        }
    }
}

I've tried this and it all worked fine

If you need anymore help feel free to comment :)

Remove duplicated rows

Or you could nest the data in cols 4 and 5 into a single row with tidyr:

library(tidyr)
df %>% nest(V4:V5)

# A tibble: 1 × 4
#                      V1    V2    V3             data
#                  <fctr> <int> <int>           <list>
#1 platform_external_dbus   202    16 <tibble [5 × 2]>

The col 2 and 3 duplicates are now removed for statistical analysis, but you have kept the col 4 and 5 data in a tibble and can go back to the original data frame at any point with unnest().

Detect changes in the DOM

Use the MutationObserver interface as shown in Gabriele Romanato's blog

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();

Is it possible to use pip to install a package from a private GitHub repository?

If you have your own library/package on GitHub, GitLab, etc., you have to add a tag to commit with a concrete version of the library, for example, v2.0, and then you can install your package:

pip install git+ssh://link/name/[email protected]

This works for me. Other solutions haven't worked for me.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Write / add data in JSON file using Node.js

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

MySQL supports Spatial data types and Point is a single-value type which can be used. Example:

CREATE TABLE `buildings` (
  `coordinate` POINT NOT NULL,
  /* Even from v5.7.5 you can define an index for it */
  SPATIAL INDEX `SPATIAL` (`coordinate`)
) ENGINE=InnoDB;

/* then for insertion you can */
INSERT INTO `buildings` 
(`coordinate`) 
VALUES
(POINT(40.71727401 -74.00898606));

Addition for BigDecimal

//you can do in this way...as BigDecimal is immutable so cant set values except in constructor

BigDecimal test = BigDecimal.ZERO;
BigDecimal result = test.add(new BigDecimal(30));
System.out.println(result);

result would be 30

How to pause / sleep thread or process in Android?

You probably don't want to do it that way. By putting an explicit sleep() in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.

Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.

Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.

IsNullOrEmpty with Object

object MyObject = null;

if (MyObject != null && !string.IsNullOrEmpty(MyObject.ToString())) { ... }

How to change collation of database, table, column?

You can run a php script.

               <?php
                   $con = mysql_connect('localhost','user','password');
                   if(!$con) { echo "Cannot connect to the database ";die();}
                   mysql_select_db('dbname');
                   $result=mysql_query('show tables');
                   while($tables = mysql_fetch_array($result)) {
                            foreach ($tables as $key => $value) {
                             mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
                       }}
                   echo "The collation of your database has been successfully changed!";
                ?>

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

Call javascript from MVC controller action

Yes, it is definitely possible using Javascript Result:

return JavaScript("Callback()");

Javascript should be referenced by your view:

function Callback(){
    // do something where you can call an action method in controller to pass some data via AJAX() request
}

How can I upgrade specific packages using pip and a requirements file?

If you upgrade a package, the old one will be uninstalled.

A convenient way to do this is to use this pip-upgrader which also updates the versions in your requirements.txt file for the chosen packages (or all packages).

Installation

pip install pip-upgrader

Usage

Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).

cd into your project directory, and then run:

pip-upgrade

Advanced usage

If the requirements are placed in a non-standard location, send them as arguments:

pip-upgrade path/to/requirements.txt

If you already know what package you want to upgrade, simply send them as arguments:

pip-upgrade -p django -p celery -p dateutil

If you need to upgrade to pre-release / post-release version, add --prerelease argument to your command.

Full disclosure: I wrote this package.

hexadecimal string to byte array in python

provided I understood correctly, you should look for binascii.unhexlify

import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]

Send Email Intent

use Anko - kotlin

context.email(email, subject, body)

Change SVN repository URL

In my case, the svn relocate command (as well as svn switch --relocate) failed for some reason (maybe the repo was not moved correctly, or something else). I faced this error:

$ svn relocate NEW_SERVER
svn: E195009: The repository at 'NEW_SERVER' has uuid 'e7500204-160a-403c-b4b6-6bc4f25883ea', but the WC has '3a8c444c-5998-40fb-8cb3-409b74712e46'

I did not want to redownload the whole repository, so I found a workaround. It worked in my case, but generally I can imagine a lot of things can get broken (so either backup your working copy, or be ready to re-checkout the whole repo if something goes wrong).

The repo address and its UUID are saved in the .svn/wc.db SQLite database file in your working copy. Just open the database (e.g. in SQLite Browser), browse table REPOSITORY, and change the root and uuid column values to the new ones. You can find the UUID of the new repo by issuing svn info NEW_SERVER.

Again, treat this as a last resort method.

How to get a jqGrid cell value when editing

Hi, I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.

My solution like this:

var userIDContent = $("#grid").getCell(id,"userID");  // Use getCell to get the content
//alert("userID:" +userID);  // you can see the content here.

//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val();  // var userID = $(userIDContent).attr('attrName');

Show all tables inside a MySQL database using PHP?

Try this:

SHOW TABLES FROM nameOfDatabase;

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

e.printStackTrace equivalent in python

e.printStackTrace equivalent in python

In Java, this does the following (docs):

public void printStackTrace()

Prints this throwable and its backtrace to the standard error stream...

This is used like this:

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}

In Java, the Standard Error stream is unbuffered so that output arrives immediately.

The same semantics in Python 2 are:

import traceback
import sys
try: # code that may raise an error
    pass 
except IOError as e: # exception handling
    # in Python 2, stderr is also unbuffered
    print >> sys.stderr, traceback.format_exc()
    # in Python 2, you can also from __future__ import print_function
    print(traceback.format_exc(), file=sys.stderr)
    # or as the top answer here demonstrates, use:
    traceback.print_exc()
    # which also uses stderr.

Python 3

In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:

    print(traceback.format_exception(None, # <- type(e) by docs, but ignored 
                                     e, e.__traceback__),
          file=sys.stderr, flush=True)

Conclusion:

In Python 3, therefore, traceback.print_exc(), although it uses sys.stderr by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print with flush=True.

Check if decimal value is null

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

Which Radio button in the group is checked?

You can wire the CheckedEvents of all the buttons against one handler. There you can easily get the correct Checkbox.

// Wire all events into this.
private void AllCheckBoxes_CheckedChanged(Object sender, EventArgs e) {
    // Check of the raiser of the event is a checked Checkbox.
    // Of course we also need to to cast it first.
    if (((RadioButton)sender).Checked) {
        // This is the correct control.
        RadioButton rb = (RadioButton)sender;
    }
}

Use chrome as browser in C#?

I don't know of any full Chrome component, but you could use WebKit, which is the rendering engine that Chrome uses. The Mono project made WebKit Sharp, which might work for you.

How to link html pages in same or different folders?

Also, this will go up a directory and then back down to another subfolder.

<a href = "../subfolder/page.html">link</a>

To go up multiple directories you can do this.

<a href = "../../page.html">link</a>

To go the root, I use this

<a href = "~/page.html">link</a>

Android: Rotate image in imageview by an angle

You can simply use rotation atribute of ImageView

Below is the attribute from ImageView with details from Android source

<!-- rotation of the view, in degrees. -->
<attr name="rotation" format="float" />

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

Recommended add-ons/plugins for Microsoft Visual Studio

Here is my list:

Google Play Services Library update and missing symbol @integer/google_play_services_version

I faced the same issue, and apparently Eclipse somehow left the version.xml file in /res/values from the original google-play-services_lib project while making a copy. I pulled the file from original project and pasted it in my copy of the project and the problem is fixed.

How do I position a div relative to the mouse pointer using jQuery?

You don not need to create a $(document).mousemove( function(e) {}) to handle mouse x,y. Get the event in the $.hover function and from there it is possible to get x and y positions of the mouse. See the code below:

$('foo').hover(function(e){
    var pos = [e.pageX-150,e.pageY];
    $('foo1').dialog( "option", "position", pos );
    $('foo1').dialog('open');
},function(){
    $('foo1').dialog('close');
});

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

Return positions of a regex match() in Javascript?

This member fn returns an array of 0-based positions, if any, of the input word inside the String object

String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline )
{
   /*besides '_word' param, others are flags (0|1)*/
   var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
   var _bound = _whole_words ? "\\b" : "" ;
   var _re = new RegExp( _bound+_word+_bound, _match_pattern );
   var _pos = [], _chunk, _index = 0 ;

   while( true )
   {
      _chunk = _re.exec( this ) ;
      if ( _chunk == null ) break ;
      _pos.push( _chunk['index'] ) ;
      _re.lastIndex = _chunk['index']+1 ;
   }

   return _pos ;
}

Now try

var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log( _sentence.matching_positions( _word, 1, 0, 0 ) );
console.log( _sentence.matching_positions( _word, 1, 1, 0 ) );

You can also input regular expressions:

var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );

Here one gets the position index of linear term.

Linear regression with matplotlib / numpy

Another quick and dirty answer is that you can just convert your list to an array using:

import numpy as np
arr = np.asarray(listname)

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;

@end


@implementation YourObject


-(id) copyWithZone: (NSZone *) zone
{
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre: self.name];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;
}

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

Generic deep diff between two objects

I have used this piece of code for doing the task that you describe:

function mergeRecursive(obj1, obj2) {
    for (var p in obj2) {
        try {
            if(obj2[p].constructor == Object) {
                obj1[p] = mergeRecursive(obj1[p], obj2[p]);
            }
            // Property in destination object set; update its value.
            else if (Ext.isArray(obj2[p])) {
                // obj1[p] = [];
                if (obj2[p].length < 1) {
                    obj1[p] = obj2[p];
                }
                else {
                    obj1[p] = mergeRecursive(obj1[p], obj2[p]);
                }

            }else{
                obj1[p] = obj2[p];
            }
        } catch (e) {
            // Property in destination object not set; create it and set its value.
            obj1[p] = obj2[p];
        }
    }
    return obj1;
}

this will get you a new object that will merge all the changes between the old object and the new object from your form

Calculate average in java

 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

How to download and save a file from Internet using Java?

Personally, I've found Apache's HttpClient to be more than capable of everything I've needed to do with regards to this. Here is a great tutorial on using HttpClient

How to select all textareas and textboxes using jQuery?

Password boxes are also textboxes, so if you need them too:

$("input[type='text'], textarea, input[type='password']").css({width: "90%"});

and while file-input is a bit different, you may want to include them too (eg. for visual consistency):

$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Codeigniter's `where` and `or_where`

You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.

$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->group_start() //this will start grouping
    ->where('library.available_until >=', date("Y-m-d H:i:s"))
    ->or_where('library.available_until =', "00-00-00 00:00:00")
    ->group_end() //this will end grouping
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id')

Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Change :hover CSS properties with JavaScript

If you use lightweight html ux lang, check here an example, write:

div root
 .onmouseover = ev => {root.style.backgroundColor='red'}
 .onmouseleave = ev => {root.style.backgroundColor='initial'}

The code above performes the css :hover metatag.

Eloquent get only one column as an array

You can use the pluck method:

Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();

For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.

How to copy a collection from one database to another in MongoDB

In my case, I had to use a subset of attributes from the old collection in my new collection. So I ended up choosing those attributes while calling insert on the new collection.

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

How do I remove a CLOSE_WAIT socket connection

As described by Crist Clark.

CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.

The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.

Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

Drop shadow on a div container?

CSS3 has a box-shadow property. Vendor prefixes are required at the moment for maximum browser compatibility.

div.box-shadow {
    -webkit-box-shadow: 2px 2px 4px 1px #fff;
    box-shadow: 2px 2px 4px 1px #fff;
}

There is a generator available at css3please.

Javascript : get <img> src and set as variable?

in this situation, you would grab the element by its id using getElementById and then just use .src

var youtubeimgsrc = document.getElementById("youtubeimg").src;

Difference between \w and \b regular expression meta characters

@Mahender, you probably meant the difference between \W (instead of \w) and \b. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.

\W would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b can be thought of as (\W|^|$). [Edit: as @?mega mentions below, \b is a zero-length match so (\W|^|$) is not strictly correct, but hopefully helps explain the diff]

Quick example: For the string Hello World, .+\W would match Hello_ (with the space) but will not match World. .+\b would match both Hello and World.

Converting an object to a string

For non-nested objects:

Object.entries(o).map(x=>x.join(":")).join("\r\n")

How to read until EOF from cin in C++

Using loops:

#include <iostream>
using namespace std;
...
// numbers
int n;
while (cin >> n)
{
   ...
}
// lines
string line;
while (getline(cin, line))
{
   ...
}
// characters
char c;
while (cin.get(c))
{
   ...
}

resource

How to get a Static property with Reflection

The below seems to work for me.

using System;
using System.Reflection;

public class ReflectStatic
{
    private static int SomeNumber {get; set;}
    public static object SomeReference {get; set;}
    static ReflectStatic()
    {
        SomeReference = new object();
        Console.WriteLine(SomeReference.GetHashCode());
    }
}

public class Program
{
    public static void Main()
    {
        var rs = new ReflectStatic();
        var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
        if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
        Console.WriteLine(pi.GetValue(rs, null).GetHashCode());


    }
}

How to use vagrant in a proxy environment?

You will want to install the plugin proxyconf since this makes configuring the proxy for the guest machines pretty straight forward in the VagrantFile

config.proxy.http     = "http://proxy:8888"
config.proxy.https    = "http://proxy:8883"
config.proxy.no_proxy = "localhost,127.0.0.1"

However, there's quite a few things that could still go wrong. Firstly, you probably can't install vagrant plugins when behind the proxy. If that's the case you should download the source e.g. from rubygems.org and install from source

$ vagrant plugin install vagrant-proxyconf --plugin-source file://fully/qualified/path/vagrant-proxyconf-1.x.0.gem

If you solve that problem you might have the fortune of being behind an NTLM proxy, which means that if you are using *nix on your guest machines then you still have some way to go, because NTLM authentication is not supported natively There are many ways of solving that. I've used CNTLM to solve tht part of the puzzle. It acts as glue between standard authorization protocols and NTLM

For a complete walk through, have a look at this blog entry about setting vagrant up behind a corporate proxy

Direct download from Google Drive using Google Drive API

I faced an issue in direct download because I was logged in using multiple Google accounts. Solution is append authUser=0 parameter. Sample request URL to download :https://drive.google.com/uc?id=FILEID&authuser=0&export=download

Laravel check if collection is empty

To determine if there are any results you can do any of the following:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }

Notes / References

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty() https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) works because the Collection implements Countable and an internal count() method:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

So what you can do is :

if (!$mentors->intern->employee->isEmpty()) { }

Run PHP function on html button click

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

VB.NET: how to prevent user input in a ComboBox

this is the most simple way but it works for me with a ComboBox1 name

SOLUTION on 3 Basic STEPS:

step 1.

Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:

     Dim xCurrentTextValue as string

step 2.

Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value

Example:

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown

    xCurrentTextValue = ComboBox1.Text

    If e.KeyCode <> Keys.Enter Then
        Me.ComboBox1.Text = xCmbItem
    End If

End Sub

step 3.

Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value

Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
    If Len(xCurrentTextValue) > 0 Then
        Me.ComboBox1.Text = xCurrentTextValue

    End If
End Sub

========================================================== that's it,

Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box


!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use

THIS IS THE CORRECT CODE

xCurrentTextValue = ComboBox1.Text

If e.KeyCode <> Keys.Enter Then
    Me.ComboBox1.Text = xCurrentTextValue
End If

ContractFilter mismatch at the EndpointDispatcher exception

I had this problem and found that in my proxy generator, which I copied from another service, I forgot to change the name of the service.

I changed this...

Return New Service1DataClient(binding, New EndpointAddress(My.Settings.WCFServiceURL & "/Service1Data.svc"))

to...

Return New Service2DataClient(binding, New EndpointAddress(My.Settings.WCFServiceURL & "/Service2Data.svc"))

It was a simple code error, but nearly impossible to debug. I hope this saves someone time.

Java - Relative path of a file in a java web application

there is another way, if you are using a container like Tomcat :

String textPath = "http://localhost:8080/NameOfWebapp/resources/images/file.txt";

What is the @Html.DisplayFor syntax for?

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

Save child objects automatically using JPA Hibernate

Following program describe how bidirectional relation work in hibernate.

When parent will save its list of child object will be auto save.

On Parent side:

    @Entity
    @Table(name="clients")
    public class Clients implements Serializable  {

         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)     
         @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
          List<SmsNumbers> smsNumbers;
    }

And put the following annotation on the child side:

  @Entity
  @Table(name="smsnumbers")
  public class SmsNumbers implements Serializable {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     int id;
     String number;
     String status;
     Date reg_date;
     @ManyToOne
     @JoinColumn(name = "client_id")
     private Clients clients;

    // and getter setter.

 }

Main class:

 public static void main(String arr[])
 {
    Session session = HibernateUtil.openSession();
      //getting transaction object from session object
    session.beginTransaction();

    Clients cl=new Clients("Murali", "1010101010");
    SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
    SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
    SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
    List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
    lstSmsNumbers.add(sms1);
    lstSmsNumbers.add(sms2);
    lstSmsNumbers.add(sms3);
    cl.setSmsNumbers(lstSmsNumbers);
    session.saveOrUpdate(cl);
    session.getTransaction().commit(); 
    session.close();    

 }

Selenium Webdriver submit() vs click()

Also, correct me if I'm wrong, but I believe that submit will wait for a new page to load, whereas click will immediately continue executing code

How to remove a package in sublime text 2

Just wanted to add, that after you remove the package in question you might also need to check to see if it's listed in the list of packages in the following area and manually remove its listing:

Preferences>Package Settings>Package Control>Settings - User

{
    "auto_upgrade_last_run": null,
    "installed_packages":
    [
        "AdvancedNewFile",
        "Emmet",
        "Package Control",
        "SideBarEnhancements",
        "Sublimerge"
    ]
}

In my instance, my trial period for "Sublimerge" had run out and I would get a popup every time I would start Sublime Text 2 saying:

"The package specified, Sublimerge, is not available"

I would have to close the event window out before being able to do anything in ST2.

But in my case, even after successfully removing the package through package control, I still received a event window popup message telling me "Sublimerge" wasn't available. This didn't make any sense as I had successfully removed the package.

It wasn't until I found this "auto_upgrade_last_run" file and manually removed the "Sublimerge" entry and saved my edit, did the message go away.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

CASE .. WHEN expression in Oracle SQL

CASE TO_CHAR(META.RHCONTRATOSFOLHA.CONTRATO)
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0001' THEN '91RJ'
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0002' THEN '91SP'
END CONTRATO,

00905. 00000 -  "missing keyword"
*Cause:    
*Action:
Erro na linha: 15 Coluna: 11

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

Are multiple `.gitignore`s frowned on?

There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs, cache, uploads directories etc.

So what I always do is to add a .gitignore file in those directories with the following content:

*
!.gitignore

With this .gitignore file, Git will not track any files in those directories yet still allow me to add the .gitignore file and hence the directory itself to the repo.

Git Ignores and Maven targets

add following lines in gitignore, from all undesirable files

/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

How to export JavaScript array info to csv (on client side)?

There are two questions here:

  1. How to convert an array to csv string
  2. How to save that string to a file

All the answers to the first question (except the one by Milimetric) here seem like an overkill. And the one by Milimetric does not cover altrenative requirements, like surrounding strings with quotes or converting arrays of objects.

Here are my takes on this:

For a simple csv one map() and a join() are enough:

    var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];
    var csv = test_array.map(function(d){
        return d.join();
    }).join('\n');

    /* Results in 
    name1,2,3
    name2,4,5
    name3,6,7
    name4,8,9
    name5,10,11

This method also allows you to specify column separator other than a comma in the inner join. for example a tab: d.join('\t')

On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:

var csv = test_array.map(function(d){
       return JSON.stringify(d);
    })
    .join('\n') 
    .replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ]
                                   // brackets from each line 

/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11

if you have array of objects like :

var data = [
  {"title": "Book title 1", "author": "Name1 Surname1"},
  {"title": "Book title 2", "author": "Name2 Surname2"},
  {"title": "Book title 3", "author": "Name3 Surname3"},
  {"title": "Book title 4", "author": "Name4 Surname4"}
];

// use
var csv = data.map(function(d){
        return JSON.stringify(Object.values(d));
    })
    .join('\n') 
    .replace(/(^\[)|(\]$)/mg, '');

Count number of lines in a git repository

Try:

find . -type f -name '*.*' -exec wc -l {} + 

on the directory/directories in question

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...