Programs & Examples On #Paraffin

What's the difference between ".equals" and "=="?

(1) == can be be applied for both primitives and object types, but equals() method can be applied for only object types.

(2) == cannot be overridden for content comparison, but equals method can be overridden for content comparison(ex; String class, wrapper classes, collection classes).

(3) == gives incomparable types error when try to apply for heterogeneous types , where as equals method returns false.

How can I mimic the bottom sheet from the Maps app?

I released a library based on my answer below.

It mimics the Shortcuts application overlay. See this article for details.

The main component of the library is the OverlayContainerViewController. It defines an area where a view controller can be dragged up and down, hiding or revealing the content underneath it.

let contentController = MapsViewController()
let overlayController = SearchViewController()

let containerController = OverlayContainerViewController()
containerController.delegate = self
containerController.viewControllers = [
    contentController,
    overlayController
]

window?.rootViewController = containerController

Implement OverlayContainerViewControllerDelegate to specify the number of notches wished:

enum OverlayNotch: Int, CaseIterable {
    case minimum, medium, maximum
}

func numberOfNotches(in containerViewController: OverlayContainerViewController) -> Int {
    return OverlayNotch.allCases.count
}

func overlayContainerViewController(_ containerViewController: OverlayContainerViewController,
                                    heightForNotchAt index: Int,
                                    availableSpace: CGFloat) -> CGFloat {
    switch OverlayNotch.allCases[index] {
        case .maximum:
            return availableSpace * 3 / 4
        case .medium:
            return availableSpace / 2
        case .minimum:
            return availableSpace * 1 / 4
    }
}

SwiftUI (12/29/20)

A SwiftUI version of the library is now available.

Color.red.dynamicOverlay(Color.green)

Previous answer

I think there is a significant point that is not treated in the suggested solutions: the transition between the scroll and the translation.

Maps transition between the scroll and the translation

In Maps, as you may have noticed, when the tableView reaches contentOffset.y == 0, the bottom sheet either slides up or goes down.

The point is tricky because we can not simply enable/disable the scroll when our pan gesture begins the translation. It would stop the scroll until a new touch begins. This is the case in most of the proposed solutions here.

Here is my try to implement this motion.

Starting point: Maps App

To start our investigation, let's visualize the view hierarchy of Maps (start Maps on a simulator and select Debug > Attach to process by PID or Name > Maps in Xcode 9).

Maps debug view hierarchy

It doesn't tell how the motion works, but it helped me to understand the logic of it. You can play with the lldb and the view hierarchy debugger.

Our view controller stacks

Let's create a basic version of the Maps ViewController architecture.

We start with a BackgroundViewController (our map view):

class BackgroundViewController: UIViewController {
    override func loadView() {
        view = MKMapView()
    }
}

We put the tableView in a dedicated UIViewController:

class OverlayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    lazy var tableView = UITableView()

    override func loadView() {
        view = tableView
        tableView.dataSource = self
        tableView.delegate = self
    }

    [...]
}

Now, we need a VC to embed the overlay and manage its translation. To simplify the problem, we consider that it can translate the overlay from one static point OverlayPosition.maximum to another OverlayPosition.minimum.

For now it only has one public method to animate the position change and it has a transparent view:

enum OverlayPosition {
    case maximum, minimum
}

class OverlayContainerViewController: UIViewController {

    let overlayViewController: OverlayViewController
    var translatedViewHeightContraint = ...

    override func loadView() {
        view = UIView()
    }

    func moveOverlay(to position: OverlayPosition) {
        [...]
    }
}

Finally we need a ViewController to embed the all:

class StackViewController: UIViewController {

    private var viewControllers: [UIViewController]

    override func viewDidLoad() {
        super.viewDidLoad()
        viewControllers.forEach { gz_addChild($0, in: view) }
    }
}

In our AppDelegate, our startup sequence looks like:

let overlay = OverlayViewController()
let containerViewController = OverlayContainerViewController(overlayViewController: overlay)
let backgroundViewController = BackgroundViewController()
window?.rootViewController = StackViewController(viewControllers: [backgroundViewController, containerViewController])

The difficulty behind the overlay translation

Now, how to translate our overlay?

Most of the proposed solutions use a dedicated pan gesture recognizer, but we actually already have one : the pan gesture of the table view. Moreover, we need to keep the scroll and the translation synchronised and the UIScrollViewDelegate has all the events we need!

A naive implementation would use a second pan Gesture and try to reset the contentOffset of the table view when the translation occurs:

func panGestureAction(_ recognizer: UIPanGestureRecognizer) {
    if isTranslating {
        tableView.contentOffset = .zero
    }
}

But it does not work. The tableView updates its contentOffset when its own pan gesture recognizer action triggers or when its displayLink callback is called. There is no chance that our recognizer triggers right after those to successfully override the contentOffset. Our only chance is either to take part of the layout phase (by overriding layoutSubviews of the scroll view calls at each frame of the scroll view) or to respond to the didScroll method of the delegate called each time the contentOffset is modified. Let's try this one.

The translation Implementation

We add a delegate to our OverlayVC to dispatch the scrollview's events to our translation handler, the OverlayContainerViewController :

protocol OverlayViewControllerDelegate: class {
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    func scrollViewDidStopScrolling(_ scrollView: UIScrollView)
}

class OverlayViewController: UIViewController {

    [...]

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        delegate?.scrollViewDidScroll(scrollView)
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        delegate?.scrollViewDidStopScrolling(scrollView)
    }
}

In our container, we keep track of the translation using a enum:

enum OverlayInFlightPosition {
    case minimum
    case maximum
    case progressing
}

The current position calculation looks like :

private var overlayInFlightPosition: OverlayInFlightPosition {
    let height = translatedViewHeightContraint.constant
    if height == maximumHeight {
        return .maximum
    } else if height == minimumHeight {
        return .minimum
    } else {
        return .progressing
    }
}

We need 3 methods to handle the translation:

The first one tells us if we need to start the translation.

private func shouldTranslateView(following scrollView: UIScrollView) -> Bool {
    guard scrollView.isTracking else { return false }
    let offset = scrollView.contentOffset.y
    switch overlayInFlightPosition {
    case .maximum:
        return offset < 0
    case .minimum:
        return offset > 0
    case .progressing:
        return true
    }
}

The second one performs the translation. It uses the translation(in:) method of the scrollView's pan gesture.

private func translateView(following scrollView: UIScrollView) {
    scrollView.contentOffset = .zero
    let translation = translatedViewTargetHeight - scrollView.panGestureRecognizer.translation(in: view).y
    translatedViewHeightContraint.constant = max(
        Constant.minimumHeight,
        min(translation, Constant.maximumHeight)
    )
}

The third one animates the end of the translation when the user releases its finger. We calculate the position using the velocity & the current position of the view.

private func animateTranslationEnd() {
    let position: OverlayPosition =  // ... calculation based on the current overlay position & velocity
    moveOverlay(to: position)
}

Our overlay's delegate implementation simply looks like :

class OverlayContainerViewController: UIViewController {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard shouldTranslateView(following: scrollView) else { return }
        translateView(following: scrollView)
    }

    func scrollViewDidStopScrolling(_ scrollView: UIScrollView) {
        // prevent scroll animation when the translation animation ends
        scrollView.isEnabled = false
        scrollView.isEnabled = true
        animateTranslationEnd()
    }
}

Final problem: dispatching the overlay container's touches

The translation is now pretty efficient. But there is still a final problem: the touches are not delivered to our background view. They are all intercepted by the overlay container's view. We can not set isUserInteractionEnabled to false because it would also disable the interaction in our table view. The solution is the one used massively in the Maps app, PassThroughView:

class PassThroughView: UIView {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let view = super.hitTest(point, with: event)
        if view == self {
            return nil
        }
        return view
    }
}

It removes itself from the responder chain.

