Programs & Examples On #Heapalloc

Does Java have something like C#'s ref and out keywords?

Actually there is neither ref nor out keyword equivalent in Java language as far as I know. However I've just transformed a C# code into Java that uses out parameter and will advise what I've just done. You should wrap whatever object into a wrapper class and pass the values wrapped in wrapper object instance as follows;

A Simple Example For Using Wrapper

Here is the Wrapper Class;

public class Wrapper {
    public Object ref1; // use this as ref
    public Object ref2; // use this as out

    public Wrapper(Object ref1) {
        this.ref1 = ref1;
    }
}

And here is the test code;

public class Test {

    public static void main(String[] args) {
        String abc = "abc";
        changeString(abc);
        System.out.println("Initial object: " + abc); //wont print "def"

        Wrapper w = new Wrapper(abc);
        changeStringWithWrapper(w);
        System.out.println("Updated object: " + w.ref1);
        System.out.println("Out     object: " + w.ref2);
    }

    // This won't work
    public static void changeString(String str) {
        str = "def";
    }

    // This will work
    public static void changeStringWithWrapper(Wrapper w) {
        w.ref1 = "def";
        w.ref2 = "And this should be used as out!";
    }

}

A Real World Example

A C#.NET method using out parameter

Here there is a C#.NET method that is using out keyword;

public bool Contains(T value)
{
    BinaryTreeNode<T> parent;
    return FindWithParent(value, out parent) != null;
}

private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
    BinaryTreeNode<T> current = _head;
    parent = null;

    while(current != null)
    {
        int result = current.CompareTo(value);

        if (result > 0)
        {
            parent = current;
            current = current.Left;
        }
        else if (result < 0)
        {
            parent = current;
            current = current.Right;
        }
        else
        {
            break;
        }
    }

    return current;
}

Java Equivalent of the C# code that is using the out parameter

And the Java equivalent of this method with the help of wrapper class is as follows;

public boolean contains(T value) {
    BinaryTreeNodeGeneration<T> result = findWithParent(value);

    return (result != null);
}

private BinaryTreeNodeGeneration<T> findWithParent(T value) {
    BinaryTreeNode<T> current = head;
    BinaryTreeNode<T> parent = null;
    BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
    resultGeneration.setParentNode(null);

    while(current != null) {
        int result = current.compareTo(value);

        if(result >0) {
            parent = current;
            current = current.left;
        } else if(result < 0) {
            parent = current;
            current = current.right;
        } else {
            break;
        }
    }

    resultGeneration.setChildNode(current);
    resultGeneration.setParentNode(parent);

    return resultGeneration;
}

Wrapper Class

And the wrapper class used in this Java code is as below;

public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>>  {

    private BinaryTreeNode<TNode>   parentNode;
    private BinaryTreeNode<TNode>   childNode;

    public BinaryTreeNodeGeneration() {
        this.parentNode = null;
        this.childNode = null;
    }

    public BinaryTreeNode<TNode> getParentNode() {
        return parentNode;
    }

    public void setParentNode(BinaryTreeNode<TNode> parentNode) {
        this.parentNode = parentNode;
    }

    public BinaryTreeNode<TNode> getChildNode() {
        return childNode;
    }

    public void setChildNode(BinaryTreeNode<TNode> childNode) {
        this.childNode = childNode;
    }

}

How do I fix 'ImportError: cannot import name IncompleteRead'?

This should work for you. Follow these simple steps.

First, let's remove the pip which is already installed so it won't cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.

Method-1

Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

or

Method-2

Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name get-pip.py .

Step: 3 use: cd to go to the same directory as your get-pip.py file

Step: 4 use: sudo python get-pip.py

It will install pip latest version.

or

Method-3

Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.

parent & child with position fixed, parent overflow:hidden bug

2016 update:

You can create a new stacking context, as seen on Coderwall:

<div style="transform: translate3d(0,0,0);overflow:hidden">
   <img style="position:fixed; ..." />
</div>

Which refers to http://dev.w3.org/csswg/css-transforms/#transform-rendering

For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

How to wait till the response comes from the $http request, in angularjs?

for people new to this you can also use a callback for example:

In your service:

.factory('DataHandler',function ($http){

   var GetRandomArtists = function(data, callback){
     $http.post(URL, data).success(function (response) {
         callback(response);
      });
   } 
})

In your controller:

    DataHandler.GetRandomArtists(3, function(response){
      $scope.data.random_artists = response;
   });

How to listen state changes in react.js?

I think you should be using below Component Lifecycle as if you have an input property which on update needs to trigger your component update then this is the best place to do it as its will be called before render you even can do update component state to be reflected on the view.

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

How to remove all numbers from string?

For Western Arabic numbers (0-9):

$words = preg_replace('/[0-9]+/', '', $words);

For all numerals including Western Arabic (e.g. Indian):

$words = '????';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+ matches multiple numerals.
  • The modifier /u enables unicode string treatment. This modifier is important, otherwise the numerals would not match.

How to detect Esc Key Press in React and how to handle it

You'll want to listen for escape's keyCode (27) from the React SyntheticKeyBoardEvent onKeyDown:

const EscapeListen = React.createClass({
  handleKeyDown: function(e) {
    if (e.keyCode === 27) {
      console.log('You pressed the escape key!')
    }
  },

  render: function() {
    return (
      <input type='text'
             onKeyDown={this.handleKeyDown} />
    )
  }
})

Brad Colthurst's CodePen posted in the question's comments is helpful for finding key codes for other keys.

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

Rearrange columns using cut

Expanding on the answer from @Met, also using Perl:
If the input and output are TAB-delimited:

perl -F'\t' -lane 'print join "\t", @F[1, 0]' in_file

If the input and output are whitespace-delimited:

perl -lane 'print join " ", @F[1, 0]' in_file

Here,
-e tells Perl to look for the code inline, rather than in a separate script file,
-n reads the input 1 line at a time,
-l removes the input record separator (\n on *NIX) after reading the line (similar to chomp), and add output record separator (\n on *NIX) to each print,
-a splits the input line on whitespace into array @F,
-F'\t' in combination with -a splits the input line on TABs, instead of whitespace into array @F.

@F[1, 0] is the array made up of the 2nd and 1st elements of array @F, in this order. Remember that arrays in Perl are zero-indexed, while fields in cut are 1-indexed. So fields in @F[0, 1] are the same fields as the ones in cut -f1,2.

Note that such notation enables more flexible manipulation of input than in some other answers posted above (which are fine for a simple task). For example:

# reverses the order of fields:
perl -F'\t' -lane 'print join "\t", reverse @F' in_file

# prints last and first fields only:
perl -F'\t' -lane 'print join "\t", @F[-1, 0]' in_file

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Case insensitive regular expression without re.compile?

#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string. 
#'re.search' returns location of the where the match is found 
#'re.compile' creates a regex object that can be used for multiple matches

 >>> s = r'TeSt'   
 >>> print (re.match(s, r'test123', re.I))
 <_sre.SRE_Match object; span=(0, 4), match='test'>
 # OR
 >>> pattern = re.compile(s, re.I)
 >>> print(pattern.match(r'test123'))
 <_sre.SRE_Match object; span=(0, 4), match='test'>

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

SQL Server Case Statement when IS NULL

Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx

'Access denied for user 'root'@'localhost' (using password: NO)'

  1. Change the password from config.inc.php present in C:\xampp\phpMyAdmin.
  2. Type mysql -u root -p in the command prompt.
  3. You will be asked to enter the password. Enter that password which you updated in the config.inc.php.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

In my case I wasn't aware that the PHP run by Apache was different from the one run by CLI. That might be the case if during configuration in httpd.conf you specified a PHP module, not being the default one your CLI uses.

How to implement "confirmation" dialog in Jquery UI dialog?

How about this:

$("ul li a").click(function() {

el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
                             draggable:true,
                             modal: true,
                             buttons: { "Ok": function() {
                                el.parent().remove();
                                $(this).dialog("close"); } }
                           });
$("#confirmDialog").dialog("open");

return false;
});

I have tested it at this html:

<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>

It removes the whole li element, you can adapt it at your needs.

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

I was also getting the same issue of breaking constraints in the log, for a viewCircle in the xib. I almost tried everything listed above and nothing was working for me. Then I tried to change the priority of the Height constraint which was breaking in the log(confirmed by adding an identifiers for the constraints on the xib)enter image description here

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

Detect if device is iOS

Detecting iOS

With iOS 13 iPad both User agent and platform strings are changed and differentiating between iPad and MacOS seems possible, so all answers below needs to take that into account now.

This might be the shortest alternative that also covers iOS 13:

function iOS() {
  return [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ].includes(navigator.platform)
  // iPad on iOS 13 detection
  || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
}

iOS will be either true or false

Worse option: User agent sniffing

User Agent sniffing is more dangerous and problems appear often.

On iPad iOS 13, the user agent is identical with that of a MacOS 13 computer, but if you ignore iPads this might work still for a while:

var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent); // fails on iPad iOS 13

The !window.MSStream is to not incorrectly detect IE11, see here and here.

Note: Both navigator.userAgent and navigator.platform can be faked by the user or a browser extension.

Browser extensions to change userAgent or platform exist because websites use too heavy-handed detection and often disable some features even if the user's browser would otherwise be able to use that feature.

To de-escalate this conflict with users it's recommended to detect specifically for each case the exact features that your website needs. Then when the user gets a browser with the needed feature it will already work without additional code changes.