In OverlayContainerViewController:

override func loadView() {
    view = PassThroughView()
}

Result

Here is the result:

Result

You can find the code here.

Please if you see any bugs, let me know ! Note that your implementation can of course use a second pan gesture, specially if you add a header in your overlay.

Update 23/08/18

We can replace scrollViewDidEndDragging with willEndScrollingWithVelocity rather than enabling/disabling the scroll when the user ends dragging:

func scrollView(_ scrollView: UIScrollView,
                willEndScrollingWithVelocity velocity: CGPoint,
                targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    switch overlayInFlightPosition {
    case .maximum:
        break
    case .minimum, .progressing:
        targetContentOffset.pointee = .zero
    }
    animateTranslationEnd(following: scrollView)
}

We can use a spring animation and allow user interaction while animating to make the motion flow better:

func moveOverlay(to position: OverlayPosition,
                 duration: TimeInterval,
                 velocity: CGPoint) {
    overlayPosition = position
    translatedViewHeightContraint.constant = translatedViewTargetHeight
    UIView.animate(
        withDuration: duration,
        delay: 0,
        usingSpringWithDamping: velocity.y == 0 ? 1 : 0.6,
        initialSpringVelocity: abs(velocity.y),
        options: [.allowUserInteraction],
        animations: {
            self.view.layoutIfNeeded()
    }, completion: nil)
}

How to use jQuery to call an ASP.NET web service?

SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use

It is certified for SharePoint 2007

The list of supported operations for Lists.asmx could be found here

Example

In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:

<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">

$(document).ready(function() {
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Announcements",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
        $("#tasksUL").append(liHtml);
      });
    }
  });
});
</script>
<ul id="tasksUL"/>

Taking multiple inputs from user in python

# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( ) 
#for printing 
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)

#for multiple inputs    
#using list, map
#split seperates values by ( )single space in this case

x=list(map(int,input("enter the numbers: ").split( )))

#we will get list of our desired elements 

print("print list: ",x)

hope you got your answer :)

"Stack overflow in line 0" on Internet Explorer

Also having smartNavigation="true" causes this"

ESLint - "window" is not defined. How to allow global variables in package.json

Add .eslintrc in the project root.

{
  "globals": {
    "document": true,
    "foo": true,
    "window": true
  }
}

Official reasons for "Software caused connection abort: socket write error"

I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.

Hope this helps.
And if still facing issue than brief your problem here in details.

Error in installation a R package

In my case, the installation of nlme package is in trouble:

mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme' 
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme': 
Permission denied

Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:

sudo R
install.packages('nlme')
q()

Get current AUTO_INCREMENT value for any table

you can also use this if you know the name of the primary key

SELECT
    MAX(primary_key_name) + 1
FROM
    TABLE_NAME

Purpose of "%matplotlib inline"

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

Twitter Bootstrap Button Text Word Wrap

You can add these style's and it works just as expected.

.btn {
    white-space:normal !important; 
    word-wrap: break-word; 
    word-break: normal;
}

Open existing file, append a single line

We can use

public StreamWriter(string path, bool append);

while opening the file

string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);

First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true

Writing to the file can be done with:

writer.Write(string)

or

writer.WriteLine(string)

Sample Code

private void WriteAndAppend()
{
            string Path = Application.StartupPath + "\\notes.txt";
            FileInfo fi = new FileInfo(Path);
            StreamWriter SW;
            StreamReader SR;
            if (fi.Exists)
            {
                SR = new StreamReader(Path);
                string Line = "";
                while (!SR.EndOfStream) // Till the last line
                {
                    Line = SR.ReadLine();
                }
                SR.Close();
                int x = 0;
                if (Line.Trim().Length <= 0)
                {
                    x = 0;
                }
                else
                {
                    x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
                }
                x++;
                SW = new StreamWriter(Path, true);
                SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine(x.ToString() + "." + textBox1.Text);

            }
            else
            {
                SW = new StreamWriter(Path);
                SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine("1." + textBox1.Text);
            }
            SW.Flush();
            SW.Close();
        }

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

How to downgrade python from 3.7 to 3.6

create a virtual environment, install then switch to python 3.6.5

$ conda create -n tensorflow python=3.7
$ conda activate tensorflow
$ conda install python=3.6.5
$ pip install tensorflow

activate the environment when you would want to use tensorflow

What is the correct way to free memory in C#

The .NET garbage collector takes care of all this for you.

It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

jQuery prevent change for select

Implement custom readonly like eventHandler

<select id='country' data-changeable=false>
  <option selected value="INDIA">India</option>
  <option value="USA">United States</option>
  <option value="UK">United Kingdom</option>
</select>

<script>
    var lastSelected = $("#country option:selected");

    $("#country").on("change", function() {
       if(!$(this).data(changeable)) {
            lastSelected.attr("selected", true);              
       }        
    });

    $("#country").on("click", function() {
       lastSelected = $("#country option:selected");
    });
</script>

Demo : https://jsfiddle.net/0mvajuay/8/

Valid characters of a hostname?

A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.

This is provided in http://support.microsoft.com/kb/149044

Set focus on textbox in WPF

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>

When to use the different log levels

My two cents about FATAL and TRACE error log levels.

ERROR is when some FAULT (exception) occur.

FATAL is actually DOUBLE FAULT: when exception occur while handling exception.

It's easy to understand for web service.

  1. Request come. Event is logged as INFO
  2. System detects low disk space. Event is logged as WARN
  3. Some function is called to handle the request. While processing division by zero occur. Event is logged as ERROR
  4. Web service's exception handler is called to handle division by zero. Web service/framework is going to send email, but it can not because mailing service is offline now. This second exception can not be handled normally, because Web service's exception handler can not process exception.
  5. Different exception handler called. Event is logged as FATAL

TRACE is when we can trace function entry/exit. This is not about logging, because this message can be generated by some debugger and your code has not call to log at all. So messages that are not from your application are marked like TRACE level. For example your run your application by with strace

So generally in your program you do DEBUG, INFO and WARN logging. And only if you are writing some web service/framework you will use FATAL. And when you are debugging application you will get TRACE logging from this type of software.

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

Guid.NewGuid() vs. new Guid()

Guid.NewGuid(), as it creates GUIDs as intended.

Guid.NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

new Guid() merely creates an empty GUID (all zeros, I think).

I guess they had to make the constructor public as Guid is a struct.

Mongoose, update values in array of objects

Below is an example of how to update the value in the array of objects more dynamically.

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})

Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilters and positional operator like so:

"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value} 

"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]

More usage can be found in the official docs.

javascript window.location in new tab

with jQuery its even easier and works on Chrome as well

$('#your-button').on('click', function(){
       $('<a href="https://www.some-page.com" target="blank"></a>')[0].click();    
})

Python data structure sort list alphabetically

You can use built-in sorted function.

print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])

How can I check if a string contains ANY letters from the alphabet?

You can also do this in addition

import re
string='24234ww'
val = re.search('[a-zA-Z]+',string) 
val[0].isalpha() # returns True if the variable is an alphabet
print(val[0]) # this will print the first instance of the matching value

Also note that if variable val returns None. That means the search did not find a match

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

byte[] iso88591Data = theString.getBytes("ISO-8859-1");

Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.

What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes() method as shown above).

jQuery has deprecated synchronous XMLHTTPRequest

No one of the previous answers (which all are correct) was suited to my situation: I don't use the async parameter in jQuery.ajax() and I don't include a script tag as part of the content that was being returned like:

<div> 
     SOME CONTENT HERE
</div>
<script src="/scripts/script.js"></script> 

My situation is that I am calling two AJAX requests consecutively with the aim to update two divs at the same time:

function f1() {
     $.ajax(...); // XMLHTTP request to url_1 and append result to div_1
}

function f2() {
     $.ajax(...); // XMLHTTP request to url_2 and append result to div_2
}

function anchor_f1(){
$('a.anchor1').click(function(){
     f1();
})
}

function anchor_f2(){
$('a.anchor2').click(function(){
     f2();
});
}

// the listener of anchor 3 the source of problem
function anchor_problem(){
$('a.anchor3').click(function(){
     f1();
     f2();
});
}

anchor_f1();
anchor_f2();
anchor_problem();

When I click on a.anchor3, it raises the warning flag.I resolved the issue by replacing f2 invoking by click() function:

function anchor_problem(){
$('a.anchor_problem').click(function(){
     f1();
     $('a.anchor_f2').click();
});
}

Dealing with "Xerces hell" in Java/Maven?

You should debug first, to help identify your level of XML hell. In my opinion, the first step is to add

-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl

to the command line. If that works, then start excluding libraries. If not, then add

-Djaxp.debug=1

to the command-line.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

git rm - fatal: pathspec did not match any files

Step 1

Add the file name(s) to your .gitignore file.

Step 2

git filter-branch --force --index-filter \
    'git rm -r --cached --ignore-unmatch YOURFILE' \
    --prune-empty --tag-name-filter cat -- --all

Step 3

git push -f origin branch

A big thank you to @mu.

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

How do I upgrade PHP in Mac OS X?

to upgrade php7 to latest stable version brew upgrade php7 or for php5.X to latest stable version

brew upgrade php56

use brew list to check installed version

How can I get device ID for Admob

The accepted answers will work if you are only testing on the Emulator or on a few devices, but if you are testing on a plethora of devices, you may need some means of prorammatically adding the running device's device ID.

The following code will make the current running device into an adview test device programmatically

...
    if(YourApplication.debugEnabled(this)) //debug flag from somewhere that you set
    {

        String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
        mAdRequest.addTestDevice(deviceId);
        boolean isTestDevice = mAdRequest.isTestDevice(this);

        Log.v(TAG, "is Admob Test Device ? "+deviceId+" "+isTestDevice); //to confirm it worked
    }

You need to use the md5 of the Android ID, and it needs to be upper case. Here is the md5 code I used

public static final String md5(final String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            String h = Integer.toHexString(0xFF & messageDigest[i]);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        Logger.logStackTrace(TAG,e);
    }
    return "";
}

EDIT: Apparently that MD5 method isnt perfect, and it was suggested to try https://stackoverflow.com/a/21333739/2662474 I no longer need this feature so I havent tested. Good luck!

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

I found that not only did I have to restart Visual Studio Code but the node server process as well before I could get a good compile.

Ruby optional parameters

Recently I found a way around this. I wanted to create a method in the array class with an optional parameter, to keep or discard elements in the array.

The way I simulated this was by passing an array as the parameter, and then checking if the value at that index was nil or not.

class Array
  def ascii_to_text(params)
    param_len = params.length
    if param_len > 3 or param_len < 2 then raise "Invalid number of arguments #{param_len} for 2 || 3." end
    bottom  = params[0]
    top     = params[1]
    keep    = params[2]
    if keep.nil? == false
      if keep == 1
        self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
      else
        raise "Invalid option #{keep} at argument position 3 in #{p params}, must be 1 or nil"
      end
    else
      self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
    end
  end
end

Trying out our class method with different parameters:

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126, 1]) # Convert all ASCII values of 32-126 to their chr value otherwise keep it the same (That's what the optional 1 is for)

output: ["1", "2", "a", "b", "c"]

Okay, cool that works as planned. Now let's check and see what happens if we don't pass in the the third parameter option (1) in the array.

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126]) # Convert all ASCII values of 32-126 to their chr value else remove it (1 isn't a parameter option)

output: ["a", "b", "c"]

As you can see, the third option in the array has been removed, thus initiating a different section in the method and removing all ASCII values that are not in our range (32-126)

Alternatively, we could had issued the value as nil in the parameters. Which would look similar to the following code block:

def ascii_to_text(top, bottom, keep = nil)
  if keep.nil?
    self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
  else
    self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
end

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Simple proof that GUID is not unique

Any two GUIDs are very likely unique (not equal).

See this SO entry, and from Wikipedia

While each generated GUID is not guaranteed to be unique, the total number of unique keys (2^128 or 3.4×10^38) is so large that the probability of the same number being generated twice is very small. For example, consider the observable universe, which contains about 5×10^22 stars; every star could then have 6.8×10^15 universally unique GUIDs.

So probably you have to wait for many more billion of years, and hope that you hit one before the universe as we know it comes to an end.

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

How to add a border to a widget in Flutter?

You can add the TextField as a child to a Container that has a BoxDecoration with border property:

enter image description here

new Container(
  margin: const EdgeInsets.all(15.0),
  padding: const EdgeInsets.all(3.0),
  decoration: BoxDecoration(
    border: Border.all(color: Colors.blueAccent)
  ),
  child: Text("My Awesome Border"),
)

How do you make a LinearLayout scrollable?

you need to use the following attribute and enclose it within the linear layout

<LinearLayout ...>
<scrollView ...> 

</scrollView>
</LinearLayout>

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

Just Change the property based on your machine and all have done :-)

Project---> Properties--->Build--->Target Framework---> X64

or

Project---> Properties--->Build--->Target Framework---> X86

Best practice for instantiating a new Android Fragment

You can use smth like this:

val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, YourFragment::class.java.name)

because this answer now is Deprecated

How to source virtualenv activate in a Bash script

Sourcing runs shell commands in your current shell. When you source inside of a script like you are doing above, you are affecting the environment for that script, but when the script exits, the environment changes are undone, as they've effectively gone out of scope.

If your intent is to run shell commands in the virtualenv, you can do that in your script after sourcing the activate script. If your intent is to interact with a shell inside the virtualenv, then you can spawn a sub-shell inside your script which would inherit the environment.

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

Kill all processes for a given user

Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

pkill -9 -u `id -u username`

Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

Why did Servlet.service() for servlet jsp throw this exception?

The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.

It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>


Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.

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

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

In Python, how do I iterate over a dictionary in sorted key order?

sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.

I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:

return iter(sorted(dict.iteritems()))

of course you will be getting back tuples now because sorted turned your dict into a list of tuples

ex: say your dict was: {'a':1,'c':3,'b':2} sorted turns it into a list:

[('a',1),('b',2),('c',3)]

so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.

How do I exit the Vim editor?

I got Vim by installing a Git client on Windows. :q wouldn't exit Vim for me. :exit did however...

SQL Server database backup restore on lower version

you can use BCP in and out for small tables.

BCP OUT command:-

BCP "SELECT *  FROM [Dinesh].[dbo].[Invoices]" QUERYOUT C:\av\Invoices1.txt -S MC0XENTC -T -c -r c:\error.csv

BCP IN command:- Create table structure for Invoicescopy1.

BCP [Dinesh].[dbo].[Invoicescopy1] IN C:\av\Invoices.txt -S MC0XENTC -T -c

Windows.history.back() + location.reload() jquery

You can't do window.history.back(); and location.reload(); in the same function.

window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.

location.reload() has to be called on the page you redirect to when using window.history.back().

I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.

Difference between "include" and "require" in php

The difference between include() and require() arises when the file being included cannot be found: include() will release a warning (E_WARNING) and the script will continue, whereas require() will release a fatal error (E_COMPILE_ERROR) and terminate the script. If the file being included is critical to the rest of the script running correctly then you need to use require().

For more details : Difference between Include and Require in PHP

How to get line count of a large file cheaply in Python?

Why not read the first 100 and the last 100 lines and estimate the average line length, then divide the total file size through that numbers? If you don't need a exact value this could work.

In Spring MVC, how can I set the mime type header when using @ResponseBody

You may not be able to do it with @ResponseBody, but something like this should work:

package xxx;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class FooBar {
  @RequestMapping(value="foo/bar", method = RequestMethod.GET)
  public void fooBar(HttpServletResponse response) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(myService.getJson().getBytes());
    response.setContentType("application/json");
    response.setContentLength(out.size());
    response.getOutputStream().write(out.toByteArray());
    response.getOutputStream().flush();
  }
}

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

Make git automatically remove trailing whitespace before committing

For Sublime Text users.

Set following properly in you Setting-User configuration.

"trim_trailing_white_space_on_save": true

Generating Fibonacci Sequence

Here's a simple function to iterate the Fibonacci sequence into an array using arguments in the for function more than the body of the loop:

fib = function(numMax){
    for(var fibArray = [0,1], i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
        x=i+j;
        fibArray.push(x);
    }
    console.log(fibArray);
}

fib(10)

[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

Is there an easy way to reload css without reloading the page?

In a simple manner you can use rel="preload" instead of rel="stylesheet" .

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">

Regex (grep) for multi-line search needed

Without the need to install the grep variant pcregrep, you can do multiline search with grep.

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

Explanation:

-P activate perl-regexp for grep (a powerful extension of regular expressions)

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

-o print only matching. Because we're using -z, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.

In regexp:

(?s) activate PCRE_DOTALL, which means that . finds any character or newline

\N find anything except newline, even with PCRE_DOTALL activated

.*? find . in non-greedy mode, that is, stops as soon as possible.

^ find start of line

\1 backreference to the first group (\s*). This is a try to find the same indentation of method.

As you can imagine, this search prints the main method in a C (*.c) source file.

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Adding Permissions in AndroidManifest.xml in Android Studio?

Put these two line in your AndroidMainfest

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

Is there a format code shortcut for Visual Studio?

Yes, you can use the two-chord hotkey (Ctrl+K, Ctrl+F if you're using the General profile) to format your selection.

Other formatting options are under menu EditAdvanced, and like all Visual Studio commands, you can set your own hotkey via menu ToolsOptionsEnvironmentKeyboard (the format selection command is called Edit.FormatSelection).

Formatting doesn't do anything with blank lines, but it will indent your code according to some rules that are usually slightly off from what you probably want.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

How to get week number of the month from the date in sql server 2008

Logic here works as well 4.3 weeks in every month. Take that from the DATEPART(WEEK) on every month but January. Just another way of looking at things. This would also account for months where there is a 5th week

DECLARE @date VARCHAR(10)
SET @date = '7/27/2019'

SELECT CEILING(DATEPART(WEEK,@date)-((DATEPART(MONTH,@date)-1)*4.3333)) 'Week of Month'

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

How to install Jdk in centos

There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:

OpenJDK Runtime Environment (Java SE 6)

yum install java-1.6.0-openjdk

OpenJDK Runtime Environment (Java SE 7)

yum install java-1.7.0-openjdk

OpenJDK Development Environment (Java SE 7)

yum install java-1.7.0-openjdk-devel

OpenJDK Development Environment (Java SE 6)

yum install java-1.6.0-openjdk-devel

Update for Java 8

In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:

OpenJDK Runtime Environment (Java SE 8)

yum install java-1.8.0-openjdk

OpenJDK Development Environment (Java SE 8)

yum install java-1.8.0-openjdk-devel

There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:

OpenJDK Runtime Environment - Headless (Java SE 8)

yum install java-1.8.0-openjdk-headless

Node.js client for a socket.io server

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

ASP.NET MVC on IIS 7.5

Another possible solution, if you move around your global.asax, make sure the markup points to the correct MvcApplication class. Hopefully this will save someone in future.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Though this question already has sufficient answers, I thought somebody would want to know why this flag works in this peculiar manner, This is what I found in Android documentation

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent.

If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().


So, Either,
1. Change the launchMode of the Activity A to something else from standard (ie. singleTask or something). Then your flag FLAG_ACTIVITY_CLEAR_TOP will not restart your Activity A.

or,

2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP as your flag. Then it will work the way you desire.

Is it valid to have a html form inside another html form?

rather use a custom javascript-method inside the action attribute of the form!

eg

<html>
    <head>
        <script language="javascript" type="text/javascript">
        var input1 = null;
        var input2 = null;
        function InitInputs() {
            if (input1 == null) {
                input1 = document.getElementById("input1");
            }
            if (input2 == null) {
                input2 = document.getElementById("input2");
            }

            if (input1 == null) {
                alert("input1 missing");
            }
            if (input2 == null) {
                alert("input2 missing");
            }
        }
        function myMethod1() {
            InitInputs();
            alert(input1.value + " " + input2.value);
        }
        function myMethod2() {
            InitInputs();
            alert(input1.value);
        }
        </script>
    </head>
    <body>
        <form action="javascript:myMethod1();">
            <input id="input1" type="text" />
            <input id="input2" type="text" />
            <input type="button" onclick="myMethod2()" value="myMethod2"/>
            <input type="submit" value="myMethod1" />
        </form>
    </body>
</html>

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You had selected the time format wrong

<?php 
date_default_timezone_set('GMT');

echo date("Y-m-d,h:m:s");
?>

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

I got the problem like you so I decide to write small tool to help me out. Please check ExcelDiff_Tools. It comes with several key points:

  • Support xls, xlsx, xlsm.
  • With formula cell. It will compare both formula and value.
  • I try to make UI look like standard diff text viewer with : modified, deleted, added, unchanged status. Please take a look with image below for example: enter image description here

How to read line by line or a whole text file at once?

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.

difference between new String[]{} and new String[] in java

TL;DR

  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.

Replies

1. String[] array= new String[]{}; what is the use of { } here ?

It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}. Just make up your mind and use one of those - Java thinks.

help me i am confused

Examples

String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

Eric Lippert recently had a very in-depth series of blog posts about this: "Every Binary Tree There Is" and "Every Tree There Is" (plus some more after that).

In answer to your specific question, he says:

The number of binary trees with n nodes is given by the Catalan numbers, which have many interesting properties. The nth Catalan number is determined by the formula (2n)! / (n+1)!n!, which grows exponentially.

How to make sure docker's time syncs with that of the host?

If you're using docker-machine, the virtual machines can drift. To update the clock on the virtual machine without restarting run:

docker-machine ssh <machine-name|default>
sudo ntpclient -s -h pool.ntp.org

This will update the clock on the virtual machine using NTP and then all the containers launched will have the correct date.

using batch echo with special characters

another method:

@echo off

for /f "useback delims=" %%_ in (%0) do (
  if "%%_"=="___ATAD___" set $=
  if defined $ echo(%%_
  if "%%_"=="___DATA___" set $=1
)
pause
goto :eof

___DATA___
<?xml version="1.0" encoding="utf-8" ?>
 <root>
   <data id="1">
      hello world
   </data>
 </root>
___ATAD___


rem # 
rem # 

What is this date format? 2011-08-12T20:17:46.384Z

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

C/C++ switch case with string

You could create a hashtable. The keys can be the string and the value can be and integer. Setup your integers for the values as constants and then you can check for them with the switch.

Print string to text file

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

RedirectToAction with parameter

It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

So the url would be:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

These can then be referenced by your controller:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }

Change font size of UISegmentedControl

XCode 8.1, Swift 3

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        UISegmentedControl.appearance().setTitleTextAttributes(NSDictionary(objects: [UIFont.systemFont(ofSize: 24.0)], 
        forKeys: [NSFontAttributeName as NSCopying]) as? [AnyHashable : Any], 
        for: UIControlState.normal)
    }
}

just change the number value (ofSize: 24.0)

Preview

JavaScript for handling Tab Key press

Use TAB & TAB+SHIFT in a Specified container or element

Source