Detecting iOS version

The most common way of detecting the iOS version is by parsing it from the User Agent string. But there is also feature detection inference*;

We know for a fact that history API was introduced in iOS4 - matchMedia API in iOS5 - webAudio API in iOS6 - WebSpeech API in iOS7 and so on.

Note: The following code is not reliable and will break if any of these HTML5 features is deprecated in a newer iOS version. You have been warned!

function iOSversion() {

  if (iOS) { // <-- Use the one here above
    if (window.indexedDB) { return 'iOS 8 and up'; }
    if (window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (window.webkitAudioContext) { return 'iOS 6'; }
    if (window.matchMedia) { return 'iOS 5'; }
    if (window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

Dropping Unique constraint from MySQL table

  1. First delete table

  2. go to SQL

Use this code:

CREATE  TABLE service( --tablename 
  `serviceid` int(11) NOT NULL,--columns
  `customerid` varchar(20) DEFAULT NULL,--columns
  `dos` varchar(30) NOT NULL,--columns
  `productname` varchar(150) NOT NULL,--columns
  `modelnumber` bigint(12) NOT NULL,--columns
  `serialnumber` bigint(20) NOT NULL,--columns
  `serviceby` varchar(20) DEFAULT NULL--columns
)
--INSERT VALUES
INSERT INTO `service` (`serviceid`, `customerid`, `dos`, `productname`, `modelnumber`, `serialnumber`, `serviceby`) VALUES
(1, '1', '12/10/2018', 'mouse', 1234555, 234234324, '9999'),
(2, '09', '12/10/2018', 'vhbgj', 79746385, 18923984, '9999'),
(3, '23', '12/10/2018', 'mouse', 123455534, 11111123, '9999'),
(4, '23', '12/10/2018', 'mouse', 12345, 84848, '9999'),
(5, '546456', '12/10/2018', 'ughg', 772882, 457283, '9999'),
(6, '23', '12/10/2018', 'keyboard', 7878787878, 22222, '1'),
(7, '23', '12/10/2018', 'java', 11, 98908, '9999'),
(8, '128', '12/10/2018', 'mouse', 9912280626, 111111, '9999'),
(9, '23', '15/10/2018', 'hg', 29829354, 4564564646, '9999'),
(10, '12', '15/10/2018', '2', 5256, 888888, '9999');
--before droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  unique`modelnumber` (`modelnumber`),
  ADD  unique`serialnumber` (`serialnumber`),
  ADD unique`modelnumber_2` (`modelnumber`);
--after droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  modelnumber` (`modelnumber`),
  ADD  serialnumber` (`serialnumber`),
  ADD modelnumber_2` (`modelnumber`);

Git undo changes in some files

Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?

In your situation (for your example) it would be:

prompt> git add B
prompt> git commit

Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use

prompt> git reset A

or

prompt> git checkout HEAD -- A

to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).

How do I get countifs to select all non-blank cells in Excel?

You can try this :

=COUNTIF(Data!A2:A300,"<>"&"")

Change Button color onClick

1.

function setColor(e) {
  var target = e.target,
      count = +target.dataset.count;

   target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
   target.dataset.count = count === 1 ? 0 : 1;
   /* 

   () : ? - this is conditional (ternary) operator - equals 

   if (count === 1) {
      target.style.backgroundColor = "#7FFF00";
      target.dataset.count = 0;
   } else {
      target.style.backgroundColor = "#FFFFFF";
      target.dataset.count = 1;
   } 
   target.dataset - return all "data attributes" for current element, 
   in the form of object, 
   and you don't need use global variable in order to save the state 0 or 1
  */ 
}


<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)"; 
  data-count="1" 
/>

2.

function setColor(e) {
   var target = e.target,
       status = e.target.classList.contains('active');

   e.target.classList.add(status ? 'inactive' : 'active');
   e.target.classList.remove(status ? 'active' : 'inactive'); 
}

.active {
  background-color: #7FFF00;  
}

.inactive {
  background-color: #FFFFFF;
}

<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)" 
/>

([conditional (ternary) operator])

Example-1

Example-2

window.open with headers

You can't directly add custom headers with window.open() in popup window but to work that we have two possible solutions


  1. Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in<i>window.open()</i> here is abc.html
        $.ajax({
        url: "ORIGIONAL_URL",
        type: 'GET',
        dataType: 'json',
        headers: {
            Authorization : 'Bearer ' + data.id_token,
            AuthorizationCheck : 'AccessCode ' +data.checkSum , 
            ContentType :'application/json'
        },

        success: function (result) {
              console.log(result);
        },
        error: function (error) {

        } });

call html

window.open('*\abc.html')

here CORS policy can block the request if CORS is not enabled in requested URL.


  1. You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.

Suppose in Java Servlet(/requestURL) we'll make this request

`

        String[] responseHeader= new String[2];
        responseHeader[0] = "Bearer " + id_token;
        responseHeader[1] = "AccessCode " + checkSum;

        String url = "ORIGIONAL_URL";

        URL obj = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Authorization", responseHeader[0]);
        urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new 
                         InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response1 = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response1.append(inputLine);
            }
            in.close();
            response.sendRedirect(response1.toString());
            // print result
            System.out.println(response1.toString());
        } else {
            System.out.println("GET request not worked");
        }

`

call servlet in window.open('/requestURL')

What is a good regular expression to match a URL?

Regex if you want to ensure URL starts with HTTP/HTTPS:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you do not require HTTP protocol:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.

Example JavaScript implementation:

_x000D_
_x000D_
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
  alert("Successful match");_x000D_
} else {_x000D_
  alert("No match");_x000D_
}
_x000D_
_x000D_
_x000D_

No == operator found while comparing structs in C++

You need to explicitly define operator == for MyStruct1.

struct MyStruct1 {
  bool operator == (const MyStruct1 &rhs) const
  { /* your logic for comparision between "*this" and "rhs" */ }
};

Now the == comparison is legal for 2 such objects.

How to change DataTable columns order

We Can use this method for changing the column index but should be applied to all the columns if there are more than two number of columns otherwise it will show all the Improper values from data table....................

How to trigger checkbox click event even if it's checked through Javascript code?

Trigger function from jQuery could be your answer.

jQuery docs says: Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user

Thus best one line solution should be:

$('.selector_class').trigger('click');

//or

$('#foo').click();

converting CSV/XLS to JSON?

Since Powershell 3.0 (shipped with Windows 8, available for Windows 7 and windows Server 2008 but not Windows Vista ) you can use the built-in convertto-json commandlet:

PS E:> $topicsjson = import-csv .\itinerary-all.csv | ConvertTo-Json 

PS E:\> $topicsjson.Length
11909

PS E:\> $topicsjson.getType()

IsPublic IsSerial Name                                     BaseType                  
-------- -------- ----                                     --------                  
True     True     Object[]                                 System.Array              

Online Help Page on Technet

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:

--ignore-space-change 
--ignore-all-space 
--ignore-space-at-eol

Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

How can I make one python file run another?

It may be called abc.py from the main script as below:

#!/usr/bin/python
import abc

abc.py may be something like this:

print'abc'

iFrame onload JavaScript event

Your code is correct. Just test to ensure it is being called like:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>

Convert String into a Class Object

Continuing from my comment. toString is not the solution. Some good soul has written whole code for serialization and deserialization of an object in Java. See here: http://www.javabeginner.com/uncategorized/java-serialization

Suggested read:

  1. Old and good Java Technical Article on Serialization
  2. http://java.sun.com/developer/technicalArticles/ALT/serialization/
  3. http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/serial.html

Is there a way to list open transactions on SQL Server 2000 database?

You can get all the information of active transaction by the help of below query

SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION 
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL

and it will give below similar result enter image description here

and you close that transaction by the help below KILL query by refering session id

KILL 77

How to include a sub-view in Blade templates?

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
      @include('parentFolder.childFolder.mypage')
  </html>

Mask for an Input to allow phone numbers?

I Think the simplest solutions is to add ngx-mask

npm i --save ngx-mask

then you can do

<input type='text' mask='(000) 000-0000' >

OR

<p>{{ phoneVar | mask: '(000) 000-0000' }} </p>

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

TypeScript function overloading

As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.

myComponent {
  method(): { console.info("no args"); },
  method(arg): { console.info("with arg"); }
}

Calling:

myComponent.method()

seems to execute the method with arguments, silently ignoring the no-arg version, with output:

with arg

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

UPDATE and REPLACE part of a string

you should use the below update query

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4

Either of the above queries should work.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

Remove all spaces from a string in SQL Server

A functional version (udf) that removes spaces, cr, lf, tabs or configurable.

select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as S

Result: '234asdfwefwef3x'

alter function Common.RemoveWhitespace
(
    @pString nvarchar(max),
    @pWhitespaceCharsOpt nvarchar(max) = null -- default: tab, lf, cr, space 
)  
returns nvarchar(max) as
/*--------------------------------------------------------------------------------------------------
    Purpose:   Compress whitespace

    Example:  select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as s 
              -- Result: 234asdfwefwef3x

    Modified    By          Description
    ----------  ----------- --------------------------------------------------------------------
    2018.07.24  crokusek    Initial Version 
  --------------------------------------------------------------------------------------------------*/ 
begin    
    declare 
        @maxLen bigint = 1073741823, -- (2^31 - 1) / 2 (https://stackoverflow.com/a/4270085/538763)
        @whitespaceChars nvarchar(30) = coalesce(
            @pWhitespaceCharsOpt, 
            char(9) + char(10) + char(13) + char(32));  -- tab, lf, cr, space

    declare
        @whitespacePattern nvarchar(30) = '%[' + @whitespaceChars + ']%',
        @nonWhitespacePattern nvarchar(30) = '%[^' + @whitespaceChars + ']%',
        @previousString nvarchar(max) = '';

    while (@pString != @previousString)
    begin
        set @previousString = @pString;

        declare
            @whiteIndex int = patindex(@whitespacePattern, @pString);

        if (@whiteIndex > 0)
        begin                   
            declare 
                @whitespaceLength int = nullif(patindex(@nonWhitespacePattern, substring(@pString, @whiteIndex, @maxLen)), 0) - 1;                

            set @pString = 
                substring(@pString, 1, @whiteIndex - 1) + 
                iif(@whiteSpaceLength > 0, substring(@pString, @whiteIndex + @whiteSpaceLength, @maxLen), '');
        end        
    end        
    return @pString;
end
go

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

What's the difference between xsd:include and xsd:import?

The fundamental difference between include and import is that you must use import to refer to declarations or definitions that are in a different target namespace and you must use include to refer to declarations or definitions that are (or will be) in the same target namespace.

Source: https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

Should a RESTful 'PUT' operation return something

The HTTP/1.1 spec (section 9.6) discusses the appropriate response/error codes. However it doesn't address the response content.

What would you expect ? A simple HTTP response code (200 etc.) seems straightforward and unambiguous to me.

What version of javac built my jar?

Following up on @David J. Liszewski's answer, I ran the following commands to extract the jar file's manifest on Ubuntu:

# Determine the manifest file name:
$ jar tf LuceneSearch.jar | grep -i manifest
META-INF/MANIFEST.MF

# Extract the file:
$ sudo jar xf LuceneSearch.jar META-INF/MANIFEST.MF

# Print the file's contents:
$ more META-INF/MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.7.0_25-b30 (Oracle Corporation)
Main-Class: org.wikimedia.lsearch.config.StartupManager

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

CSS transition between left -> right and top -> bottom positions

For elements with dynamic width it's possible to use transform: translateX(-100%); to counter the horizontal percentage value. This leads to two possible solutions:

1. Option: moving the element in the entire viewport:

Transition from:

transform: translateX(0);

to

transform: translateX(calc(100vw - 100%));

_x000D_
_x000D_
#viewportPendulum {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateX(calc(100vw - 100%));_x000D_
  }_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
_x000D_
_x000D_

2. Option: moving the element in the parent container:

Transition from:

transform: translateX(0);
left: 0;

to

left: 100%;
transform: translateX(-100%);

_x000D_
_x000D_
#parentPendulum {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  animation: 2s ease-in-out infinite alternate swingParent;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
    left: 0;_x000D_
  }_x000D_
  to {_x000D_
    left: 100%;_x000D_
    transform: translateX(-100%);_x000D_
  }_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2rem 0;_x000D_
  margin: 2rem 15%;_x000D_
  background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Demo on Codepen

Note: This approach can easily be extended to work for vertical positioning. Visit example here.

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

React.js: Identifying different inputs with one onChange handler

You can also do it like this:

...
constructor() {
    super();
    this.state = { input1: 0, input2: 0 };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(input, value) {
    this.setState({
        [input]: value
    })
}

render() {
    const total = this.state.input1 + this.state.input2;
    return (
        <div>
            {total}<br />
            <input type="text" onChange={e => this.handleChange('input1', e.target.value)} />
            <input type="text" onChange={e => this.handleChange('input2', e.target.value)} />
        </div>
    )
}

Form inside a form, is that alright?

It's not valid XHTML to have to have nested forms. However, you can use multiple submit buttons and use a serverside script to run different codes depending on which button the users has clicked.

Can't operator == be applied to generic types in C#?

The .Equals() works for me while TKey is a generic type.

public virtual TOutputDto GetOne(TKey id)
{
    var entity =
        _unitOfWork.BaseRepository
            .FindByCondition(x => 
                !x.IsDelete && 
                x.Id.Equals(id))
            .SingleOrDefault();


    // ...
}

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

Mockito: Trying to spy on method is calling the original method

Bit late to the party but above solutions did not work for me , so sharing my 0.02$

Mokcito version: 1.10.19

MyClass.java

private int handleAction(List<String> argList, String action)

Test.java

MyClass spy = PowerMockito.spy(new MyClass());

Following did NOT work for me (actual method was being called):

1.

doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());

2.

doReturn(0).when(spy , "handleAction", any(), anyString());

3.

doReturn(0).when(spy , "handleAction", null, null);

Following WORKED:

doReturn(0).when(spy , "handleAction", any(List.class), anyString());

How can I confirm a database is Oracle & what version it is using SQL?

For Oracle use:

Select * from v$version;

For SQL server use:

Select @@VERSION as Version

and for MySQL use:

Show variables LIKE "%version%";

Enum to String C++

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

How can I get the values of data attributes in JavaScript code?

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

_x000D_
_x000D_
var elem = document.getElementById('the-span');_x000D_
_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type   = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
);
_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
_x000D_
_x000D_
_x000D_

Get length of array?

Length of an array:

UBound(columns)-LBound(columns)+1

UBound alone is not the best method for getting the length of every array as arrays in VBA can start at different indexes, e.g Dim arr(2 to 10)

UBound will return correct results only if the array is 1-based (starts indexing at 1 e.g. Dim arr(1 to 10). It will return wrong results in any other circumstance e.g. Dim arr(10)

More on the VBA Array in this VBA Array tutorial.

Exit Shell Script Based on Process Exit Code

If you just call exit in Bash without any parameters, it will return the exit code of the last command. Combined with OR, Bash should only invoke exit, if the previous command fails. But I haven't tested this.

command1 || exit;
command2 || exit;

Bash will also store the exit code of the last command in the variable $?.

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I've been fighting with this issue for a long time, and just y'day I figure out how to make it gone and today I can run a 50 threads process calling selenium without seen this issue anymore and also stop crashing my machine with outofmemory issue with too many open chromedriver processes.

  1. I am using selenium 3.7.1, chromedrive 2.33, java.version: '1.8.0', redhat ver '3.10.0-693.5.2.el7.x86_64', chrome browser version: 60.0.3112.90;
  2. running an open session with screen, to be sure my session never dies,
  3. running Xvfb : nohup Xvfb -ac :15 -screen 0 1280x1024x16 &
  4. export DISPLAY:15 from .bashsh/.profile

these 4 items are the basic setting everyone would already know, now comes the code, where all made a lot of difference to achieve the success:

public class HttpWebClient {
    public static ChromeDriverService service;
    public ThreadLocal<WebDriver> threadWebDriver = new ThreadLocal<WebDriver>(){
    @Override
    protected WebDriver initialValue() {
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("permissions.default.stylesheet", 2);
        profile.setPreference("permissions.default.image", 2);
        profile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
        profile.setPreference(FirefoxProfile.ALLOWED_HOSTS_PREFERENCE, "localhost");
        WebDriver driver = new FirefoxDriver(profile);
        return driver;
    };
};

public HttpWebClient(){
    // fix for headless systems:
    // start service first, this will create an instance at system and every time you call the 
    // browser will be used
    // be sure you start the service only if there are no alive instances, that will prevent you to have 
    // multiples chromedrive instances causing it to crash
    try{
        if (service==null){
            service = new ChromeDriverService.Builder()
            .usingDriverExecutable(new File(conf.get("webdriver.chrome.driver"))) // set the chromedriver path at your system
            .usingAnyFreePort()
            .withEnvironment(ImmutableMap.of("DISPLAY", ":15"))
            .withSilent(true)
            .build();
            service.start();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

// my Configuration class is for good and easy setting, you can replace it by using values instead.
public WebDriver getDriverForPage(String url, Configuration conf) {
    WebDriver driver = null;
    DesiredCapabilities capabilities = null;
    long pageLoadWait = conf.getLong("page.load.delay", 60);

    try {
            System.setProperty("webdriver.chrome.driver", conf.get("webdriver.chrome.driver"));
            String driverType = conf.get("selenium.driver", "chrome");

        capabilities = DesiredCapabilities.chrome();
        String[] options = new String[] { "--start-maximized", "--headless" };
        capabilities.setCapability("chrome.switches", options);

                    // here is where your chromedriver will call the browser
                    // I used to call the class ChromeDriver directly, which was causing too much problems 
                    // when you have multiple calls
        driver = new RemoteWebDriver(service.getUrl(), capabilities);

        driver.manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.SECONDS);
        driver.get(url);

                    // never look back

    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.debug("Crawling URL : "+url);
            LOG.debug("Selenium WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }
    return driver;
}

public void cleanUpDriver(WebDriver driver) {
    if (driver != null) {
        try {
                            // be sure to close every driver you opened
            driver.close();
            driver.quit();
            //service.stop(); do not stop the service, bcz it is needed
            TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

}

Good luck and I hope you don't see that crash issue anymore

Please comment your success

Best regards,

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

Display / print all rows of a tibble (tbl_df)

i prefer to physically print my tables instead:

CONNECT_SERVER="https://196.168.1.1/"
CONNECT_API_KEY<-"hpphotosmartP9000:8273827"

data.frame = data.frame(1:1000, 1000:2)

connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")

install.packages('print2print')

print2print::send2printer(connectServer, apiKey, data.frame)

How do I change the root directory of an Apache server?

I had made the /var/www to be a soft link to the required directory (for example, /users/username/projects) and things were fine after that.

However, naturally, the original /var/www needs to be deleted - or renamed.

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

Assign variable in if condition statement, good practice or not?

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===. For example, when you see this:

if (value = someFunction()) {
    ...
}

you don't know if that's what they meant to do, or if they intended to write this:

if (value == someFunction()) {
    ...
}

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
    ...
}

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

Fragment Inside Fragment

AFAIK, fragments cannot hold other fragments.


UPDATE

With current versions of the Android Support package -- or native fragments on API Level 17 and higher -- you can nest fragments, by means of getChildFragmentManager(). Note that this means that you need to use the Android Support package version of fragments on API Levels 11-16, because even though there is a native version of fragments on those devices, that version does not have getChildFragmentManager().

Escape a string for a sed replace pattern

If you are just looking to replace Variable value in sed command then just remove Example:

sed -i 's/dev-/dev-$ENV/g' test to sed -i s/dev-/dev-$ENV/g test

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Enabling WiFi on Android Emulator

Wifi is not available on the emulator if you are using below of API level 25.

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

More Information: https://developer.android.com/studio/run/emulator.html#wifi

What are Bearer Tokens and token_type in OAuth 2?

token_type is a parameter in Access Token generate call to Authorization server, which essentially represents how an access_token will be generated and presented for resource access calls. You provide token_type in the access token generation call to an authorization server.

If you choose Bearer (default on most implementation), an access_token is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand, if you choose Mac and sign_type (default hmac-sha-1 on most implementation), the access token is generated and kept as secret in Key Manager as an attribute, and an encrypted secret is sent back as access_token.

Yes, you can use your own implementation of token_type, but that might not make much sense as developers will need to follow your process rather than standard implementations of OAuth.

Google Spreadsheet, Count IF contains a string

Try just =COUNTIF(A2:A51,"iPad")

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

Find size of an array in Perl

The “Perl variable types” section of the perlintro documentation contains

The special variable $#array tells you the index of the last element of an array:

print $mixed[$#mixed];       # last element, prints 1.23

You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don’t bother. As it happens, using @array where Perl expects to find a scalar value (“in scalar context”) will give you the number of elements in the array:

if (@animals < 5) { ... }

The perldata documentation also covers this in the “Scalar values” section.

If you evaluate an array in scalar context, it returns the length of the array. (Note that this is not true of lists, which return the last value, like the C comma operator, nor of built-in functions, which return whatever they feel like returning.) The following is always true:

scalar(@whatever) == $#whatever + 1;

Some programmers choose to use an explicit conversion so as to leave nothing to doubt:

$element_count = scalar(@whatever);

Earlier in the same section documents how to obtain the index of the last element of an array.

The length of an array is a scalar value. You may find the length of array @days by evaluating $#days, as in csh. However, this isn’t the length of the array; it’s the subscript of the last element, which is a different value since there is ordinarily a 0th element.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Search for all occurrences of a string in a mysql database

I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.

<?php

    // Setup the associative array for replacing the old string with new string
    $replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');

    $mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
    if( ! $mysql_link) {
        die( 'Could not connect: ' . mysql_error() );
    }

    $mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
    if(! $mysql_db ) {
        die( 'Can\'t select database: ' . mysql_error() );
    }

    // Traverse all tables
    $tables_query = 'SHOW TABLES';
    $tables_result = mysql_query( $tables_query );
    while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
        foreach( $tables_rows as $table ) {

            // Traverse all columns
            $columns_query = 'SHOW COLUMNS FROM ' . $table;
            $columns_result = mysql_query( $columns_query );
            while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {

                $column = $columns_row['Field'];
                $type = $columns_row['Type'];

                // Process only text-based columns
                if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
                    // Process all replacements for the specific column                    
                    foreach( $replace_array as $old_string => $new_string ) {
                        $replace_query = 'UPDATE ' . $table . 
                            ' SET ' .  $column . ' = REPLACE(' . $column . 
                            ', \'' . $old_string . '\', \'' . $new_string . '\')';
                        mysql_query( $replace_query );
                    }
                }
            }
        }
    }

    mysql_free_result( $columns_result );
    mysql_free_result( $tables_result );
    mysql_close( $mysql_link );

    echo 'Done!';

?>

How can I color dots in a xy scatterplot according to column value?

If you code your x axis text categories, list them in a single column, then in adjacent columns list plot points for respective variables against relevant text category code and just leave blank cells against non-relevant text category code, you can scatter plot and get the displayed result. Any questions let me know. enter image description here

Setting DEBUG = False causes 500 Error

I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'. I fixed that by locally running python manage.py collectstatic.

How to render an ASP.NET MVC view as a string?

I found a better way to render razor view page when I got error with the methods above, this solution for both web form environment and mvc environment. No controller is needed.

Here is the code example, in this example I simulated a mvc action with an async http handler:

    /// <summary>
    /// Enables processing of HTTP Web requests asynchronously by a custom HttpHandler that implements the IHttpHandler interface.
    /// </summary>
    /// <param name="context">An HttpContext object that provides references to the intrinsic server objects.</param>
    /// <returns>The task to complete the http request.</returns>
    protected override async Task ProcessRequestAsync(HttpContext context)
    {
        if (this._view == null)
        {
            this.OnError(context, new FileNotFoundException("Can not find the mvc view file.".Localize()));
            return;
        }
        object model = await this.LoadModelAsync(context);
        WebPageBase page = WebPageBase.CreateInstanceFromVirtualPath(this._view.VirtualPath);
        using (StringWriter sw = new StringWriter())
        {
            page.ExecutePageHierarchy(new WebPageContext(new HttpContextWrapper(context), page, model), sw);
            await context.Response.Output.WriteAsync(sw.GetStringBuilder().ToString());
        }
    }

Angular2 - Radio Button Binding

Here is some code I use that works with Angular 7

(Note: In the past I sometimes used info provided by the answer of Anthony Brenelière, which I appreciate. But, at least for Angular 7, this part:

 [checked]="model.options==2"

I found to be unnecessary.)

My solution here has three advantages:

  1. Consistent with the most commonly recommended solutions. So it is good for new projects.
  2. Also allows radio button code to be similar to Flex/ActionScript code. This is personally important because I am translating Flex code to Angular. Like Flex/ActionScript code it allows code to work on a radio button object to check or uncheck or find out if a radio button is checked.
  3. Unlike most solutions you will see, it is very object-based. One advantage is organization: It groups together data binding fields of a radio button, such as selected, enabled, visible, and possibly others.

Example HTML:

       <input type="radio" id="byAllRadioButton"
                 name="findByRadioButtonGroup"
                 [(ngModel)]="findByRadioButtonGroup.dataBindingValue"
                 [value]="byAllRadioButton.MY_DATA_BINDING_VALUE">         

      <input type="radio" id="byNameRadioButton"
                 name="findByRadioButtonGroup" 
                 [(ngModel)]="findByRadioButtonGroup.dataBindingValue"
                 [value]="byNameRadioButton.MY_DATA_BINDING_VALUE">

Example TypeScript:

 findByRadioButtonGroup : UIRadioButtonGroupModel
    = new UIRadioButtonGroupModel("findByRadioButtonGroup",
                                  "byAllRadioButton_value",
                                  (groupValue : any) => this.handleCriteriaRadioButtonChange(groupValue)
                                  );

  byAllRadioButton : UIRadioButtonControlModel
    = new UIRadioButtonControlModel("byAllRadioButton",
    "byAllRadioButton_value",
    this.findByRadioButtonGroup) ;

  byNameRadioButton : UIRadioButtonControlModel
    = new UIRadioButtonControlModel("byNameRadioButton",
    "byNameRadioButton_value",
    this.findByRadioButtonGroup) ;



  private handleCriteriaRadioButtonChange = (groupValue : any) : void => {

    if ( this.byAllRadioButton.selected ) {

      // Do something

    } else if ( this.byNameRadioButton.selected ) {

      // Do something

    } else {
      throw new Error("No expected radio button selected");
    }
  };

Two classes are used:

Radio Button Group Class:

export class UIRadioButtonGroupModel {


  private _dataBindingValue : any;


  constructor(private readonly debugName : string,
              private readonly initialDataBindingValue : any = null,   // Can be null or unspecified
              private readonly notifyOfChangeHandler : Function = null       // Can be null or unspecified
  ) {

    this._dataBindingValue = initialDataBindingValue;
  }


  public get dataBindingValue() : any {

    return this._dataBindingValue;
  }


  public set dataBindingValue(val : any) {

    this._dataBindingValue = val;
    if (this.notifyOfChangeHandler != null) {
      MyAngularUtils.callLater(this.notifyOfChangeHandler, this._dataBindingValue);
    }
  }



  public unselectRadioButton(valueOfOneRadioButton : any) {

    //
    // Warning: This method probably never or almost never should be needed.
    // Setting the selected radio button to unselected probably should be avoided, since
    // the result will be that no radio button will be selected.  That is
    // typically not how radio buttons work.  But we allow it here.
    // Be careful in its use.
    //

    if (valueOfOneRadioButton == this._dataBindingValue) {
      console.warn("Setting radio button group value to null");
      this.dataBindingValue = null;
    }
  }

};

Radio Button Class

export class UIRadioButtonControlModel {


  public enabled : boolean = true;
  public visible : boolean = true;


  constructor(public readonly debugName : string,
              public readonly MY_DATA_BINDING_VALUE : any,
              private readonly group : UIRadioButtonGroupModel,
              ) {

  }


  public get selected() : boolean {

    return (this.group.dataBindingValue == this.MY_DATA_BINDING_VALUE);
  }


  public set selected(doSelectMe : boolean) {

    if (doSelectMe) {
      this.group.dataBindingValue = this.MY_DATA_BINDING_VALUE;
    } else {
      this.group.unselectRadioButton(this.MY_DATA_BINDING_VALUE);
    }
  }

}

How to solve static declaration follows non-static declaration in GCC C code?

Try -Wno-traditional.

But better, add declarations for your static functions:

static void foo (void);

// ... somewhere in code
    foo ();

static void foo ()
{
    // do sth
}

filter out multiple criteria using excel vba

An option using AutoFilter


Option Explicit

Public Sub FilterOutMultiple()
    Dim ws As Worksheet, filterOut As Variant, toHide As Range

    Set ws = ActiveSheet
    If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then Exit Sub 'Empty sheet

    filterOut = Split("A B C D E F G")

    Application.ScreenUpdating = False
    With ws.UsedRange.Columns("A")
        If ws.FilterMode Then .AutoFilter
       .AutoFilter Field:=1, Criteria1:=filterOut, Operator:=xlFilterValues
        With .SpecialCells(xlCellTypeVisible)
            If .CountLarge > 1 Then Set toHide = .Cells 'Remember unwanted (A, B, and C)
        End With
       .AutoFilter
        If Not toHide Is Nothing Then
            toHide.Rows.Hidden = True                   'Hide unwanted (A, B, and C)
           .Cells(1).Rows.Hidden = False                'Unhide header
        End If
    End With
    Application.ScreenUpdating = True
End Sub

How to detect if multiple keys are pressed at once using JavaScript?

You should use the keydown event to keep track of the keys pressed, and you should use the keyup event to keep track of when the keys are released.

See this example: http://jsfiddle.net/vor0nwe/mkHsU/

(Update: I’m reproducing the code here, in case jsfiddle.net bails:) The HTML:

<ul id="log">
    <li>List of keys:</li>
</ul>

...and the Javascript (using jQuery):

var log = $('#log')[0],
    pressedKeys = [];

$(document.body).keydown(function (evt) {
    var li = pressedKeys[evt.keyCode];
    if (!li) {
        li = log.appendChild(document.createElement('li'));
        pressedKeys[evt.keyCode] = li;
    }
    $(li).text('Down: ' + evt.keyCode);
    $(li).removeClass('key-up');
});

$(document.body).keyup(function (evt) {
    var li = pressedKeys[evt.keyCode];
    if (!li) {
       li = log.appendChild(document.createElement('li'));
    }
    $(li).text('Up: ' + evt.keyCode);
    $(li).addClass('key-up');
});

In that example, I’m using an array to keep track of which keys are being pressed. In a real application, you might want to delete each element once their associated key has been released.

Note that while I've used jQuery to make things easy for myself in this example, the concept works just as well when working in 'raw' Javascript.

convert date string to mysql datetime field

$time = strtotime($oldtime);

Then use date() to put it into the correct format.

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

Java 8 NullPointerException in Collectors.toMap

According to the Stacktrace

Exception in thread "main" java.lang.NullPointerException
at java.util.HashMap.merge(HashMap.java:1216)
at java.util.stream.Collectors.lambda$toMap$148(Collectors.java:1320)
at java.util.stream.Collectors$$Lambda$5/391359742.accept(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1359)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.guice.Main.main(Main.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

When is called the map.merge

        BiConsumer<M, T> accumulator
            = (map, element) -> map.merge(keyMapper.apply(element),
                                          valueMapper.apply(element), mergeFunction);

It will do a null check as first thing

if (value == null)
    throw new NullPointerException();

I don't use Java 8 so often so i don't know if there are a better way to fix it, but fix it is a bit hard.

You could do:

Use filter to filter all NULL values, and in the Javascript code check if the server didn't send any answer for this id means that he didn't reply to it.

Something like this:

Map<Integer, Boolean> answerMap =
        answerList
                .stream()
                .filter((a) -> a.getAnswer() != null)
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

Or use peek, which is used to alter the stream element for element. Using peek you could change the answer to something more acceptable for map but it means edit your logic a bit.

Sounds like if you want to keep the current design you should avoid Collectors.toMap

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

mymap.setView(point, 11, { animation: true });        

BAD: https://jsfiddle.net/nstudor/Lgahv905/

mymap.panTo(point);
mymap.setZoom(11);

Shortest way to check for null and assign another value if not

Try this:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();

You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();

But this example only works since a possible value for this.approved_by is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.

Django Model() vs Model.objects.create()

The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:

from django.db import models

class Test(models.Model):

    added = models.DateTimeField(auto_now_add=True)

And you create a first object:

foo = Test.objects.create(pk=1)

Then you try to create an object with the same primary key:

foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")

foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

After trying many solutions, seems like the one that finally did the trick was to connect by IP. No longer file sockets getting deleted randomly.

Just update your MySQL client config (e.g. /usr/local/etc/my.cnf) with:

[client]
port = 3306
host=127.0.0.1
protocol=tcp

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

There is a change in syntax from Python 2 to Python 3. In Python 2,

print "Hello, World!" 

will work but in Python 3, use parentheses as

print("Hello, World!")

This is equivalent syntax to Scala and near to Java.

Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
    
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

How to select rows from a DataFrame based on column values

Faster results can be achieved using numpy.where.

For example, with unubtu's setup -

In [76]: df.iloc[np.where(df.A.values=='foo')]
Out[76]: 
     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing comparisons:

In [68]: %timeit df.iloc[np.where(df.A.values=='foo')]  # fastest
1000 loops, best of 3: 380 µs per loop

In [69]: %timeit df.loc[df['A'] == 'foo']
1000 loops, best of 3: 745 µs per loop

In [71]: %timeit df.loc[df['A'].isin(['foo'])]
1000 loops, best of 3: 562 µs per loop

In [72]: %timeit df[df.A=='foo']
1000 loops, best of 3: 796 µs per loop

In [74]: %timeit df.query('(A=="foo")')  # slowest
1000 loops, best of 3: 1.71 ms per loop

AngularJS : ng-model binding not updating when changed with jQuery

Just use:

$('#selectedDueDate').val(dateText).trigger('input');

instead of:

$('#selectedDueDate').val(dateText);

Pandas: Looking up the list of sheets in an excel file

I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Adding the following block of code in web.config solves my problem

 <system.net>
    <defaultProxy enabled="false" >
    </defaultProxy>
  </system.net>

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

JMS Topic vs Queues

Queue is JMS managed object used for holding messages waiting for subscribers to consume. When all subscribers consumed the message , message will be removed from queue.

Topic is that all subscribers to a topic receive the same message when the message is published.

Running windows shell commands with python

Refactoring of @srini-beerge's answer which gets the output and the return code

import subprocess
def run_win_cmd(cmd):
    result = []
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        result.append(line)
    errcode = process.returncode
    for line in result:
        print(line)
    if errcode is not None:
        raise Exception('cmd %s failed, see above for details', cmd)

How can I echo the whole content of a .html file in PHP?

If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include or require. Simply do:

echo file_get_contents("/path/to/file.html");

Can't find how to use HttpContent

Just leaving the way using Microsoft.AspNet.WebApi.Client here.

Example:

var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class RegisterAction {


    public String execute() {


         RegisterAction mailBean = new RegisterAction();

           String subject="Your username & password ";

           String message="Hi," + username;
          message+="\n \n Your username is " + email;
          message+="\n \n Your password is " + password;
          message+="\n \n Please login to the web site with your username and password.";
          message+="\n \n Thanks";
          message+="\n \n \n Regards";

           //Getting  FROM_MAIL

           String[] recipients = new String[1];
            recipients[0] = new String();
            recipients[0] = customer.getEmail();

           try{
          mailBean.sendMail(recipients,subject,message);

          return "success";
          }catch(Exception e){
           System.out.println("Error in sending mail:"+e);
          }

        return "failure";
    }

    public void sendMail( String recipients[ ], String subject, String message)
             throws MessagingException
              {
                boolean debug = false;

                 //Set the host smtp address

                 Properties props = new Properties();
                 props.put("mail.smtp.host", "smtp.gmail.com");
                 props.put("mail.smtp.starttls.enable", true);
                 props.put("mail.smtp.auth", true);

                // create some properties and get the default Session

                Session session = Session.getDefaultInstance(props, new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "[email protected]", "5373273437543");// Specify the Username and the PassWord
                    }

                });
                session.setDebug(debug);


                // create a message
                Message msg = new MimeMessage(session);


                InternetAddress[] addressTo = new InternetAddress[recipients.length];
                for (int i = 0; i < recipients.length; i++)
                {
                  addressTo[i] = new InternetAddress(recipients[i]);
                }

                msg.setRecipients(Message.RecipientType.TO, addressTo);

                // Optional : You can also set your custom headers  in the Email if you Want
                //msg.addHeader("MyHeaderName", "myHeaderValue");

                // Setting the Subject and Content Type
                msg.setSubject(subject);
                msg.setContent(message, "text/plain");

                //send message
                Transport.send(msg);

                System.out.println("Message Sent Successfully");
              }

}

How to do a recursive find/replace of a string with awk or sed?

find /home/www/ -type f -exec perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +

find /home/www/ -type f will list all files in /home/www/ (and its subdirectories). The "-exec" flag tells find to run the following command on each file found.

perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +

is the command run on the files (many at a time). The {} gets replaced by file names. The + at the end of the command tells find to build one command for many filenames.

Per the find man page: "The command line is built in much the same way that xargs builds its command lines."

Thus it's possible to achieve your goal (and handle filenames containing spaces) without using xargs -0, or -print0.

What causes a Python segmentation fault?

Google search found me this article, and I did not see the following "personal solution" discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but "re-installing" pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

How to uninstall Jenkins?

On Mac; these two below commands completely remove Jenkins from your machine. just open your Terminal and execute them:

  1. '/Library/Application Support/Jenkins/Uninstall.command' and
  2. sudo rm -rf /var/root/.jenkins ~/.jenkins

Thanks

Remove non-utf8 characters from string

So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.

The pseudo-python would be:

newstring = ''
cont = 0
for each ch in string:
  if cont:
    if (ch >> 6) != 2: # high 2 bits are 10
      # do whatever, e.g. skip it, or skip whole point, or?
    else:
      # acceptable continuation of multi-octlet char
      newstring += ch
    cont -= 1
  else:
    if (ch >> 7): # high bit set?
      c = (ch << 1) # strip the high bit marker
      while (c & 1): # while the high bit indicates another octlet
        c <<= 1
        cont += 1
        if cont > 4:
           # more than 4 octels not allowed; cope with error
      if !cont:
        # illegal, do something sensible
      newstring += ch # or whatever
if cont:
  # last utf-8 was not terminated, cope

This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.

How do you overcome the svn 'out of date' error?

After trying all the obvious things, and some of the other suggestions here, with no luck whatsoever, a Google search led to this link (link not working anymore) - Subversion says: Your file or directory is probably out-of-date

In a nutshell, the trick is to go to the .svn directory (in the directory that contains the offending file), and delete the "all-wcprops" file.

Worked for me when nothing else did.

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Alternative to iFrames with HTML5

You can use object and embed, like so:

<object data="http://www.web-source.net" width="600" height="400">
    <embed src="http://www.web-source.net" width="600" height="400"> </embed>
    Error: Embedded data could not be displayed.
</object>

Which isn't new, but still works. I'm not sure if it has the same functionality though.

how to destroy bootstrap modal window completely?

This worked for me.

$('.modal-backdrop').removeClass('in');
$('#myDiv').removeClass('in');

The dialog and backdrop went away, but they came back the next time I clicked the button.

Integrating the ZXing library directly into my Android application

UPDATE! - SOLVED + GUIDE

I've managed to figure it out :) And down below you can read step-by-step guide so it hopefully can help others with the same problem as I had ;)

  1. Install Apache Ant - (See this YouTube video for config help)
  2. Download the ZXing source from ZXing homepage and extract it
  3. With the use of Windows Commandline (Run->CMD) navigate to the root directory of the downloaded zxing src.
  4. In the commandline window - Type ant -f core/build.xml press enter and let Apache work it's magic [having issues?]
  5. Enter Eclipse -> new Android Project, based on the android folder in the directory you just extracted
  6. Right-click project folder -> Properties -> Java Build Path -> Library -> Add External JARs...
  7. Navigate to the newly extracted folder and open the core directory and select core.jar ... hit enter!

Now you just have to correct a few errors in the translations and the AndroidManifest.xml file :) Now you can happily compile, and you will now have a working standalone barcode scanner app, based on the ZXing source ;)

Happy coding guys - I hope it can help others :)

How can I get sin, cos, and tan to use degrees instead of radians?

I created my own little lazy Math-Object for degree (MathD), hope it helps:

//helper
/**
 * converts degree to radians
 * @param degree
 * @returns {number}
 */
var toRadians = function (degree) {
    return degree * (Math.PI / 180);
};

/**
 * Converts radian to degree
 * @param radians
 * @returns {number}
 */
var toDegree = function (radians) {
    return radians * (180 / Math.PI);
}

/**
 * Rounds a number mathematical correct to the number of decimals
 * @param number
 * @param decimals (optional, default: 5)
 * @returns {number}
 */
var roundNumber = function(number, decimals) {
    decimals = decimals || 5;
    return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
//the object
var MathD = {
    sin: function(number){
        return roundNumber(Math.sin(toRadians(number)));
    },
    cos: function(number){
        return roundNumber(Math.cos(toRadians(number)));
    },
    tan: function(number){
        return roundNumber(Math.tan(toRadians(number)));
    },
    asin: function(number){
        return roundNumber(toDegree(Math.asin(number)));
    },
    acos: function(number){
       return roundNumber(toDegree(Math.acos(number)));
   },
   atan: function(number){
       return roundNumber(toDegree(Math.atan(number)));
   }
};

Do I need <class> elements in persistence.xml?

In Java SE environment, by specification you have to specify all classes as you have done:

A list of all named managed persistence classes must be specified in Java SE environments to insure portability

and

If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element should be used. The exclude-unlisted-classes element is not intended for use in Java SE environments.

(JSR-000220 6.2.1.6)

In Java EE environments, you do not have to do this as the provider scans for annotations for you.

Unofficially, you can try to set <exclude-unlisted-classes>false</exclude-unlisted-classes> in your persistence.xml. This parameter defaults to false in EE and truein SE. Both EclipseLink and Toplink supports this as far I can tell. But you should not rely on it working in SE, according to spec, as stated above.

You can TRY the following (may or may not work in SE-environments):

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
     <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
    </properties>
</persistence-unit>

Prevent typing non-numeric in input type number

Try it:

document.querySelector("input").addEventListener("keyup", function () {
   this.value = this.value.replace(/\D/, "")
});

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Twitter Bootstrap Datepicker within modal window

I think is better to change the logical function in the plugin. Around row 552 i change this:

            var zIndex = parseInt(this.element.parents().filter(function(){
                return $(this).css('z-index') !== 'auto';
            }).first().css('z-index'))+10;

into this:

            var zIndex = parseInt(this.element.parents().filter(function(){
                return $(this).css('z-index') !== 'auto';
            }).first().css('z-index')) + 10 * 1000; //think is enought

How do you write multiline strings in Go?

According to the language specification you can use a raw string literal, where the string is delimited by backticks instead of double quotes.

`line 1
line 2
line 3`

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

SQL Server: UPDATE a table by using ORDER BY

No.

Not a documented 100% supported way. There is an approach sometimes used for calculating running totals called "quirky update" that suggests that it might update in order of clustered index if certain conditions are met but as far as I know this relies completely on empirical observation rather than any guarantee.

But what version of SQL Server are you on? If SQL2005+ you might be able to do something with row_number and a CTE (You can update the CTE)

With cte As
(
SELECT id,Number,
ROW_NUMBER() OVER (ORDER BY id DESC) AS RN
FROM Test
)
UPDATE cte SET Number=RN

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

How to mark a build unstable in Jenkins when running shell scripts

In my job script, I have the following statements (this job only runs on the Jenkins master):

# This is the condition test I use to set the build status as UNSTABLE
if [ ${PERCENTAGE} -gt 80 -a ${PERCENTAGE} -lt 90 ]; then
  echo WARNING: disc usage percentage above 80%

  # Download the Jenkins CLI JAR:
  curl -o jenkins-cli.jar ${JENKINS_URL}/jnlpJars/jenkins-cli.jar

  # Set build status to unstable
  java -jar jenkins-cli.jar -s ${JENKINS_URL}/ set-build-result unstable

fi

You can see this and a lot more information about setting build statuses on the Jenkins wiki: https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI

MongoError: connect ECONNREFUSED 127.0.0.1:27017

For windows - just go to Mongodb folder (ex : C:\ProgramFiles\MongoDB\Server\3.4\bin) and open cmd in the folder and type "mongod.exe --dbpath c:\data\db"

if c:\data\db folder doesn't exist then create it by yourself and run above command again.

All should work fine by now.))

How to run an EXE file in PowerShell with parameters with spaces and quotes

You can run exe files in powershell different ways. For instance if you want to run unrar.exe and extract a .rar file you can simply write in powershell this:

$extract_path = "C:\Program Files\Containing folder";
$rar_to_extract = "C:\Path_to_arch\file.rar"; #(or.exe if its a big file)  
C:\Path_here\Unrar.exe x -o+ -c- $rar_to_extract $extract_path;

But sometimes, this doesn't work so you must use the & parameter as shown above: For instance, with vboxmanage.exe (a tool to manage virtualbox virtual machines) you must call the paramterers outside of the string like this, without quotes:

> $vmname = "misae_unrtes_1234123"; #(name too long, we want to change this)
> & 'C:\Program Files\Oracle\VirtualBox\VBoxManage.exe' modifyvm $vmname --name UBUNTU;

If you want to call simply a winrar archived file as .exe files, you can also unzip it with the invoke-command cmdlet and a Silent parameter /S (Its going to extract itself in the same folder than where it has been compressed).

> Invoke-Command -ScriptBlock { C:\Your-path\archivefile.exe /S };

So there are several ways to run .exe files with arguments in powershell.

Sometimes, one must find a workaround to make it work properly, which can require some further effort and pain :) depending on the way the .exe has been compiled or made bi its creators.

String length in bytes in JavaScript

Actually, I figured out what's wrong. For the code to work the page <head> should have this tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Or, as suggested in comments, if server sends HTTP Content-Encoding header, it should work as well.

Then results from different browsers are consistent.

Here is an example:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>mini string length test</title>
</head>
<body>

<script type="text/javascript">
document.write('<div style="font-size:100px">' 
    + (unescape(encodeURIComponent("???! Naïve?")).length) + '</div>'
  );
</script>
</body>
</html>

Note: I suspect that specifying any (accurate) encoding would fix the encoding problem. It is just a coincidence that I need UTF-8.

Eclipse CDT: no rule to make target all

"all" is a default setting, even though Behaviour->Build (Incremental build) tab has no variable. I solved as

  1. Go to Project Properties > C/C++ Build > Behaviour Tab.
  2. Leave Build (Incremental Build) Checked.
  3. Enter "test" in the text box next to Build (Incremental Build).
  4. Build Project. You will see error message.
  5. Go back to Build (Incremental Build) and delete "test".
  6. Build Project.

Hadoop cluster setup - java.net.ConnectException: Connection refused

From the netstat output you can see the process is listening on address 127.0.0.1

tcp        0      0 127.0.0.1:9000          0.0.0.0:*  ...

from the exception message you can see that it tries to connect to address 127.0.1.1

java.net.ConnectException: Call From marta-komputer/127.0.1.1 to localhost:9000 failed ...

further in the exception it's mentionend

For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

on this page you find

Check that there isn't an entry for your hostname mapped to 127.0.0.1 or 127.0.1.1 in /etc/hosts (Ubuntu is notorious for this)

so the conclusion is to remove this line in your /etc/hosts

127.0.1.1       marta-komputer

Propagate all arguments in a bash shell script

For bash and other Bourne-like shells:

java com.myserver.Program "$@"

WRONGTYPE Operation against a key holding the wrong kind of value php

This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

Trying to handle "back" navigation button action in iOS

This is Objective-C version of dadachi's Answer :

Objective-C

- (void)didMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        NSLog(@"Back Pressed");
    }
}

How do I copy a string to the clipboard?

The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something)

import subprocess
import os

def cp2clip(clist):

    #create a temporary file
    fi=open("thisTextfileShouldNotExist.txt","w")

    #write in the text file the way you want your data to be
    for m in clist:
        fi.write(m+"\n")

    #close the file
    fi.close()

    #send "clip < file" to the shell
    cmd="clip < thisTextfileShouldNotExist.txt"
    w = subprocess.check_call(cmd,shell=True)

    #delete the temporary text file
    os.remove("thisTextfileShouldNotExist.txt")

    return w

works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated...

example:

>>>cp2clip(["ET","phone","home"])
>>>0

Ctrl+V in any text editor :

ET
phone
home

How to "flatten" a multi-dimensional array to simple one in PHP?

Given multi-dimensional array and converting it into one-dimensional, can be done by unsetting all values which are having arrays and saving them into first dimension, for example:

function _flatten_array($arr) {
  while ($arr) {
    list($key, $value) = each($arr); 
    is_array($value) ? $arr = $value : $out[$key] = $value;
    unset($arr[$key]);
  }
  return (array)$out;
}

jQuery get specific option tag text

$(this).children(":selected").text()

Can I have two JavaScript onclick events in one element?

There is no need to have two functions within one element, you need just one that calls the other two!

HTML

<a href="#" onclick="my_func()" >click</a>

JavaScript

function my_func() {
    my_func_1();
    my_func_2();
}

Angular 2 - Setting selected value on dropdown list

This works for me.

<select formControlName="preferredBankAccountId" class="form-control" value="">
    <option value="">Please select</option>    
    <option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>

Not sure this is valid or not, correct me if it's wrong.
Correct me if this should not be like this.

Send POST request with JSON data using Volley

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

Storing JSON in database vs. having a new column for each key

Basically, the first model you are using is called as document-based storage. You should have a look at popular NoSQL document-based database like MongoDB and CouchDB. Basically, in document based db's, you store data in json files and then you can query on these json files.

The Second model is the popular relational database structure.

If you want to use relational database like MySql then i would suggest you to only use second model. There is no point in using MySql and storing data as in the first model.

To answer your second question, there is no way to query name like 'foo' if you use first model.

What is the function of the push / pop instructions used on registers in x86 assembly?

pushing a value (not necessarily stored in a register) means writing it to the stack.

popping means restoring whatever is on top of the stack into a register. Those are basic instructions:

push 0xdeadbeef      ; push a value to the stack
pop eax              ; eax is now 0xdeadbeef

; swap contents of registers
push eax
mov eax, ebx
pop ebx

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

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/

Can I add extension methods to an existing static class?

You can't add static methods to a type. You can only add (pseudo-)instance methods to an instance of a type.

The point of the this modifier is to tell the C# compiler to pass the instance on the left-side of the . as the first parameter of the static/extension method.

In the case of adding static methods to a type, there is no instance to pass for the first parameter.

What does .class mean in Java?

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()

The .class Syntax

If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

See: docs.oracle.com about class

jQuery: Check if button is clicked

try something like :

var focusout = false;

$("#Button1").click(function () {
    if (focusout == true) {
        focusout = false;
        return;
    }
    else {
        GetInfo();
    }
});

$("#Text1").focusout(function () {
    focusout = true;
    GetInfo();
});

Rails ActiveRecord date between

I ran this code to see if the checked answer worked, and had to try swapping around the dates to get it right. This worked--

Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721

If you're thinking the output should have been 36, consider this, Sir, how many days is 3 days to 3 people?

How to parse a date?

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Bootstrap Carousel Full Screen

Update Bootstrap 4

Bootstrap 4 has utility classes that make it easier to create a full screen carousel. For example, use the min-vh-100 class on the carousel-item content...

<div class="carousel slide" data-ride="carousel">
      <div class="carousel-inner bg-info" role="listbox">
            <div class="carousel-item active">
                <div class="d-flex align-items-center justify-content-center min-vh-100">
                    <h1 class="display-1">ONE</h1>
                </div>
            </div>
      </div>
</div>

Full screen carousel demo

This works to make the carousel items full screen, but carousel items that contain images or videos that have a specific size & aspect ratio require further consideration.

Since the viewport h/w ratio is likely to be different than the image or video h/w ratio, usually background images or object-fit are commonly used to size images and videos to "full screen". For videos, use the Bootstrap responsive embed classes as needed for the video ratio (21:9, 19:9, etc...).

Full screen videos demo

Also see: https://stackoverflow.com/a/58765043/171456


Original answer (Bootstrap 3)

Make sure the img inside the carousel item is set to height and width 100%. You also have to make sure the carousel and any of the .item containers (html,body) are 100%...

html,body{height:100%;}
.carousel,.item,.active{height:100%;}
.carousel-inner{height:100%;}

Boostrap 3 Full Screen Carousel Demo

Here's an example for Bootstrap 3.x: http://www.codeply.com/go/2tVXo3mAtV

How to get Month Name from Calendar?

You will get this way also.

  String getMonthForInt(int num) {
        String month = "wrong";
        DateFormatSymbols dfs = new DateFormatSymbols();
        String[] months = dfs.getMonths();
        if (num >= 0 && num <= 11 ) {
            month = months[num];
        }
        return month;
    }

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

Regex remove all special characters except numbers?

Use the global flag:

var name = name.replace(/[^a-zA-Z ]/g, "");
                                    ^

If you don't want to remove numbers, add it to the class:

var name = name.replace(/[^a-zA-Z0-9 ]/g, "");

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

git with development, staging and production branches

one of the best things about git is that you can change the work flow that works best for you.. I do use http://nvie.com/posts/a-successful-git-branching-model/ most of the time but you can use any workflow that fits your needs

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}


// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

VBA test if cell is in a range

Determine if a cell is within a range using VBA in Microsoft Excel:

From the linked site (maintaining credit to original submitter):

VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()
    If InRange(ActiveCell, Range("A1:D100")) Then
        ' code to handle that the active cell is within the right range
        MsgBox "Active Cell In Range!"
    Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Active Cell NOT In Range!"
    End If
End Sub

Better/Faster to Loop through set or list?

While a set may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set vs list because you're converting from a list to a set in set_loop, and then you're creating the list you'll be looping through in list_loop. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:

ids_list = range(1000000)
ids_set = set(ids)
def f(x):
    for i in x:
         pass

%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop

How do I extract Month and Year in a MySQL date and compare them?

There should also be a YEAR().

As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)

Or you could use multiple comparisons (i.e. years first, then months).

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

T-SQL stored procedure that accepts multiple Id values

One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.

This way, you're only parsing once.

It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)

This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.

IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
BEGIN
    DROP TABLE #tmpDept
END

SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')

CREATE TABLE #tmpDept (DeptID INT)
DECLARE @DeptID INT
IF IsNumeric(@DepartmentIDs)=1
BEGIN
    SET @DeptID=@DepartmentIDs
    INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
ELSE
BEGIN
        WHILE CHARINDEX(',',@DepartmentIDs)>0
        BEGIN
            SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
            SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
            INSERT INTO #tmpDept (DeptID) SELECT @DeptID
        END
END

This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.

So if you did something like:

SELECT Dept.Name 
FROM Departments 
JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
ORDER BY Dept.Name

You would see the names of all of the department IDs that you passed in...

Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P

-- Kevin Fairchild

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

How to Display blob (.pdf) in an AngularJS app

First of all you need to set the responseType to arraybuffer. This is required if you want to create a blob of your data. See Sending_and_Receiving_Binary_Data. So your code will look like this:

$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});

The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:

$scope.content = $sce.trustAsResourceUrl(fileURL);

Do not forget to inject the $sce service.

If this is all done you can now embed your pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

Does Index of Array Exist

The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

public ItemContext GetThisElement(int row,
    int col)
{
    ItemContext ctx = null;
    if (rgItemCtx[row, col] != null)
    {
        try
        {
          ctx = rgItemCtx[row, col];
        }
        catch (SystemException sex)
        {
          ctx = null;
          // perhaps do something with sex properties
        }
    }

    return (ctx);
}

Why is IoC / DI not common in Python?

Actually, it is quite easy to write sufficiently clean and compact code with DI (I wonder, will it be/stay pythonic then, but anyway :) ), for example I actually perefer this way of coding:

def polite(name_str):
    return "dear " + name_str

def rude(name_str):
    return name_str + ", you, moron"

def greet(name_str, call=polite):
    print "Hello, " + call(name_str) + "!"

_

>>greet("Peter")
Hello, dear Peter!
>>greet("Jack", rude)
Hello, Jack, you, moron!

Yes, this can be viewed as just a simple form of parameterizing functions/classes, but it does its work. So, maybe Python's default-included batteries are enough here too.

P.S. I have also posted a larger example of this naive approach at Dynamically evaluating simple boolean logic in Python.

jQuery: Handle fallback for failed AJAX Request

I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.

var promise = $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000
  }).then(function( data, textStatus, jqXHR ) {
    alert('request successful');
  }, function( jqXHR, textStatus, errorThrown ) {
    alert('request failed');
});

//also access the success and fail using variable
promise.then(successFunction, failFunction);

How can I generate an apk that can run without server with react-native?

Run this command:

react-native run-android --variant=release

Note that --variant=release is only available if you've set up signing with cd android && ./gradlew assembleRelease.

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

How to fluently build JSON in Java?

The reference implementation includes a fluent interface. Check out JSONWriter and its toString-implementing subclass JSONStringer

Git - how delete file from remote repository

  1. If you want to push a deleted file to remote

git add 'deleted file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote and locally

git rm 'file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote only

git rm --cached 'file name'

git commit -m'message'

git push -u origin branch

Can we have multiple <tbody> in same <table>?

I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.

HTML

<div>
        <table class="table table-hover table-condensed table-striped">
            <thead>
                <tr>
                    <th>Store ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Cost</th>
                    <th>Sales</th>
                    <th>Revenue</th>
                    <th>Employees</th>
                    <th>Employees H-sum</th>
                </tr>
            </thead>
            <tbody data-ng-repeat="storedata in storeDataModel.storedata">
                <tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
                    <td>{{storedata.store.storeId}}</td>
                    <td>{{storedata.store.storeName}}</td>
                    <td>{{storedata.store.storeAddress}}</td>
                    <td>{{storedata.store.storeCity}}</td>
                    <td>{{storedata.data.costTotal}}</td>
                    <td>{{storedata.data.salesTotal}}</td>
                    <td>{{storedata.data.revenueTotal}}</td>
                    <td>{{storedata.data.averageEmployees}}</td>
                    <td>{{storedata.data.averageEmployeesHours}}</td>
                </tr>
                <tr data-ng-show="dayDataCollapse[$index]">
                    <td colspan="2">&nbsp;</td>
                    <td colspan="7">
                        <div>
                            <div class="pull-right">
                                <table class="table table-hover table-condensed table-striped">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Date [YYYY-MM-dd]</th>
                                            <th>Cost</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Employees</th>
                                            <th>Employees H-sum</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
                                            <td class="pullright">
                                                <button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
                                                </button>
                                            </td>
                                            <td>{{dayData.date}}</td>
                                            <td>{{dayData.cost}}</td>
                                            <td>{{dayData.sales}}</td>
                                            <td>{{dayData.revenue}}</td>
                                            <td>{{dayData.employees}}</td>
                                            <td>{{dayData.employeesHoursSum}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

jquery change class name

So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:

Let's start with this HTML:

<body>
  <div>
    <select id="test">
      <option>Bob</option>
      <option>Sam</option>
      <option>Sue</option>
      <option>Jen</option>
    </select>
  </div>

  <table id="theTable">
    <tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
    <tr><td>Sue</td><td>Jen</td></tr>
  </table>
</body>

Some very basic CSS:

?#theTable td {
    border:1px solid #555;
}
.activeCell {
    background-color:#F00;
}

And set up a jQuery event:

function highlightCell(useVal){
  $("#theTable td").removeClass("activeCell")
      .filter(":contains('"+useVal+"')").addClass("activeCell");
}

$(document).ready(function(){
    $("#test").change(function(e){highlightCell($(this).val())});
});

Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying

.filter("#"+useVal)

and make sure to add the ids appropriately. Hope this helps!

What is the equivalent to getch() & getche() in Linux?

There is a getch() function in the ncurses library. You can get it by installing the ncurses-dev package.

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

How to make picturebox transparent?

One way to do this is by changing the parent of the overlapping picture box to the PictureBox over which it is lapping. Since the Visual Studio designer doesn't allow you to add a PictureBox to a PictureBox, this will have to be done in your code (Form1.cs) and within the Intializing function:

public Form1()
{
    InitializeComponent();
    pictureBox7.Controls.Add(pictureBox8);
    pictureBox8.Location = new Point(0, 0);
    pictureBox8.BackColor = Color.Transparent;
}

Just change the picture box names to what ever you need. This should return:

enter image description here

global variable for all controller and views

View::share('site_settings', $site_settings);

Add to

app->Providers->AppServiceProvider file boot method

it's global variable.

How can I match a string with a regex in Bash?

Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:

[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}

Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I was able to fix this by downgrading RubyGems to 1.5.3, since it happens with RubyGems 1.6.0+ and Rails < 2.3.11:

gem update --system 1.5.3

If you had previously downgraded to an even earlier version and want to update to 1.5.3, you might get the following when trying to run that:

Updating RubyGems
ERROR:  While executing gem ... (RuntimeError)
    No gem names are allowed with the --system option

If you get that error, then update, so that it lets you specify the version, and then downgrade again:

gem update --system
gem update --system 1.5.3

Constructor of an abstract class in C#

Far as I know we can't instantiate an abstract class

There's your error right there. Of course you can instantiate an abstract class.

abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();

There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.

Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.

Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I'm not sure why the way you did it doesn't work, but I usually do it with the spyOn function. Something like this:

describe('Testing remote call returning promise', function() {
  var myService;

  beforeEach(module('app.myService'));

  beforeEach(inject( function(_myService_, myOtherService, $q){
    myService = _myService_;
    spyOn(myOtherService, "makeRemoteCallReturningPromise").and.callFake(function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;
    });
  }

  it('can do remote call', inject(function() {
    myService.makeRemoteCall()
      .then(function() {
        console.log('Success');
      });    
  }));

Also remember that you will need to make a $digest call for the then function to be called. See the Testing section of the $q documentation.

------EDIT------

After looking closer at what you're doing, I think I see the problem in your code. In the beforeEach, you're setting myOtherServiceMock to a whole new object. The $provide will never see this reference. You just need to update the existing reference:

beforeEach(inject( function(_myService_, $q){
    myService = _myService_;
    myOtherServiceMock.makeRemoteCallReturningPromise = function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;   
    };
  }

Initialising mock objects - MockIto

For the mocks initialization, using the runner or the MockitoAnnotations.initMocks are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner :

JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.


The first solution (with the MockitoAnnotations.initMocks) could be used when you have already configured a specific runner (SpringJUnit4ClassRunner for example) on your test case.

The second solution (with the MockitoJUnitRunner) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of automatic validation of framework usage (described by @David Wallace in this answer).

Both solutions allows to share the mocks (and spies) between the test methods. Coupled with the @InjectMocks, they allow to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example:

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock(name = "database") private ArticleDatabase dbMock;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @InjectMocks private ArticleManager manager;

    @Test public void shouldDoSomething() {
        manager.initiateArticle();
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        manager.finishArticle();
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: The code is minimal

Cons: Black magic. IMO it is mainly due to the @InjectMocks annotation. With this annotation "you loose the pain of code" (see the great comments of @Brice)


The third solution is to create your mock on each test method. It allow as explained by @mlk in its answer to have "self contained test".

public class ArticleManagerTest {

    @Test public void shouldDoSomething() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (BDD...)

Cons: there is more boilerplate code. (The mocks creation)


My recommandation is a compromise. Use the @Mock annotation with the @RunWith(MockitoJUnitRunner.class), but do not use the @InjectMocks :

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock private ArticleDatabase database;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @Test public void shouldDoSomething() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then 
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (How my ArticleManager is instantiated). No boilerplate code.

Cons: The test is not self contained, less pain of code

SSH to Vagrant box in Windows?

Another solution here but only for the virtual box of windows 10 to test explorer. ssh user: IEUser ssh pass:Passw0rd!