we will handle TAB & TAB+SHIFT key listeners first

        $(document).ready(function() {
            lastIndex = 0;
            $(document).keydown(function(e) {
                if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
                if (e.keyCode == 9) {
                    if (e.shiftKey) {
                        //Focus previous input
                        if (thisTab == startIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
                            return false;
                        }
                    } else {
                        if (thisTab == lastIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
                            return false;
                        }
                    }
                }
            });
            var setTabindexLimit = function(x, fancyID) {
                console.log(x);
                startIndex = 1;
                lastIndex = x;
                tabLimitInID = fancyID;
                $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
            }
            /*Taking last tabindex=10 */
            setTabindexLimit(10, "limitTablJolly");
        });

In HTML define tabindex

        <div class="limitTablJolly">
            <a tabindex=1>link</a>    
             <a tabindex=2>link</a>    
             <a tabindex=3>link</a>    
             <a tabindex=4>link</a>    
             <a tabindex=5>link</a>    
             <a tabindex=6>link</a>    
             <a tabindex=7>link</a>    
             <a tabindex=8>link</a>    
             <a tabindex=9>link</a>    
             <a tabindex=10>link</a>   
        </div>

Why is my xlabel cut off in my matplotlib plot?

An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.

Method 1

Set this in your matplotlibrc file

figure.autolayout : True

See here for more information on customizing the matplotlibrc file: http://matplotlib.org/users/customizing.html

Method 2

Update the rcParams during runtime like this

from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

The advantage of using this approach is that your code will produce the same graphs on differently-configured machines.

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

Change the Right Margin of a View Programmatically?

Use This function to set all Type of margins

      public void setViewMargins(Context con, ViewGroup.LayoutParams params,      
       int left, int top , int right, int bottom, View view) {

    final float scale = con.getResources().getDisplayMetrics().density;
    // convert the DP into pixel
    int pixel_left = (int) (left * scale + 0.5f);
    int pixel_top = (int) (top * scale + 0.5f);
    int pixel_right = (int) (right * scale + 0.5f);
    int pixel_bottom = (int) (bottom * scale + 0.5f);

    ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
    s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);

    view.setLayoutParams(params);
}

Java String import

Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.

The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.

Sort a List of Object in VB.NET

try..

Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry

mylist = sortedList.ToList

How to select an item in a ListView programmatically?

I know this is an old question, but I think this is the definitive answer.

listViewRamos.Items[i].Focused = true;
listViewRamos.Items[i].Selected = true;
listViewRemos.Items[i].EnsureVisible();

If there is a chance the control does not have the focus but you want to force the focus to the control, then you can add the following line.

listViewRamos.Select();

Why Microsoft didn't just add a SelectItem() method that does all this for you is beyond me.

Using Mockito with multiple calls to the same method with the same arguments

doReturn( value1, value2, value3 ).when( method-call )

Java says FileNotFoundException but file exists

Apart from all the other answers mentioned here, you can do one thing which worked for me.

If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.

It worked for me, hope it helps someone :)

Commit only part of a file in Git

If you're using VSCode, then you're in luck. Select the range that you want to stage, then use Git: Stage Selected Ranges to stage them, and commit if you want.

I recorded a gif to demonstrate what I meant:

enter image description here

How can I get name of element with jQuery?

$('someSelectorForTheElement').attr('name');

How to remove border of drop down list : CSS

This solution seems not working for me.

select {
    border: 0px;
    outline: 0px;
}

But you may set select border to the background color of the container and it will work.

jquery - Check for file extension before uploading

<!DOCTYPE html>
    <html>
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script>
         jQuery(document).ready(function(){
               jQuery('.form-file input').each(function () {
                     $this = jQuery(this);
                          $this.on('change', function() {
                               var fsize = $this[0].files[0].size,
                                   ftype = $this[0].files[0].type,
                                   fname = $this[0].files[0].name,
                                   fextension = fname.substring(fname.lastIndexOf('.')+1);
                                   validExtensions = ["jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","pptx","txt","zip","rar","gzip"];

                                if ($.inArray(fextension, validExtensions) == -1){
                                    alert("This type of files are not allowed!");
                                    this.value = "";
                                    return false;
                                }else{
                                    if(fsize > 3145728){/*1048576-1MB(You can change the size as you want)*/
                                        alert("File size too large! Please upload less than 3MB");
                                        this.value = "";
                                        return false;
                                    }
                                    return true;
                               }

                         });
             });
       });
    </script>
    </head>

<body>
    <form>
          <div class="form-file">
               <label for="file-upload" class="from-label">File Upload</label>
               <input class="form-control" name="file-upload" id="file-upload" type="file">
          </div>
    </form>
</body>

</html>

Here is complete answer for checking file size and file extension. This used default file input field and jQuery library. Working example : https://jsfiddle.net/9pfjq6zr/2/

Return a `struct` from a function in C

You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language. The only problem with struct b = a is that you didn't provide a complete type. struct MyObj b = a will work just fine. You can pass structures to functions as well - a structure is exactly the same as any built-in type for purposes of parameter passing, return values, and assignment.

Here's a simple demonstration program that does all three - passes a structure as a parameter, returns a structure from a function, and uses structures in assignment statements:

#include <stdio.h>

struct a {
   int i;
};

struct a f(struct a x)
{
   struct a r = x;
   return r;
}

int main(void)
{
   struct a x = { 12 };
   struct a y = f(x);
   printf("%d\n", y.i);
   return 0;
}

The next example is pretty much exactly the same, but uses the built-in int type for demonstration purposes. The two programs have the same behaviour with respect to pass-by-value for parameter passing, assignment, etc.:

#include <stdio.h>

int f(int x) 
{
  int r = x;
  return r;
}

int main(void)
{
  int x = 12;
  int y = f(x);
  printf("%d\n", y);
  return 0;
}

Register DLL file on Windows Server 2008 R2

This is what has to occur.

You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\

Then in the Run dialog, type this in: C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll

and you will get the message:

DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.

Radio Buttons "Checked" Attribute Not Working

Hey I was also facing similar problem, in an ajax generated page.. I took generated source using Webdeveloper pluggin in FF, and checked all the inputs in the form and found out that there was another checkbox inside a hidden div(display:none) with same ID, Once I changed the id of second checkbox, it started working.. You can also try that.. and let me know the result.. cheers

Inner join with 3 tables in mysql

Almost correctly.. Look at the joins, you are referring the wrong fields

SELECT student.firstname,
       student.lastname,
       exam.name,
       exam.date,
       grade.grade
  FROM grade
 INNER JOIN student ON student.studentId = grade.fk_studentId
 INNER JOIN exam ON exam.examId = grade.fk_examId
 ORDER BY exam.date

How to center a component in Material-UI and make it responsive?

With other answers used, xs='auto' did a trick for me.

<Grid container
    alignItems='center'
    justify='center'
    style={{ minHeight: "100vh" }}>

    <Grid item xs='auto'>
        <GoogleLogin
            clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
            buttonText="Log in with Google"
            onSuccess={this.handleLogin}
            onFailure={this.handleLogin}
             cookiePolicy={'single_host_origin'}
         />
    </Grid>
</Grid>

How do I set a value in CKEditor with Javascript?

As now to day CKEditor 4+ launched we have to use it.ekeditor 4 setData documentation

CKEDITOR.instances['editor1'].setData(value);

Where editor1 is textarea Id.

Old methods such as insertHtml('html data') and insertText('text data') also works fine.

and to get data use

var ckdata =  CKEDITOR.instances['editor1'].getData();
var data = CKEDITOR.instances.editor1.getData();

Ckedtor 4 documentation

To the power of in C?

you can use pow(base, exponent) from #include <math.h>

or create your own:

int myPow(int x,int n)
{
    int i; /* Variable used in loop counter */
    int number = 1;

    for (i = 0; i < n; ++i)
        number *= x;

    return(number);
}

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

spring PropertyPlaceholderConfigurer and context:property-placeholder

Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>

Somehow "classpath:xxx" is not picking the file.

CSS: fixed to bottom and centered

You should use a sticky footer solution such as this one :

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

There are others like this;

* {margin:0;padding:0;} 

/* must declare 0 margins on everything, also for main layout components use padding, not 
vertical margins (top and bottom) to add spacing, else those margins get added to total height 
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */

html, body, #wrap {height: 100%;}

body > #wrap {height: auto; min-height: 100%;}

#main {padding-bottom: 150px;}  /* must be same height as the footer */

#footer {position: relative;
    margin-top: -150px; /* negative value of footer height */
    height: 150px;
    clear:both;} 

/* CLEAR FIX*/
.clearfix:after {content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}

with the html:

<div id="wrap">

    <div id="main" class="clearfix">

    </div>

</div>

<div id="footer">

</div>

memcpy() vs memmove()

Just because memcpy doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.

How to set the env variable for PHP?

You need to add the PHP directory to your path. On the command line (e.g. in a batch file), it would look like this:

SET PATH=%PATH%;C:\your\wamp\path\php

if in doubt, it's the directory containing the php.exe.

You can also pre-set the path in Windows' control panel. See here on how to do this in Windows 7 for example.

Be aware that if you call the PHP executable from an arbitrary directory, that directory will be the working directory. You may need to adjust your scripts so they use the proper directories for their file operations (if there are any).

How can I read numeric strings in Excel cells as string (not numbers)?

I don't think we had this class back when you asked the question, but today there is an easy answer.

What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.

For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.

Also, note that lots of people suggest doing cell.setCellType(Cell.CELL_TYPE_STRING), but the Apache POI JavaDocs quite clearly state that you shouldn't do this! Doing the setCellType call will loose formatting, as the javadocs explain the only way to convert to a String with formatting remaining is to use the DataFormatter class.

how to add css class to html generic control div?

dynDiv.Attributes["class"] = "myCssClass";

Docker Error bind: address already in use

This helped me:

docker-compose down  # Stop container on current dir if there is a docker-compose.yml
docker rm -fv $(docker ps -aq)  # Remove all containers
sudo lsof -i -P -n | grep <port number>  # List who's using the port

and then: kill -9 <process id> (macOS) or sudo kill <process id> (Linux).

Source: comment by user Rub21.

Python json.loads shows ValueError: Extra data

You can just read from a file, jsonifying each line as you go:

tweets = []
for line in open('tweets.json', 'r'):
    tweets.append(json.loads(line))

This avoids storing intermediate python objects. As long as your write one full tweet per append() call, this should work.

Why is __dirname not defined in node REPL?

If you are using Node.js modules, __dirname and __filename don't exist.

From the Node.js documentation:

No require, exports, module.exports, __filename, __dirname

These CommonJS variables are not available in ES modules.

require can be imported into an ES module using module.createRequire().

Equivalents of __filename and __dirname can be created inside of each file via import.meta.url:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname

Login failed for user 'DOMAIN\MACHINENAME$'

I spent a few hours trying to fix the issue and I finally got it - the SQL Server Browser was "Stopped". The fix is to change it to "Automatic" mode:

If it is disabled, go to Control Panel->Administrative Tools->Services, and look for the SQL Server Agent. Right-click, and select "Properties." From the "Startup Type" dropdown, change from "Disabled" to "Automatic".

quote from here

Get a list of dates between two dates using a function

A few ideas:

If you need the list dates in order to loop through them, you could have a Start Date and Day Count parameters and do a while loop whilst creating the date and using it?

Use C# CLR Stored Procedures and write the code in C#

Do this outside the database in code

How do I copy the contents of a String to the clipboard in C#?

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

How to install numpy on windows using pip install?

As of March 2016, pip install numpy works on Windows without a Fortran compiler. See here.

pip install scipy still tries to use a compiler.

July 2018: mojoken reports pip install scipy working on Windows without a Fortran compiler.

This project references NuGet package(s) that are missing on this computer

If you are using TFS

Remove the NuGet.exe and NuGet.targets files from the solution's .nuget folder. Make sure the files themselves are also removed from the solution workspace. Retain the NuGet.Config file to continue to bypass adding packages to source control.

Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets file. Open the project file(s) in the editor of your choice and remove the following settings:

<RestorePackages>true</RestorePackages>  
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />  
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">  
    <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

If you are not using TFS

Remove the .nuget folder from your solution. Make sure the folder itself is also removed from the solution workspace.

Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets file. Open the project file(s) in the editor of your choice and remove the following settings:

<RestorePackages>true</RestorePackages>  
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />  
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">  
    <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

Reference: Migrating MSBuild-Integrated solutions to use Automatic Package Restore

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

There are a lot of correct/same answers, but for future references:

Same stands for Tomcat 7. Be aware that updating only your used frameworks' versions (as proposed in other similar questions) isn't enough.

You also have to update Tomcat plugin's version. What worked for me, using Java 7, was upgrading to version 2.2 of tomcat7-maven-plugin (= Tomcat 7.0.47).

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

Repeat string to certain length

from itertools import cycle, islice
def srepeat(string, n):
   return ''.join(islice(cycle(string), n))

Disable Buttons in jQuery Mobile

  $(document).ready(function () {
        // Set button disabled

        $('#save_info').button("disable");


        $(".name").bind("change", function (event, ui) {

            var edit = $("#your_name").val();
            var edit_surname = $("#your_surname").val();
            console.log(edit);

            if (edit != ''&& edit_surname!='') {
                //name.addClass('hightlight');
                $('#save_info').button("enable");
                console.log("enable");

                return false;
            } else {

                $('#save_info').button("disable");

                console.log("disable");
            }

        });


    <ul data-role="listview" data-inset="true" data-split-icon="gear" data-split-theme="d">
        <li>
            <input type="text" name="your_name" id="your_name" class="name" value="" placeholder="Frist Name" /></li>
        <li>
            <input type="text" name="your_surname" id="your_surname"  class="name" value="" placeholder="Last Name" /></li>
        <li>
            <button data-icon="info" href="" data-role="submit" data-inline="true" id="save_info">
            Save</button>

This one work for me you might need to workout the logic, of disable -enable

How to update PATH variable permanently from Windows command line?

This script http://www.autohotkey.com/board/topic/63210-modify-system-path-gui/

includes all the necessary Windows API calls which can be refactored for your needs. It is actually an AutoHotkey GUI to change the System PATH easily. Needs to be run as an Administrator.

C++ - Decimal to binary converting

here a simple converter by using std::string as container. it allows a negative value.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

Ternary operator (?:) in Bash

ternary operator ? : is just short form of if/else

case "$b" in
 5) a=$c ;;
 *) a=$d ;;
esac

Or

 [[ $b = 5 ]] && a="$c" || a="$d"

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

Try this:

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

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

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

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

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

result = np.mat(result)

Checkout Jenkins Pipeline Git SCM with credentials?

Adding you a quick example using git plugin GitSCM:

    checkout([
        $class: 'GitSCM', 
        branches: [[name: '*/master']], 
        doGenerateSubmoduleConfigurations: false, 
        extensions: [[$class: 'CleanCheckout']], 
        submoduleCfg: [], 
        userRemoteConfigs: [[credentialsId: '<gitCredentials>', url: '<gitRepoURL>']]
    ])

in your pipeline

stage('checkout'){
    steps{
        script{
            checkout
        }
    }
}

How can I have linebreaks in my long LaTeX equations?

There are a couple ways you can deal with this. First, and perhaps best, is to rework your equation so that it is not so long; it is likely unreadable if it is that long.

If it must be so, check out the AMS Short Math Guide for some ways to handle it. (on the second page)

Personally, I'd use an align environment, so that the breaking and alignment can be precisely controlled. e.g.

\begin{align*}
   x&+y+\dots+\dots+x_100000000\\
   &+x_100000001+\dots+\dots
\end{align*}

which would line up the first plus signs of each line... but obviously, you can set the alignments wherever you like.

How do I set a VB.Net ComboBox default value

If ComboBox1.SelectedIndex = -1 Then
    ComboBox1.SelectedIndex = 0    
End If

How to export a Vagrant virtual machine to transfer it

As of 2019 there is a subcommand: vagrant box repackage

vagrant box repackage --help 
Usage: vagrant box repackage <name> <provider> <version>
    -h, --help                       Print this help

You can find name provider and version by running vagrant box list

vagrant box list
macinbox (virtualbox, 10.14.5)

The ouput of vagrant box repackage is a file called package.box which is basically a tgz file which the content can be listed as below:

tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk

Picking a random element from a set

For fun I wrote a RandomHashSet based on rejection sampling. It's a bit hacky, since HashMap doesn't let us access it's table directly, but it should work just fine.

It doesn't use any extra memory, and lookup time is O(1) amortized. (Because java HashTable is dense).

class RandomHashSet<V> extends AbstractSet<V> {
    private Map<Object,V> map = new HashMap<>();
    public boolean add(V v) {
        return map.put(new WrapKey<V>(v),v) == null;
    }
    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {
            RandKey key = new RandKey();
            @Override public boolean hasNext() {
                return true;
            }
            @Override public V next() {
                while (true) {
                    key.next();
                    V v = map.get(key);
                    if (v != null)
                        return v;
                }
            }
            @Override public void remove() {
                throw new NotImplementedException();
            }
        };
    }
    @Override
    public int size() {
        return map.size();
    }
    static class WrapKey<V> {
        private V v;
        WrapKey(V v) {
            this.v = v;
        }
        @Override public int hashCode() {
            return v.hashCode();
        }
        @Override public boolean equals(Object o) {
            if (o instanceof RandKey)
                return true;
            return v.equals(o);
        }
    }
    static class RandKey {
        private Random rand = new Random();
        int key = rand.nextInt();
        public void next() {
            key = rand.nextInt();
        }
        @Override public int hashCode() {
            return key;
        }
        @Override public boolean equals(Object o) {
            return true;
        }
    }
}

How can I use Async with ForEach?

This little extension method should give you exception-safe async iteration:

public static async Task ForEachAsync<T>(this List<T> list, Func<T, Task> func)
{
    foreach (var value in list)
    {
        await func(value);
    }
}

Since we're changing the return type of the lambda from void to Task, exceptions will propagate up correctly. This will allow you to write something like this in practice:

await db.Groups.ToList().ForEachAsync(async i => {
    await GetAdminsFromGroup(i.Gid);
});

JQuery get all elements by class name

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);

Where does pip install its packages?

pip show <package name> will provide the location for Windows and macOS, and I'm guessing any system. :)

For example:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

How can I pass a member function where a free function is expected?

There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus

void (aClass::*)(int, int)

rather than the type you try to use

void (*)(int, int)

One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).

If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.

In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().

The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.

To clarify how to use a function pointer to call a member function, here is an example:

// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
    fptr(context, 17, 42);
}

void non_member(void*, int i0, int i1) {
    std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}

struct foo {
    void member(int i0, int i1) {
        std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
    }
};

void forwarder(void* context, int i0, int i1) {
    static_cast<foo*>(context)->member(i0, i1);
}

int main() {
    somefunction(&non_member, nullptr);
    foo object;
    somefunction(&forwarder, &object);
}

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

Correct way to push into state array

You can use .concat method to create copy of your array with new data:

this.setState({ myArray: this.state.myArray.concat('new value') })

But beware of special behaviour of .concat method when passing arrays - [1, 2].concat(['foo', 3], 'bar') will result in [1, 2, 'foo', 3, 'bar'].

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

When you run WScript.Shell it runs under the local system account, this account has full rights on the machine, but no rights in Active Directory.

http://support.microsoft.com/kb/278319

Difference between Static and final?

static means there is only one copy of the variable in memory shared by all instances of the class.

The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.

Is it possible to run CUDA on AMD GPUs?

I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:

An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

How to know function return type and argument types?

For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?

Um... There is no "concise" description of this. It's complex. You've designed it to be complex. And it requires complex documentation in the docstring.

Sorry, but complexity is -- well -- complex.

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

jQuery UI Dialog - missing close icon

Even loading bootstrap after jquery-ui, I was able to fix using this:

.ui-dialog-titlebar-close:after {
   content: 'X' !important;
   position: absolute;
   top: -2px;
   right: 3px;
}

Get last dirname/filename in a file path argument in Bash

basename does remove the directory prefix of a path:

$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example

Best way to track onchange as-you-type in input type="text"?

Update:

See Another answer (2015).


Original 2009 Answer:

So, you want the onchange event to fire on keydown, blur, and paste? That's magic.

If you want to track changes as they type, use "onkeydown". If you need to trap paste operations with the mouse, use "onpaste" (IE, FF3) and "oninput" (FF, Opera, Chrome, Safari1).

1Broken for <textarea> on Safari. Use textInput instead

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

Getting number of elements in an iterator in Python

This is against the very definition of an iterator, which is a pointer to an object, plus information about how to get to the next object.

An iterator does not know how many more times it will be able to iterate until terminating. This could be infinite, so infinity might be your answer.

How can I read SMS messages from the device programmatically in Android?

Use Content Resolver ("content://sms/inbox") to read SMS which are in inbox.

// public static final String INBOX = "content://sms/inbox";
// public static final String SENT = "content://sms/sent";
// public static final String DRAFT = "content://sms/draft";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

if (cursor.moveToFirst()) { // must check the result to prevent exception
    do {
       String msgData = "";
       for(int idx=0;idx<cursor.getColumnCount();idx++)
       {
           msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
       }
       // use msgData
    } while (cursor.moveToNext());
} else {
   // empty box, no SMS
}

Please add READ_SMS permission.

I Hope it helps :)

How to install pip for Python 3 on Mac OS X?

I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do

brew doctor

After that

brew reinstall python3

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Adding default parameter value with type hint in Python

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

How to overlay density plots in R?

Adding base graphics version that takes care of y-axis limits, add colors and works for any number of columns:

If we have a data set:

myData <- data.frame(std.nromal=rnorm(1000, m=0, sd=1),
                     wide.normal=rnorm(1000, m=0, sd=2),
                     exponent=rexp(1000, rate=1),
                     uniform=runif(1000, min=-3, max=3)
                     )

Then to plot the densities:

dens <- apply(myData, 2, density)

plot(NA, xlim=range(sapply(dens, "[", "x")), ylim=range(sapply(dens, "[", "y")))
mapply(lines, dens, col=1:length(dens))

legend("topright", legend=names(dens), fill=1:length(dens))

Which gives:

enter image description here

How can I perform a short delay in C# without using sleep?

By adding using System.Timers; to your program you can use this function:

private static void delay(int Time_delay)
{
   int i=0;
  //  ameTir = new System.Timers.Timer();
    _delayTimer = new System.Timers.Timer();
    _delayTimer.Interval = Time_delay;
    _delayTimer.AutoReset = false; //so that it only calls the method once
    _delayTimer.Elapsed += (s, args) => i = 1;
    _delayTimer.Start();
    while (i == 0) { };
}

Delay is a function and can be used like:

delay(5000);

How to resize JLabel ImageIcon?

One (quick & dirty) way to resize images it to use HTML & specify the new size in the image element. This even works for animated images with transparency.

Node.js Mongoose.js string to ObjectId function

I couldn't resolve this method (admittedly I didn't search for long)

mongoose.mongo.BSONPure.ObjectID.fromHexString

If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.

You could use something like this however, which gives a bit more flex:

function toObjectId(ids) {

    if (ids.constructor === Array) {
        return ids.map(mongoose.Types.ObjectId);
    }

    return mongoose.Types.ObjectId(ids);
}

Angular routerLink does not navigate to the corresponding component

I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components

Pycharm and sys.argv arguments

On PyCharm Community or Professional Edition 2019.1+ :

  1. From the menu bar click Run -> Edit Configurations
  2. Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
  3. Click Apply
  4. Click OK

What is the easiest way to get current GMT time in Unix timestamp format?

Does this help?

from datetime import datetime
import calendar

d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime

How to convert Python UTC datetime object to UNIX timestamp

How to use Git for Unity3D source control?

I wanted to add a very simple workflow from someone who has been frustrated with git in the past. There are several ways to use git, probably the most common for unity are GitHub Desktop, Git Bash and GitHub Unity

https://assetstore.unity.com/packages/tools/version-control/github-for-unity-118069.

Essentially they all do the same thing but its user choice. You can have git for large file setup which allows 1GB free large file storage with additional storage available in data packs for $4/mo for 50GB, and this will allow you to push files >100mb to remote repositories (it stores the actual files on a server and in your repo a pointer)

https://git-lfs.github.com/

If you don't want to setup lfs for whatever reason you can scan your projects for files > 128 mb in windows by typing size:large in the directory where you have your project. This can be handy to search for large files, although there may be some files between 100mb and 128mb that get missed.

enter image description here

The general format of git bash is

git add . (adds files to be commited)

git commit -m 'message' (commits the files with a message, they are still on your pc and not in the remote repo, basically they have been 'versioned' as a new commit)

git push (push files to the repository)

The disadvantage of git bash for unity projects is that if there is a file > 100mb, you won't get an error until you push. You then have to undo your commit by resetting your head to the previous commit. Kind of a hassle, especially if you are new with git bash.

The advantage of GitHub Desktop, is BEFORE you commit files with 100mb it will give you a popup error message. You can then shrink those files or add them to a .gitignore file.

To use a .gitignore file, create a file called .gitignore in your local repository root directory. Simply add the files one line at a time you would like to omit. SharedAssets and other non-Asset folder files can usually be omitted and will automatically repopulate in the editor (packages can be re-imported etc). You can also use wildcards to exclude file types.

If other people are using your GitHub repo and you want to clone or pull you have those options available to you as well on GitHub desktop or Git bash.

I did not mention much about Unity GitHub package where you can use GitHub in the editor because personally I did not find the interface very useful, and I don't think overall its going to help anyone get familiar with git, but this is just my preference.

How to code a very simple login system with java

One way you could do it is have a file with the username and pass directly under it. Then uses the Scanner class and when you create it, make the file the parameter for the Scanner. Then use the methods hasNext(); and nextLine to verify the username and password;

String user;
String pass;

Scanner scan = new Scanner(new File("File.txt"));

while(scan.hasNext){ //While the file still has more lines remaining
     if(scan.nextLine() == user){
          if(scan.nextLine == pass){
                   lblDisplay.setText("Credentials Accepted.");
          }
          else{
               lblDisplay.setText("Please try again.");
          }
     }
}

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How to run iPhone emulator WITHOUT starting Xcode?

With Xcode 6 the location of the simulator has changed to:

/Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app

It can no longer be found here:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app

I hope this helps someone since I sometimes want to start the simulator from terminal.

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Calculate distance in meters when you know longitude and latitude in java

In C++ it is done like this:

#define LOCAL_PI 3.1415926535897932385 

double ToRadians(double degrees) 
{
  double radians = degrees * LOCAL_PI / 180;
  return radians;
}

double DirectDistance(double lat1, double lng1, double lat2, double lng2) 
{
  double earthRadius = 3958.75;
  double dLat = ToRadians(lat2-lat1);
  double dLng = ToRadians(lng2-lng1);
  double a = sin(dLat/2) * sin(dLat/2) + 
             cos(ToRadians(lat1)) * cos(ToRadians(lat2)) * 
             sin(dLng/2) * sin(dLng/2);
  double c = 2 * atan2(sqrt(a), sqrt(1-a));
  double dist = earthRadius * c;
  double meterConversion = 1609.00;
  return dist * meterConversion;
}

Android - Pulling SQlite database android device

Using Android Studio 3.0 or later version it is possible to pull database (also shared preference, cache directory and others) if application runs in debug mode on non-rooted device.

To pull database using android studio follow these steps.

  1. Click View > Tool Windows > Device File Explorer.
  2. Expand /data/data/[package-name] nodes.

Steps followed in Android Studio 3.0

How to attach a file using mail command on Linux?

My answer needs base64 in addition to mail, but some uuencode versions can also do base64 with -m, or you can forget about mime and use the plain uuencode output...

   [email protected]
   [email protected]
   SUBJECT="Auto emailed"
   MIME="application/x-gzip"  # Adjust this to the proper mime-type of file
   FILE=somefile.tar.gz
   ENCODING=base64  
   boundary="---my-unlikely-text-for-mime-boundary---$$--" 

   (cat <<EOF
    From: $FROM
    To: $REPORT_DEST
    Subject: $SUBJECT
    Date: $(date +"%a, %b %e %Y %T %z")
    Mime-Version: 1.0
    Content-Type: multipart/mixed; boundary="$boundary"
    Content-Disposition: inline

    --$boundary
    Content-Type: text/plain; charset=us-ascii
    Content-Disposition: inline

    This email has attached the file

    --$boundary
    Content-Type: $MIME;name="$FILE"
    Content-Disposition: attachment;filename="$FILE"
    Content-Transfer-Encoding: $ENCODING

    EOF
    base64 $FILE
    echo ""
    echo "--$boundary" ) | mail

Android Studio suddenly cannot resolve symbols

None of these methods helped me in Android Studio 0.5.8.

My solution was to delete ~/.AndroidStudioPreview directory (in Ubuntu). Sorry, I have no idea where is it in other OS. This directory stores temporary files and Android Studio settings, so I missed all my settings. But it works!

Toggle display:none style with JavaScript

Give the UL an ID and use the getElementById function:

<html>
<body>
    <script>
    function toggledisplay(elementID)
    {
        (function(style) {
            style.display = style.display === 'none' ? '' : 'none';
        })(document.getElementById(elementID).style);
    }
    </script>

<a href="#" title="Show Tags" onClick="toggledisplay('changethis');">Show All Tags</a>
<ul class="subforums" id="changethis" style="overflow-x: visible; overflow-y: visible; ">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

</body>
</html>

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

if you just want a human readable time string and not that exact format:

$t = localtime;
print "$t\n";

prints

Mon Apr 27 10:16:19 2015

or whatever is configured for your locale.

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

How to center and crop an image to always appear in square shape with CSS?

HTML:

<div class="thumbnail">
</div>

CSS:

.thumbnail { 
background: url(image.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}

Python Save to file

myFile = open('today','r')

ips = {}

for line in myFile:
    parts = line.split()
    if parts[1] == 'Failure':
        ips.setdefault(parts[0], 0)
        ips[parts[0]] += 1

of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
    of.write(k+'\n')

Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.

Retrieve Button value with jQuery

Give the buttons a value attribute and then retrieve the values using this:

$("button").click(function(){
  var value=$(this).attr("value");
});

Why can't I change my input value in React even with the onChange listener

If you would like to handle multiple inputs with one handler take a look at my approach where I'm using computed property to get value of the input based on it's name.

import React, { useState } from "react";
import "./style.css";

export default function App() {
  const [state, setState] = useState({
    name: "John Doe",
    email: "[email protected]"
  });

  const handleChange = e => {
    setState({
      [e.target.name]: e.target.value
    });
  };

  return (
    <div>
      <input
        type="text"
        className="name"
        name="name"
        value={state.name}
        onChange={handleChange}
      />

      <input
        type="text"
        className="email"
        name="email"
        value={state.email}
        onChange={handleChange}
      />
    </div>
  );
}

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

The easiest way to transform collection to array?

For example, you have collection ArrayList with elements Student class:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array