Programs & Examples On #K means

In statistics and data mining, k-means clustering is a method of cluster analysis which aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean (least squares).

How do I determine k when using k-means clustering?

Another approach is using Self Organizing Maps (SOP) to find optimal number of clusters. The SOM (Self-Organizing Map) is an unsupervised neural network methodology, which needs only the input is used to clustering for problem solving. This approach used in a paper about customer segmentation.

The reference of the paper is

Abdellah Amine et al., Customer Segmentation Model in E-commerce Using Clustering Techniques and LRFM Model: The Case of Online Stores in Morocco, World Academy of Science, Engineering and Technology International Journal of Computer and Information Engineering Vol:9, No:8, 2015, 1999 - 2010

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

How to efficiently remove duplicates from an array without using Set

Not a big fun of updating user input, however considering your constraints...

public int[] removeDup(int[] nums) {
  Arrays.sort(nums);
  int x = 0;
  for (int i = 0; i < nums.length; i++) {
    if (i == 0 || nums[i] != nums[i - 1]) {
    nums[x++] = nums[i];
    }
  }
  return Arrays.copyOf(nums, x);
}

Array sort can be easily replaced with any nlog(n) algorithm.

How to convert number to words in java

You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.

Here is a link to the Bitbucket Repo

How to set the style -webkit-transform dynamically using JavaScript?

If you want to do it via setAttribute you would change the style attribute like so:

element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc

This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:

element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';

The above is equivalent to

element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

invalid command code ., despite escaping periods, using sed

Probably your new domain contain / ? If so, try using separator other than / in sed, e.g. #, , etc.

find ./ -type f -exec sed -i 's#192.168.20.1#new.domain.com#' {} \;

It would also be good to enclose s/// in single quote rather than double quote to avoid variable substitution or any other unexpected behaviour

Database design for a survey

The second approach is best.

If you want to normalize it further you could create a table for question types

The simple things to do are:

  • Place the database and log on their own disk, not all on C as default
  • Create the database as large as needed so you do not have pauses while the database grows

We have had log tables in SQL Server Table with 10's of millions rows.

jQuery UI Tabs - How to Get Currently Selected Tab Index

$("#tabs").tabs({
    activate: function(event, ui) {
        new_index = ui.newTab.index()+1;
        //do anything
    }
});

IE8 css selector

OK so, it isn't css hack, but out of frustration for not being able to find ways to target ie8 from css, and due to policy of not having ie specific css files, I had to do following, which I assume someone else might find useful:

if (jQuery.browser.version==8.0) {
   $(results).css({
         'left':'23px',
         'top':'-253px'
      });
}

CSS z-index not working (position absolute)

I was struggling with this problem, and I learned (thanks to this post) that:

opacity can also affect the z-index

_x000D_
_x000D_
div:first-child {_x000D_
  opacity: .99; _x000D_
}_x000D_
_x000D_
.red, .green, .blue {_x000D_
  position: absolute;_x000D_
  width: 100px;_x000D_
  color: white;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.red {_x000D_
  z-index: 1;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.green {_x000D_
  top: 60px;_x000D_
  left: 60px;_x000D_
  background: green;_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  background: blue;_x000D_
}
_x000D_
<div>_x000D_
  <span class="red">Red</span>_x000D_
</div>_x000D_
<div>_x000D_
  <span class="green">Green</span>_x000D_
</div>_x000D_
<div>_x000D_
  <span class="blue">Blue</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

It sounds like you have a memory leak. The problem isn't handling many images, it's that your images aren't getting deallocated when your activity is destroyed.

It's difficult to say why this is without looking at your code. However, this article has some tips that might help:

http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

In particular, using static variables is likely to make things worse, not better. You might need to add code that removes callbacks when your application redraws -- but again, there's not enough information here to say for sure.

How to add hyperlink in JLabel?

If <a href="link"> doesn't work, then:

  1. Create a JLabel and add a MouseListener (decorate the label to look like a hyperlink)
  2. Implement mouseClicked() event
  3. In the implementation of mouseClicked() event, perform your action

Have a look at java.awt.Desktop API for opening a link using the default browser (this API is available only from Java6).

ActiveModel::ForbiddenAttributesError when creating new user

For those using CanCan. People might be experiencing this if they use CanCan with Rails 4+. Try AntonTrapps's rather clean workaround solution here until CanCan gets updated:

In the ApplicationController:

before_filter do
  resource = controller_name.singularize.to_sym
  method = "#{resource}_params"
  params[resource] &&= send(method) if respond_to?(method, true)
end

and in the resource controller (for example NoteController):

private
def note_params
  params.require(:note).permit(:what, :ever)
end

Update:

Here's a continuation project for CanCan called CanCanCan, which looks promising:

CanCanCan

Format a message using MessageFormat.format() in Java

For everyone that has Android problems in the string.xml, use \'\' instead of single quote.

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

Lua string to int

Use the tonumber function. As in a = tonumber("10").

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js files with modern JavaScript.

First, change all the extensions to .ts.

Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }

Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.

Get-ChildItem | foreach { tsc $_.Name  }

Finally, combine all the *.d.ts files into one index.d.ts, removing the import statements and removing the default from each export statement.

Remove-Item index.d.ts; 

Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
  foreach { Get-Content $_ } | `
  where { !$_.ToString().StartsWith("import") } | `
  foreach { $_.Replace("export default", "export") } | `
  foreach { Add-Content index.d.ts $_ }

This ends with a single, usable index.d.ts file that includes many of the definitions.

Convert serial.read() into a useable string using Arduino?

Use string append operator on the serial.read(). It works better than string.concat()

char r;
string mystring = "";

while(serial.available()){
    r = serial.read();
    mystring = mystring + r; 
}

After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

How do I duplicate a line or selection within Visual Studio Code?

If you coming from Sublime Text and do not want to relearn new key binding, you can use this extension for Visual Code Studio.

Sublime Text Keymap for VS Code

This extension ports the most popular Sublime Text keyboard shortcuts to Visual Studio Code. After installing the extension and restarting VS Code your favorite keyboard shortcuts from Sublime Text are now available.

https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

Error Running React Native App From Terminal (iOS)

None of these solutions worked for me. These two similar problems offer temporary solutions that worked, it seems the simulator process isn't being shutdown correctly:

Killing Simulator Processes

From https://stackoverflow.com/a/52533391/11279823

  1. Quit the simulator & Xcode.
  2. Opened Activity monitor, selected cpu option and search for sim, killing all the process shown as result.
  3. Then fired up the terminal and run sudo xcrun simctl erase all. It will delete all content of all simulators. By content if you logged in somewhere password will be gone, all developer apps installed in that simulator will be gone.

Opening Simulator before starting the package

From https://stackoverflow.com/a/55374768/11279823

open -a Simulator; npm start

Hopefully a permanent solution is found.

Is there any "font smoothing" in Google Chrome?

Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing property on yer h4 tags like this.

h4 {
    -webkit-font-smoothing: antialiased;
}

You can also use subpixel-antialiased, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.

Serialize object to query string in JavaScript/jQuery

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

jquery, domain, get URL

//If url is something.domain.com this returns -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-z]+.)/,"");
}

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Just add the this annotation @Temporal(TemporalType.DATE) for a java.util.Date field in your entity class.

More information available in this stackoverflow answer.

Add / remove input field dynamically with jQuery

Another solution could be:

<script>
$(document)
        .ready(
                function() {
                    var wrapper = $(".myFields");
                    $(add_button)
                            .click(
                                    function(e) {
                                        e.preventDefault();
                                        $(wrapper)
                                                .append(
                                                        '.....'); //add fields here
                                    });
                    $(wrapper).on("click", ".delFld", function(e) {
                        e.preventDefault();
                        $(this).parent('div').remove();
                    })
                }); 
</script>

Source: Here

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This works:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time" // or "runtime"
)

func cleanup() {
    fmt.Println("cleanup")
}

func main() {
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        cleanup()
        os.Exit(1)
    }()

    for {
        fmt.Println("sleeping...")
        time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
    }
}

libaio.so.1: cannot open shared object file

Here on a openSuse 12.3 the solution was installing the 32-bit version of libaio in addition. Oracle seems to need this now, although on 12.1 it run without the 32-bit version.

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

unable to remove file that really exists - fatal: pathspec ... did not match any files

I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.

I had a LibreOffice doc file, call it final report.odt. I later changed its case to Final Report.odt. In Windows, this doesn't even count as a rename. final report.odt, Final Report.odt, FiNaL RePoRt.oDt are all the same. In Linux, these are all distinct.

When I eventually went to git rm "Final Report.odt" and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt" -- did it work.

Lesson learned: to change the case I should have instead done:

git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"

Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.

Entity Framework and SQL Server View

The current Entity Framework EDM generator will create a composite key from all non-nullable fields in your view. In order to gain control over this, you will need to modify the view and underlying table columns setting the columns to nullable when you do not want them to be part of the primary key. The opposite is also true, as I encountered, the EDM generated key was causing data-duplication issues, so I had to define a nullable column as non-nullable to force the composite key in the EDM to include that column.

Copy directory to another directory using ADD command

You can use COPY. You need to specify the directory explicitly. It won't be created by itself

COPY go /usr/local/go

Reference: Docker CP reference

Convert a character digit to the corresponding integer in C

char chVal = '5';
char chIndex;

if ((chVal >= '0') && (chVal <= '9')) {

    chIndex = chVal - '0';
}
else 
if ((chVal >= 'a') && (chVal <= 'z')) {

    chIndex = chVal - 'a';
}
else 
if ((chVal >= 'A') && (chVal <= 'Z')) {

    chIndex = chVal - 'A';
}
else {
    chIndex = -1; // Error value !!!
}

How To Get Selected Value From UIPickerView

This is what I did:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    selectedEntry = [allEntries objectAtIndex:row];

}

The selectedEntry is a NSString and will hold the currently selected entry in the pickerview. I am new to objective C but I think this is much easier.

What is class="mb-0" in Bootstrap 4?

m - for classes that set margin, like this :

  • mt - for classes that set margin-top
  • mb - for classes that set margin-bottom
  • ml - for classes that set margin-left
  • mr - for classes that set margin-right
  • mx - for classes that set both margin-left and margin-right
  • my - for classes that set both margin-top and margin-bottom

Where size is one of margin :

  • 0 - for classes that eliminate the margin by setting it to 0, like mt-0
  • 1 - (by default) for classes that set the margin to $spacer * .25, like mt-1
  • 2 - (by default) for classes that set the margin to $spacer * .5, like mt-2
  • 3 - (by default) for classes that set the margin to $spacer, like mt-3
  • 4 - (by default) for classes that set the margin to $spacer * 1.5, like mt-4
  • 5 - (by default) for classes that set the margin to $spacer * 3, like mt-5
  • auto - for classes that set the margin to auto, like mx-auto

Animation fade in and out

we can simply use:

public void animStart(View view) {
    if(count==0){
        Log.d("count", String.valueOf(count));
        i1.animate().alpha(0f).setDuration(2000);
        i2.animate().alpha(1f).setDuration(2000);
        count =1;
    }
    else if(count==1){
        Log.d("count", String.valueOf(count));
        count =0;
        i2.animate().alpha(0f).setDuration(2000);
        i1.animate().alpha(1f).setDuration(2000);
    }
}

where i1 and i2 are defined in the onCreateView() as:

    i1 = (ImageView)findViewById(R.id.firstImage);
    i2 = (ImageView)findViewById(R.id.secondImage);

count is a class variable initilaized to 0.

The XML file is :

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <ImageView
            android:id="@+id/secondImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="animStart"
            android:src="@drawable/second" />
      <ImageView
          android:id="@+id/firstImage"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"

          android:onClick="animStart"
          android:src="@drawable/first" />
    </RelativeLayout>

@drawable/first and @drawable/second are the images in the drawable folder in res.

How to execute powershell commands from a batch file?

untested.cmd

;@echo off
;Findstr -rbv ; %0 | powershell -c - 
;goto:sCode

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD

;:sCode 
;echo done
;pause & goto :eof

How can I get the selected VALUE out of a QCombobox?

I did this

QDir path("/home/user/");
QStringList _dirs = path.entryList(QDir::Dirs);
std::cout << "_dirs_count = " << _dirs.count() << std::endl;
ui->cmbbox->addItem(Files);
ui->cmbbox->show();

You will see with this that the QStringList named _dirs is structured like an array whose members you can access via an index up to the value returned by _dirs.count()

What does the Excel range.Rows property really do?

Range.Rows and Range.Columns return essentially the same Range except for the fact that the new Range has a flag which indicates that it represents Rows or Columns. This is necessary for some Excel properties such as Range.Count and Range.Hidden and for some methods such as Range.AutoFit():

  • Range.Rows.Count returns the number of rows in Range.
  • Range.Columns.Count returns the number of columns in Range.
  • Range.Rows.AutoFit() autofits the rows in Range.
  • Range.Columns.AutoFit() autofits the columns in Range.

You might find that Range.EntireRow and Range.EntireColumn are useful, although they still are not exactly what you are looking for. They return all possible columns for EntireRow and all possible rows for EntireColumn for the represented range.

I know this because SpreadsheetGear for .NET comes with .NET APIs which are very similar to Excel's APIs. The SpreadsheetGear API comes with several strongly typed overloads to the IRange indexer including the one you probably wish Excel had:

  • IRange this[int row1, int column1, int row2, int column2];

Disclaimer: I own SpreadsheetGear LLC

How to create a dump with Oracle PL/SQL Developer?

Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.

CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test'; 

See this for an example.

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

What's the difference between Git Revert, Checkout and Reset?

If you broke the tree but didn't commit the code, you can use git reset, and if you just want to restore one file, you can use git checkout.

If you broke the tree and committed the code, you can use git revert HEAD.

http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

'foo' was not declared in this scope c++

In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.

Either move the definition of integrate above the one for getSkewNormal, or add a forward declaration above getSkewNormal:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

The same applies for sum.

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

How to pull specific directory with git

Sometimes, you just want to have a look at previous copies of files without the rigmarole of going through the diffs.

In such a case, it's just as easy to make a clone of a repository and checkout the specific commit that you are interested in and have a look at the subdirectory in that cloned repository. Because everything is local you can just delete this clone when you are done.

What's the fastest way to convert String to Number in JavaScript?

You can try using UnitOf, a measurement and data type conversion library we just officially released! UnitOf is super fast, small in size, and efficient at converting any data type without ever throwing an error or null/undefined. Default values you define or UnitOf's defaults are returned when a conversion is unsuccessful.

//One liner examples
UnitOf.DataType("12.5").toFloat(); //12.5 of type Float is returned. 0 would be returned if conversion failed.
UnitOf.DataType("Not A Num").toInt(10); //10 of type Int is returned as the conversion failed.

//Or as a variable
var unit = UnitOf.DataType("12.5");
unit.toInt(5); //12.5 of type Float is returned. 5 would be returned if the conversion failed.
unit.toFloat(8); // 12 of type Int is returned. 8 would be returned if the conversion failed.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

Float a DIV on top of another DIV

.close-image {
    cursor: pointer;
    display: block;
    float: right;
    position: relative;
    top: 22px;
    z-index: 1;
}

I think this might be what you are looking for.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Not sure as cant see it in steps you mentioned.

Please try FLUSH PRIVILEGES [Reloads the privileges from the grant tables in the mysql database]:

flush privileges;

You need to execute it after GRANT

Hope this help!

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

How to import other Python files?

How I import is import the file and use shorthand of it's name.

import DoStuff.py as DS
DS.main()

Don't forget that your importing file MUST BE named with .py extension

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

No pressing enter required

Here's a longer, but reusable and modular approach:

  • Returns 0=yes and 1=no
  • No pressing enter required - just a single character
  • Can press enter to accept the default choice
  • Can disable default choice to force a selection
  • Works for both zsh and bash.

Defaulting to "no" when pressing enter

Note that the N is capitalsed. Here enter is pressed, accepting the default:

$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]?

Also note, that [y/N]? was automatically appended. The default "no" is accepted, so nothing is echoed.

Re-prompt until a valid response is given:

$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]? X
Show dangerous command [y/N]? y
rm *

Defaulting to "yes" when pressing enter

Note that the Y is capitalised:

$ confirm_yes "Show dangerous command" && echo "rm *"
Show dangerous command [Y/n]?
rm *

Above, I just pressed enter, so the command ran.

No default on enter - require y or n

$ get_yes_keypress "Here you cannot press enter. Do you like this"
Here you cannot press enter. Do you like this [y/n]? k
Here you cannot press enter. Do you like this [y/n]?
Here you cannot press enter. Do you like this [y/n]? n
$ echo $?
1

Here, 1 or false was returned. Note no capitalisation in [y/n]?

Code

# Read a single char from /dev/tty, prompting with "$*"
# Note: pressing enter will return a null string. Perhaps a version terminated with X and then remove it in caller?
# See https://unix.stackexchange.com/a/367880/143394 for dealing with multi-byte, etc.
function get_keypress {
  local REPLY IFS=
  >/dev/tty printf '%s' "$*"
  [[ $ZSH_VERSION ]] && read -rk1  # Use -u0 to read from STDIN
  # See https://unix.stackexchange.com/q/383197/143394 regarding '\n' -> ''
  [[ $BASH_VERSION ]] && </dev/tty read -rn1
  printf '%s' "$REPLY"
}

# Get a y/n from the user, return yes=0, no=1 enter=$2
# Prompt using $1.
# If set, return $2 on pressing enter, useful for cancel or defualting
function get_yes_keypress {
  local prompt="${1:-Are you sure} [y/n]? "
  local enter_return=$2
  local REPLY
  # [[ ! $prompt ]] && prompt="[y/n]? "
  while REPLY=$(get_keypress "$prompt"); do
    [[ $REPLY ]] && printf '\n' # $REPLY blank if user presses enter
    case "$REPLY" in
      Y|y)  return 0;;
      N|n)  return 1;;
      '')   [[ $enter_return ]] && return "$enter_return"
    esac
  done
}
    
# Credit: http://unix.stackexchange.com/a/14444/143394
# Prompt to confirm, defaulting to NO on <enter>
# Usage: confirm "Dangerous. Are you sure?" && rm *
function confirm {
  local prompt="${*:-Are you sure} [y/N]? "
  get_yes_keypress "$prompt" 1
}    

# Prompt to confirm, defaulting to YES on <enter>
function confirm_yes {
  local prompt="${*:-Are you sure} [Y/n]? "
  get_yes_keypress "$prompt" 0
}

ng-change get new value and original value

You could use a watch instead, because that has the old and new value, but then you're adding to the digest cycle.

I'd just keep a second variable in the controller and set that.

Convert DataTable to CSV stream

I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..

public string DataTableToCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    if (dt == null)
        return "";

    try {
        // Create the header row
        for (int i = 0; i <= dt.Columns.Count - 1; i++) {
            // Append column name in quotes
            sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
            // Add carriage return and linefeed if last column, else add comma
            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
        }


        foreach (DataRow row in dt.Rows) {
            for (int i = 0; i <= dt.Columns.Count - 1; i++) {
                // Append value in quotes
                //sb.Append("""" & row.Item(i) & """")

                // OR only quote items that that are equivilant to strings
                sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);

                // Append CR+LF if last field, else add Comma
                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
            }
        }
        return sb.ToString;
    } catch (Exception ex) {
        // Handle the exception however you want
        return "";
    }

}

What is the purpose of nameof?

The ASP.NET Core MVC project uses nameof in the AccountController.cs and ManageController.cs with the RedirectToAction method to reference an action in the controller.

Example:

return RedirectToAction(nameof(HomeController.Index), "Home");

This translates to:

return RedirectToAction("Index", "Home");

and takes takes the user to the 'Index' action in the 'Home' controller, i.e. /Home/Index.

Add items in array angular 4

Your empList is object type but you are trying to push strings

Try this

this.empList.push({this.name,this.empoloyeeID});

How to truncate milliseconds off of a .NET DateTime

The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).

DateTime dateTime = ... anything ...
dateTime = new DateTime(
    dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond), 
    dateTime.Kind
    );

or the equivalent and shorter:

dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));

This could be generalized into an extension method:

public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
    if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
    if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
    return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}

which is used as follows:

dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...

Clear the entire history stack and start a new activity on Android

Sometimes your android emulator might fails to connect eclipse DDMS tool and ask for adb to start manually. In that case you can start or stop the adb using the command prompt.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

PHP Unset Array value effect on other indexes

This might be a little bit out of context but in unsetting values from a global array, apply the answer by Michael Berkowski above but in use with $GLOBALS instead of the the global value you declared with global $variable_name. So it will be something like:

unset($GLOBALS['variable_name']['array_key']);

Instead of:

global $variable_name; unset($variable_name['array_key']);

NB: This works only if you're using global variables.

Deleting DataFrame row in Pandas based on column value

If I'm understanding correctly, it should be as simple as:

df = df[df.line_race != 0]

Overwriting txt file in java

This simplifies it a bit and it behaves as you want it.

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

When should I use semicolons in SQL Server?

According to Transact-SQL Syntax Conventions (Transact-SQL) (MSDN)

Transact-SQL statement terminator. Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version.

(also see @gerryLowry 's comment)

How to make the first option of <select> selected with jQuery

$("#target").val(null);

worked fine in chrome

PHP - Get bool to echo false when false

The %b option of sprintf() will convert a boolean to an integer:

echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1

If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.

Each pattern will be replaced by the argument in order:

echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How to view transaction logs in SQL Server 2008

You could use the undocumented

DBCC LOG(databasename, typeofoutput)

where typeofoutput:

0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.

For example, DBCC LOG(database, 1)

You could also try fn_dblog.

For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.

Integer.valueOf() vs. Integer.parseInt()

parseInt() parses String to int while valueOf() additionally wraps this int into Integer. That's the only difference.

If you want to have full control over parsing integers, check out NumberFormat with various locales.

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

Could not locate Gemfile

Here is something you could try.

Add this to any config files you use to run your app.

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
Bundler.require(:default)

Rails and other Rack based apps use this scheme. It happens sometimes that you are trying to run things which are some directories deeper than your root where your Gemfile normally is located. Of course you solved this problem for now but occasionally we all get into trouble with this finding the Gemfile. I sometimes like when you can have all you gems in the .bundle directory also. It never hurts to keep this site address under your pillow. http://bundler.io/

How to remove first and last character of a string?

SOLUTION 1

def spaceMeOut(str1):

   print(str1[1:len(str1)-1])

str1='Hello'

print(spaceMeOut(str1))

SOLUTION 2

def spaceMeOut(str1):

  res=str1[1:len(str1)-1]

  print('{}'.format(res))

str1='Hello'

print(spaceMeOut(str1))

What's the "Content-Length" field in HTTP header?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 1024

Applications SHOULD use this field to indicate the transfer-length of the message-body.

In PHP you would use something like this.

header("Content-Length: ".filesize($filename));

In case of "Content-Type: application/x-www-form-urlencoded" the encoded data is sent to the processing agent designated so you can set the length or size of the data you are going to post.

Base table or view not found: 1146 Table Laravel 5

I also had this problem when doing migration => after performing php artisan migrate:refresh --seed command

"Base table or view not found: 1146 Table posts do not exist" and I solved it, I was using "soft deletes" in a separate migration file, and my original migration for "posts" table which was responsible for creating the "posts" table was performing after the "soft deletes" migration in the database\migration folder, I simply needed to rename the "posts" migration file name and put it before "softdeletes" migration to perform sooner. the do the migration again => php artisan migrate:refresh --seed it's done.

Padding or margin value in pixels as integer using jQuery

Not to necro but I made this which can determine pixels based on a variety of values:

$.fn.extend({
  pixels: function (property, base) {
    var value = $(this).css(property);
    var original = value;
    var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
      ? $(this).parent().outerWidth()
      : $(this).parent().outerHeight();

    // EM Conversion Factor
    base = base || 16;

    if (value == 'auto' || value == 'inherit') 
        return outer || 0;

    value = value.replace('rem', '');
    value = value.replace('em', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? base * value : 0;
    }

    value = value.replace('pt', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? value * 1.333333 : 0; // 1pt = 1.333px
    }

    value = value.replace('%', '');

    if (value !== original) {
      value = parseFloat(value);
      return value ? (outer * value / 100) : 0;
    }

    value = value.replace('px', '');
    return parseFloat(value) || 0;
  }
});

This way, we take into account for sizing, and auto / inherit.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

If you have the to your project and the Copy Local flag is in true, the solution should be just the project. That copy the DLL to the bin folder.

How to break nested loops in JavaScript?

loop1:
    for (var i in set1) {
loop2:
        for (var j in set2) {
loop3:
            for (var k in set3) {
                break loop2;  // breaks out of loop3 and loop2
            }
        }
    }

code copied from Best way to break from nested loops in Javascript?

Please search before posting a question. The link was the FIRST related question I saw on the left side of this page!

Is there a way to get the XPath in Google Chrome?

I tried almost all the available extensions and found the below to be one of the best.

ChroPath Extension link

Just like FirePath, this extension directly gives you the Xpath when you click on Inspect.

enter image description here

Phone: numeric keyboard for text input

For me the best solution was:

For integer numbers, which brings up the 0-9 pad on android and iphone

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d]*" />

You also may want to do this to hide the spinners in firefox/chrome/safari, most clients think they look ugly

 input[type=number]::-webkit-inner-spin-button,
 input[type=number]::-webkit-outer-spin-button {
      -webkit-appearance: none;
      margin: 0;
 }

 input[type=number] {
      -moz-appearance:textfield;
 }

And add novalidate='novalidate' to your form element, if your doing custom validation

Ps just in case you actually wanted floating point numbers after all,step to whatever precision you fancy, will add '.' to android

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d\.]*" step="0.01" />

How do I force "git pull" to overwrite local files?

I had the same problem and for some reason, even a git clean -f -d would not do it. Here is why: For some reason, if your file is ignored by Git (via a .gitignore entry, I assume), it still bothers about overwriting this with a later pull, but a clean will not remove it, unless you add -x.

?: ?? Operators Instead Of IF|ELSE

If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.

if (Source == value) return;
Source = value;
RaisePropertyChanged("Source");

Any way to make a WPF textblock selectable?

All the answers here are just using a TextBox or trying to implement text selection manually, which leads to poor performance or non-native behaviour (blinking caret in TextBox, no keyboard support in manual implementations etc.)

After hours of digging around and reading the WPF source code, I instead discovered a way of enabling the native WPF text selection for TextBlock controls (or really any other controls). Most of the functionality around text selection is implemented in System.Windows.Documents.TextEditor system class.

To enable text selection for your control you need to do two things:

  1. Call TextEditor.RegisterCommandHandlers() once to register class event handlers

  2. Create an instance of TextEditor for each instance of your class and pass the underlying instance of your System.Windows.Documents.ITextContainer to it

There's also a requirement that your control's Focusable property is set to True.

This is it! Sounds easy, but unfortunately TextEditor class is marked as internal. So I had to write a reflection wrapper around it:

class TextEditorWrapper
{
    private static readonly Type TextEditorType = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
    private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
    private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
    private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod("RegisterCommandHandlers", 
        BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);

    private static readonly Type TextContainerType = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
    private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty("TextView");

    private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);

    public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
    {
        RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
    }

    public static TextEditorWrapper CreateFor(TextBlock tb)
    {
        var textContainer = TextContainerProp.GetValue(tb);

        var editor = new TextEditorWrapper(textContainer, tb, false);
        IsReadOnlyProp.SetValue(editor._editor, true);
        TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));

        return editor;
    }

    private readonly object _editor;

    public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)
    {
        _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, 
            null, new[] { textContainer, uiScope, isUndoEnabled }, null);
    }
}

I also created a SelectableTextBlock derived from TextBlock that takes the steps noted above:

public class SelectableTextBlock : TextBlock
{
    static SelectableTextBlock()
    {
        FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
        TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);

        // remove the focus rectangle around the control
        FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
    }

    private readonly TextEditorWrapper _editor;

    public SelectableTextBlock()
    {
        _editor = TextEditorWrapper.CreateFor(this);
    }
}

Another option would be to create an attached property for TextBlock to enable text selection on demand. In this case, to disable the selection again, one needs to detach a TextEditor by using the reflection equivalent of this code:

_editor.TextContainer.TextView = null;
_editor.OnDetach();
_editor = null;

Default optional parameter in Swift function

Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How to write ternary operator condition in jQuery?

Also, the ternary operator expects expressions, not statements. Do not use semicolons, only at the end of the ternary op.

$("#blackbox").css({'background': 
    $("#blackbox").css('background') === 'pink' ? 'black' : 'pink'});

Flexbox not working in Internet Explorer 11

According to Flexbugs:

In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

Here are a couple of workarounds:

1. Always fill the viewport + scrollable <aside> and <section>:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1;
  display: flex;
}

aside, section {
  overflow: auto;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

2. Fill the viewport initially + normal page scroll with more content:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1 0 auto;
  display: flex;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

Keep values selected after form submission

JavaScript only solution:

var tmpParams = decodeURIComponent(window.location.search.substr(1)).split("&");
for (var i = 0; i < tmpParams.length; i++) {
    var tmparr = tmpParams[i].split("=");
    var tmp = document.getElementsByName(tmparr[0])[0];
    if (!!tmp){
        document.getElementsByName(tmparr[0])[0].value = tmparr[1];
    }
}

Or if you are using jQuery you can replace

 var tmp = document.getElementsByName(tmparr[0])[0];
 if (!!tmp){
     document.getElementsByName(tmparr[0])[0].value = tmparr[1];
 }

with:

 $('*[name="'+tmparr[0]+'"]').val(tmparr[1]);

Vue.js get selected option on @change

@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function

<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

function onChange(value) {
  console.log(value);
}

If you want to call Vue methods, do it like this-

<select name="LeaveType" @change="onChange($event)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
  ...
  ...
  methods:{
    onChange:function(event){
       console.log(event.target.value);
    }
  }
})

You can use v-model data attribute on the select element to bind the value.

<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
    data:{
        selectedValue : 1, // First option will be selected by default
    },
    ...
    ...
    methods:{
        onChange:function(event){
            console.log(this.selectedValue);
        }
    }
})

Hope this Helps :-)

What order are the Junit @Before/@After called?

One potential gotcha that has bitten me before:

I like to have at most one @Before method in each test class, because order of running the @Before methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest().

But, although @Before is documented as The @Before methods of superclasses will be run before those of the current class. No other ordering is defined., this only applies if each method marked with @Before has a unique name in the class hierarchy.

For example, I had the following:

public class AbstractFooTest {
  @Before
  public void setUpTest() { 
     ... 
  }
}

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() { 
    ...
  }
}

I expected AbstractFooTest.setUpTest() to run before FooTest.setUpTest(), but only FooTest.setupTest() was executed. AbstractFooTest.setUpTest() was not called at all.

The code must be modified as follows to work:

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() {
    super.setUpTest();
    ...
  }
}

MySQL Insert query doesn't work with WHERE clause

DO READ THIS AS WELL

It doesn't make sense... even literally

INSERT means add a new row and when you say WHERE you define which row are you talking about in the SQL.

So adding a new row is not possible with a condition on an existing row.

You have to choose from the following:

A. Use UPDATE instead of INSERT

B. Use INSERT and remove WHERE clause ( I am just saying it...) or if you are real bound to use INSERT and WHERE in a single statement it can be done only via INSERT..SELECT clause...

INSERT INTO Users( weight, desiredWeight ) 
SELECT FROM Users WHERE id = 1;

But this serves an entirely different purpose and if you have defined id as Primary Key this insert will be failure, otherwise a new row will be inserted with id = 1.

Regular expression to find two strings anywhere in input

(.* word1.* word2.* )|(.* word2.* word1.*)

Simple linked list in C++

head is defined inside the main as follows.

struct Node *head = new Node;

But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.

Make the declaration of the head as global and do not pass it to functions.

The functions should be as follows.

void initNode(int n){
    head->x = n;
    head->next = NULL;
}

void addNode(int n){
    struct Node *NewNode = new Node;
    NewNode-> x = n;
    NewNode->next = head;
    head = NewNode;
}

Practical uses for the "internal" keyword in C#

How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.

Comments are welcome about this approach.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

Swift: print() vs println() vs NSLog()

To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.

From Apple:

The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.

Apple highly recommends using os_log going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.

Performance of Activity Tracing, now part of the new Unified Logging system

You can learn more about this in details here.

To sum it up: use print() for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log) as much as possible for everything else.

Can't accept license agreement Android SDK Platform 24

For me I was Building the Ionic using "ionic build android" command and I was getting the same problem! The solution was simply

  • To install the required sdk
  • Run the same command in CMD must be as administrater

React - Display loading screen while DOM is rendering?

You can easily do that by using lazy loading in react. For that you have to use lazy and suspense from react like that.

import React, { lazy, Suspense } from 'react';

const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
  const LazyComponent = lazy(importFunc);

  return props => (
    <Suspense fallback={fallback}>
      <LazyComponent {...props} />
    </Suspense>
  );
};

export default loadable;

After that export your components like this.

export const TeacherTable = loadable(() =>
  import ('./MainTables/TeacherTable'), {
    fallback: <Loading />,
  });

And then in your routes file use it like this.

 <Route exact path="/app/view/teachers" component={TeacherTable} />

Thats it now you are good to go everytime your DOM is rendering your Loading compnent will be displayed as we have specified in the fallback property above. Just make sure that you do any ajax request only in componentDidMount()

OnItemCLickListener not working in listview

Android:autoText attribute also makes TextView auto focusable.

When do you use Java's @Override annotation and why?

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Getting Excel to refresh data on sheet from within VBA

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

How to get the ASCII value in JavaScript for the characters

Here is the example:

_x000D_
_x000D_
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
_x000D_
_x000D_

Or if you have longer strings:

_x000D_
_x000D_
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
  console.log(string.charCodeAt(i));_x000D_
}
_x000D_
_x000D_
_x000D_

String.charCodeAt(x) method will return ASCII character code at a given position.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Adding new line of data to TextBox

Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

What is the difference between atan and atan2 in C++?

atan(x) Returns the principal value of the arc tangent of x, expressed in radians.

atan2(y,x) Returns the principal value of the arc tangent of y/x, expressed in radians.

Notice that because of the sign ambiguity, a function cannot determine with certainty in which quadrant the angle falls only by its tangent value (atan alone). You can use atan2 if you need to determine the quadrant.

How can I create numbered map markers in Google Maps V3?

I did this using a solution similar to @ZuzEL.

Instead of use the default solution (http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000), you can create these images as you wish, using JavaScript, without any server-side code.

Google google.maps.Marker accepts Base64 for its icon property. With this we can create a valid Base64 from a SVG.

enter image description here

You can see the code to produce the same as this image in this Plunker: http://plnkr.co/edit/jep5mVN3DsVRgtlz1GGQ?p=preview

_x000D_
_x000D_
var markers = [_x000D_
  [1002, -14.2350040, -51.9252800],_x000D_
  [2000, -34.028249, 151.157507],_x000D_
  [123, 39.0119020, -98.4842460],_x000D_
  [50, 48.8566140, 2.3522220],_x000D_
  [22, 38.7755940, -9.1353670],_x000D_
  [12, 12.0733335, 52.8234367],_x000D_
];_x000D_
_x000D_
function initializeMaps() {_x000D_
  var myLatLng = {_x000D_
    lat: -25.363,_x000D_
    lng: 131.044_x000D_
  };_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 4,_x000D_
    center: myLatLng_x000D_
  });_x000D_
_x000D_
  var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
  markers.forEach(function(point) {_x000D_
    generateIcon(point[0], function(src) {_x000D_
      var pos = new google.maps.LatLng(point[1], point[2]);_x000D_
_x000D_
      bounds.extend(pos);_x000D_
_x000D_
      new google.maps.Marker({_x000D_
        position: pos,_x000D_
        map: map,_x000D_
        icon: src_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
_x000D_
  map.fitBounds(bounds);_x000D_
}_x000D_
_x000D_
var generateIconCache = {};_x000D_
_x000D_
function generateIcon(number, callback) {_x000D_
  if (generateIconCache[number] !== undefined) {_x000D_
    callback(generateIconCache[number]);_x000D_
  }_x000D_
_x000D_
  var fontSize = 16,_x000D_
    imageWidth = imageHeight = 35;_x000D_
_x000D_
  if (number >= 1000) {_x000D_
    fontSize = 10;_x000D_
    imageWidth = imageHeight = 55;_x000D_
  } else if (number < 1000 && number > 100) {_x000D_
    fontSize = 14;_x000D_
    imageWidth = imageHeight = 45;_x000D_
  }_x000D_
_x000D_
  var svg = d3.select(document.createElement('div')).append('svg')_x000D_
    .attr('viewBox', '0 0 54.4 54.4')_x000D_
    .append('g')_x000D_
_x000D_
  var circles = svg.append('circle')_x000D_
    .attr('cx', '27.2')_x000D_
    .attr('cy', '27.2')_x000D_
    .attr('r', '21.2')_x000D_
    .style('fill', '#2063C6');_x000D_
_x000D_
  var path = svg.append('path')_x000D_
    .attr('d', 'M27.2,0C12.2,0,0,12.2,0,27.2s12.2,27.2,27.2,27.2s27.2-12.2,27.2-27.2S42.2,0,27.2,0z M6,27.2 C6,15.5,15.5,6,27.2,6s21.2,9.5,21.2,21.2c0,11.7-9.5,21.2-21.2,21.2S6,38.9,6,27.2z')_x000D_
    .attr('fill', '#FFFFFF');_x000D_
_x000D_
  var text = svg.append('text')_x000D_
    .attr('dx', 27)_x000D_
    .attr('dy', 32)_x000D_
    .attr('text-anchor', 'middle')_x000D_
    .attr('style', 'font-size:' + fontSize + 'px; fill: #FFFFFF; font-family: Arial, Verdana; font-weight: bold')_x000D_
    .text(number);_x000D_
_x000D_
  var svgNode = svg.node().parentNode.cloneNode(true),_x000D_
    image = new Image();_x000D_
_x000D_
  d3.select(svgNode).select('clippath').remove();_x000D_
_x000D_
  var xmlSource = (new XMLSerializer()).serializeToString(svgNode);_x000D_
_x000D_
  image.onload = (function(imageWidth, imageHeight) {_x000D_
    var canvas = document.createElement('canvas'),_x000D_
      context = canvas.getContext('2d'),_x000D_
      dataURL;_x000D_
_x000D_
    d3.select(canvas)_x000D_
      .attr('width', imageWidth)_x000D_
      .attr('height', imageHeight);_x000D_
_x000D_
    context.drawImage(image, 0, 0, imageWidth, imageHeight);_x000D_
_x000D_
    dataURL = canvas.toDataURL();_x000D_
    generateIconCache[number] = dataURL;_x000D_
_x000D_
    callback(dataURL);_x000D_
  }).bind(this, imageWidth, imageHeight);_x000D_
_x000D_
  image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function(match, p1) {_x000D_
    return String.fromCharCode('0x' + p1);_x000D_
  }));_x000D_
}_x000D_
_x000D_
initializeMaps();
_x000D_
#map_canvas {_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link rel="stylesheet" href="style.css">_x000D_
    _x000D_
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>_x000D_
    _x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="map_canvas"></div>_x000D_
  </body>_x000D_
  _x000D_
  <script src="script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In this demo I create the SVG using D3.js, then transformed SVG to Canvas, so I can resize the image as I want and after that I get Base64 from canvas' toDataURL method.

All this demo was based on my fellow @thiago-mata code. Kudos for him.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

I also had this issue. Initially, a proxy was set and work fine. Then I connected to a network where it doesn't go through a proxy. After unsetting proxy pip again get works.

unset http_proxy; unset http_prox;  unset HTTP_PROXY; unset HTTPS_PROXY

Get model's fields in Django

As per the django documentation 2.2 you can use:

To get all fields: Model._meta.get_fields()

To get an individual field: Model._meta.get_field('field name')

ex. Session._meta.get_field('expire_date')

Excel formula to reference 'CELL TO THE LEFT'

Why not just use:

=ADDRESS(ROW(),COLUMN()-1)

How to display request headers with command line curl

the -v option for curl is too verbose in the error output which contains the leading *(status line) or >(request head field) or <(response head field). to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '>' | cut -c1-2 --complement

to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '<' | cut -c1-2 --complement

or to dump it into /tmp/test.txt file with the -D option

curl -D /tmp/test.txt -sS www.stackoverflow.com > /dev/null

in order to filter the -v output, you should direct the error output to terminal and the std output to /dev/null, the -s option is to forbid the progress metering

HttpListener Access Denied

I also faced similar problem.If you have already reserved url then you have to first delete the url to run in non admin mode else it will fail with Access is Denied error.

netsh http delete urlacl url=http://+:80

How do you set a JavaScript onclick event to a class with css

Here is my solution through CSS, It does not use any JavaScript at all

HTML:

<a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
        <div>   <a href="#close" title="Close" class="close">X</a>

                <h2>Modal Box</h2>

            <p>This is a sample modal box that can be created using the powers of CSS3.</p>
            <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
        </div>
    </div>

CSS:

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}
.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}
.close:hover {
    background: #00d9ff;
}

CSS alert No JavaScript Just pure HTML and CSS

I believe that it will do the trick for you as it has for me

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

Convert a string representation of a hex dump to a byte array using Java?

I know this is a very old thread, but still like to add my penny worth.

If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.

public static byte[] hexToBinary(String s){

  /*
   * skipped any input validation code
   */

  byte[] data = new byte[s.length()/2];

  for( int i=0, j=0; 
       i<s.length() && j<data.length; 
       i+=2, j++)
  {
     data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);
  }

  return data;
}

How to Insert Double or Single Quotes

Assuming your data is in column A, add a formula to column B

="'" & A1 & "'" 

and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.

Adb Devices can't find my phone

I did the following to get my Mac to see the devices again:

  • Run android update adb
  • Run adb kill-server
  • Run adb start-server

At this point, calling adb devices started returning devices again. Now run or debug your project to test it on your device.

How to add CORS request in header in Angular 5

Make the header looks like this for HttpClient in NG5:

let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'apikey': this.apikey,
        'appkey': this.appkey,
      }),
      params: new HttpParams().set('program_id', this.program_id)
    };

You will be able to make api call with your localhost url, it works for me ..

  • Please never forget your params columnd in the header: such as params: new HttpParams().set('program_id', this.program_id)

Only allow specific characters in textbox

You need to subscribe to the KeyDown event on the text box. Then something like this:

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
       && !char.IsDigit(e.KeyChar) 
       && e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
       && e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*' 
       && e.KeyChar != '/')
    {
        e.Handled = true;
        return;
    }
    e.Handled=false;
    return;
}

The important thing to know is that if you changed the Handled property to true, it will not process the keystroke. Setting it to false will.

jQuery add required to input fields

Using .attr method

.attr(attribute,value); // syntax

.attr("required", true);
// required="required"

.attr("required", false);
// 

Using .prop

.prop(property,value) // syntax

.prop("required", true);
// required=""

.prop("required", false);
//

Read more from here

https://stackoverflow.com/a/5876747/5413283

Why is nginx responding to any domain name?

The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.

So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.

This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.

# Default server
server {
    return 404;
}

server {
    server_name domain_1;
    [...]
}

server {
    server_name domain_2;
    [...]
}

etc

** EDIT **

It seems some users are a bit confused by this example and think it is limited to a single conf file etc.

Please note that the above is a simple example for the OP to develop as required.

I personally use separate vhost conf files with this as so (CentOS/RHEL):

http {
    [...]
    # Default server
    server {
        return 404;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf.d/ will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.

The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.

In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.

In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.

However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.

This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.

I resolve this by creating a default server for Port 8080 to redirect such requests.

http {
    [...]
    # Default server block for undefined domains
    server {
        listen 80;
        return 404;
    }
    # Default server block to redirect Port 8080 for all domains
    server {
        listen my.external.ip.addr:8080;
        return 301 http://$host$request_uri;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.

I actually have four of such server blocks and this is a simplified use case.

MySQL: How to add one day to datetime field in query

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

Or, simplier:

date("Y-m-d H:i:s", time()+((60*60)*24));

Moving Panel in Visual Studio Code to right side

Click menu option View > Appearance > Move to Side Bar Right. Once side bar moves to right, option "Move Side Bar Right" changes to "Move to Side Bar Left".

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

How to establish a connection pool in JDBC?

As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.

Regarding your doubt

Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How to set dialog to show in full screen?

EDIT Until such time as StackOverflow allows us to version our answers, this is an answer that works for Android 3 and below. Please don't downvote it because it's not working for you now, because it definitely works with older Android versions.


You should only need to add one line to your onCreateDialog() method:

@Override
protected Dialog onCreateDialog(int id) {
    //all other dialog stuff (which dialog to display)

    //this line is what you need:
    dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);

    return dialog;
}

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

This error message can also occur if the account you are using to access the SQL server is locked out by the domain.

How to use `replace` of directive definition?

You are getting confused with transclude: true, which would append the inner content.

replace: true means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1> tag.

http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview

For example without replace:true

<div myd1><span class="replaced" myd1="">directive template1</span></div>

and with replace:true

<span class="replaced" myd1="">directive template1</span>

As you can see in the latter example, the div tag is indeed replaced.

Alternative Windows shells, besides CMD.EXE?

Try Clink. It's awesome, especially if you are used to bash keybindings and features.

(As already pointed out - there is a similar question: Is there a better Windows Console Window?)

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Also try directly startup:

sqlplus /nolog
conn / as sysdba
startup

What is the difference between a schema and a table and a database?

More on schemas:

In SQL 2005 a schema is a way to group objects. It is a container you can put objects into. People can own this object. You can grant rights on the schema.

In 2000 a schema was equivalent to a user. Now it has broken free and is quite useful. You could throw all your user procs in a certain schema and your admin procs in another. Grant EXECUTE to the appropriate user/role and you're through with granting EXECUTE on specific procedures. Nice.

The dot notation would go like this:

Server.Database.Schema.Object

or

myserver01.Adventureworks.Accounting.Beans

How to view the assembly behind the code using Visual C++?

Specify the /FA switch for the cl compiler. Depending on the value of the switch either only assembly code or high-level code and assembly code is integrated. The filename gets .asm file extension. Here are the supported values:


  • /FA Assembly code; .asm
  • /FAc Machine and assembly code; .cod
  • /FAs Source and assembly code; .asm
  • /FAcs Machine, source, and assembly code; .cod

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I had a similar situation. I am using TFS for source code control. What I found is that when it was checked in, it made the files readonly. This caused the above error in my service where it was opening them read/write. Once I checked them out for edit. Everything worked great. I am considering trying opening them readonly in the service. I think that once they get published to the production server, this is not an issue. Only in the development environment. I have seen similar issues with Services that use Entity Framework. If the .svc file is checked in, you can't do updates to the database through EF.

How to Specify "Vary: Accept-Encoding" header in .htaccess

Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS codes and learn what they do.

You can use:

Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"

php resize image on upload

If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();

How to enable CORS in AngularJs

I had a similar problem and for me it boiled down to adding the following HTTP headers at the response of the receiving end:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

You may prefer not to use the * at the end, but only the domainname of the host sending the data. Like *.example.com

But this is only feasible when you have access to the configuration of the server.

Node.js - get raw request body using Express

This solution worked for me:

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));

When I use solution with req.on('data', function(chunk) { }); it not working on chunked request body.

CSS image overlay with color and transparency

Have you given a try to Webkit Filters?

You can manipulate not only opacity, but colour, brightness, luminosity and other properties:

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Update August 20, 2020 -- Now is simple!

from selenium.webdriver.support.ui import WebDriverWait

chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True

self.driver = webdriver.Chrome(
            executable_path=DRIVER_PATH, chrome_options=chrome_options)

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

How to convert a time string to seconds?

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

Input type=password, don't let browser remember the password

Try using autocomplete="off". Not sure if every browser supports it, though. MSDN docs here.

EDIT: Note: most browsers have dropped support for this attribute. See Is autocomplete="off" compatible with all modern browsers?

This is arguably something that should be left up to the user rather than the web site designer.

How do I disable "missing docstring" warnings at a file-level in Pylint?

I came looking for an answer because, as cerin said, in Django projects it is cumbersome and redundant to add module docstrings to every one of the files that Django automatically generates when creating a new application.

So, as a workaround for the fact that Pylint doesn't let you specify a difference in docstring types, you can do this:

pylint */*.py --msg-template='{path}: {C}:{line:3d},{column:2d}: {msg}' | grep docstring | grep -v module

You have to update the msg-template, so that when you grep you will still know the file name. This returns all the other missing-docstring types excluding modules.

Then you can fix all of those errors, and afterwards just run:

pylint */*.py --disable=missing-docstring

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC????
 * 
 * @author ??([email protected])
 *
 */
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Hello I have adapted Winista.MimeDetect project into .net core/framework with fallback into urlmon.dll Fell free to use it: nuget package.

   //init
   var mimeTypes = new MimeTypes();

   //usage by filepath
   var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);

How to change navbar/container width? Bootstrap 3

I just solved this issue myself. You were on the right track.

@media (min-width: 1200px) {
    .container{
        max-width: 970px;
    }
}

Here we say: On viewports 1200px or larger - set container max-width to 970px. This will overwrite the standard class that currently sets max-width to 1170px for that range.

NOTE: Make sure you include this AFTER the bootstrap.css stuff (everyone has made this little mistake in the past).

Hope this helps.. good luck!

How can I disable a button on a jQuery UI dialog?

You can also use the not now documented disabled attribute:

$("#element").dialog({
    buttons: [
    {
        text: "Confirm",
        disabled: true,
        id: "my-button-1"
    }, 
    {
        text: "Cancel",
        id: "my-button-2",
        click: function(){            
               $(this).dialog("close");
        }  

    }]
});

To enable after dialog has opened, use:

$("#my-button-1").attr('disabled', false);

JsFiddle: http://jsfiddle.net/xvt96e1p/4/

New og:image size for Facebook share?

Facebook.com og:image is 325x325 (1:1 aspect ratio, square)

https://www.facebook.com/images/fb_icon_325x325.png

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

Cleanest way to toggle a boolean variable in Java?

theBoolean ^= true;

Fewer keystrokes if your variable is longer than four letters

Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.

How to find the Center Coordinate of Rectangle?

We can calculate using mid point of line formula,

centre (x,y) =  new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)

Check if a column contains text using SQL

Try LIKE construction, e.g. (assuming StudentId is of type Char, VarChar etc.)

  select * 
    from Students
   where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain

Get HTML inside iframe using jQuery

var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();

Javascript ES6/ES5 find in array and change

An other approach is to use splice.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

N.B : In case you're working with reactive frameworks, it will update the "view", your array "knowing" you've updated it.

Answer :

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

let foundIndex = items.findIndex(element => element.id === item.id)
items.splice(foundIndex, 1, item)

And in case you want to only change a value of an item, you can use find function :

// Retrieve item and assign ref to updatedItem
let updatedItem = items.find((element) => { return element.id === item.id })

// Modify object property
updatedItem.aProp = ds.aProp

Couldn't connect to server 127.0.0.1:27017

1.Create new folder in d drive D:/data/db

2.Open terminal on D:/data/db

3.Type mongod and enter.

4.Type mongo and enter.

and your mongodb has strated............

Changing the interval of SetInterval while it's running

I'm a beginner in javascript, and didn't found any help in the previous answers (but many good ideas).
This piece of code below accelerates (acceleration > 1) or decelerates (acceleration <1). I hope it might help some people:

function accelerate(yourfunction, timer, refresh, acceleration) {
    var new_timer = timer / acceleration;
    var refresh_init = refresh;//save this user defined value
    if (refresh < new_timer ){//avoid reseting the interval before it has produced anything.
        refresh = new_timer + 1 ;
    };
    var lastInter = setInterval(yourfunction, new_timer);
    console.log("timer:", new_timer);
    function stopLastInter() {
        clearInterval(lastInter);
        accelerate(yourfunction, new_timer, refresh_init, acceleration);
        console.log("refresh:", refresh);
    };
    setTimeout(stopLastInter, refresh);
}

With :

  • timer: the setInterval initial value in ms (increasing or decreasing)
  • refresh: the time before a new value of timer is calculated. This is the step lenght
  • factor: the gap between the old and the next timer value. This is the step height

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

Exit Shell Script Based on Process Exit Code

In Bash this is easy. Just tie them together with &&:

command1 && command2 && command3

You can also use the nested if construct:

if command1
   then
       if command2
           then
               do_something
           else
               exit
       fi
   else
       exit
fi

Detect Close windows event by jQuery

You can solve this problem with vanilla-Js:

Unload Basics

If you want to prompt or warn your user that they're going to close your page, you need to add code that sets .returnValue on a beforeunload event:

    window.addEventListener('beforeunload', (event) => {
      event.returnValue = `Are you sure you want to leave?`;
    });

There's two things to remember.

  1. Most modern browsers (Chrome 51+, Safari 9.1+ etc) will ignore what you say and just present a generic message. This prevents webpage authors from writing egregious messages, e.g., "Closing this tab will make your computer EXPLODE! ".

  2. Showing a prompt isn't guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn't interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should not be able to prompt you that it's closing.

Optionally Show

You can add a simple condition to control whether to prompt your user by checking something within the event handler. This is fairly basic good practice, and could work well if you're just trying to warn a user that they've not finished filling out a single static form. For example:

    let formChanged = false;
    myForm.addEventListener('change', () => formChanged = true);
    window.addEventListener('beforeunload', (event) => {
      if (formChanged) {
        event.returnValue = 'You have unfinished changes!';
      }
    });

But if your webpage or webapp is reasonably complex, these kinds of checks can get unwieldy. Sure, you can add more and more checks, but a good abstraction layer can help you and have other benefits—which I'll get to later. ???


Promises

So, let's build an abstraction layer around the Promise object, which represents the future result of work- like a response from a network fetch().

The traditional way folks are taught promises is to think of them as a single operation, perhaps requiring several steps- fetch from the server, update the DOM, save to a database. However, by sharing the Promise, other code can leverage it to watch when it's finished.

Pending Work

Here's an example of keeping track of pending work. By calling addToPendingWork with a Promise—for example, one returned from fetch()—we'll control whether to warn the user that they're going to unload your page.

    const pendingOps = new Set();

    window.addEventListener('beforeunload', (event) => {
      if (pendingOps.size) {
        event.returnValue = 'There is pending work. Sure you want to leave?';
      }
    });

    function addToPendingWork(promise) {
      pendingOps.add(promise);
      const cleanup = () => pendingOps.delete(promise);
      promise.then(cleanup).catch(cleanup);
    }

Now, all you need to do is call addToPendingWork(p) on a promise, maybe one returned from fetch(). This works well for network operations and such- they naturally return a Promise because you're blocked on something outside the webpage's control.

more detail can view in this url:

https://dev.to/chromiumdev/sure-you-want-to-leavebrowser-beforeunload-event-4eg5

Hope that can solve your problem.

failed to lazily initialize a collection of role

It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:

public List<Node> getAll() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
    return  query.list();
}

Where your class has 2 sets like:

public class Node implements Serializable {

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;

}

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

Credit card expiration dates - Inclusive or exclusive?

How do time zones factor in this analysis. Does a card expire in New York before California? Does it depend on the billing or shipping addresses?

How to check Elasticsearch cluster health?

You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:

$ curl -XGET 'localhost:9200/_cluster/health?pretty'

This will give you the status and other related data you need.

{
 "cluster_name" : "xxxxxxxx",
 "status" : "green",
 "timed_out" : false,
 "number_of_nodes" : 2,
 "number_of_data_nodes" : 2,
 "active_primary_shards" : 15,
 "active_shards" : 12,
 "relocating_shards" : 0,
 "initializing_shards" : 0,
 "unassigned_shards" : 0,
 "delayed_unassigned_shards" : 0,
 "number_of_pending_tasks" : 0,
 "number_of_in_flight_fetch" : 0
}

How to add button inside input

Use a Flexbox, and put the border on the form.

The best way to do this now (2019) is with a flexbox.

  • Put the border on the containing element (in this case I've used the form, but you could use a div).
  • Use a flexbox layout to arrange the input and the button side by side. Allow the input to stretch to take up all available space.
  • Now hide the input by removing its border.

Run the snippet below to see what you get.

_x000D_
_x000D_
form {_x000D_
  /* This bit sets up the horizontal layout */_x000D_
  display:flex;_x000D_
  flex-direction:row;_x000D_
  _x000D_
  /* This bit draws the box around it */_x000D_
  border:1px solid grey;_x000D_
_x000D_
  /* I've used padding so you can see the edges of the elements. */_x000D_
  padding:2px;_x000D_
}_x000D_
_x000D_
input {_x000D_
  /* Tell the input to use all the available space */_x000D_
  flex-grow:2;_x000D_
  /* And hide the input's outline, so the form looks like the outline */_x000D_
  border:none;_x000D_
}_x000D_
_x000D_
input:focus {_x000D_
  /* removing the input focus blue box. Put this on the form if you like. */_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
button {_x000D_
  /* Just a little styling to make it pretty */_x000D_
  border:1px solid blue;_x000D_
  background:blue;_x000D_
  color:white;_x000D_
}
_x000D_
<form>_x000D_
  <input />_x000D_
  <button>Go</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Why this is good

  • It will stretch to any width.
  • The button will always be just as big as it needs to be. It won't stretch if the screen is wide, or shrink if the screen is narrow.
  • The input text will not go behind the button.

Caveats and Browser Support

There's limited Flexbox support in IE9, so the button will not be on the right of the form. IE9 has not been supported by Microsoft for some years now, so I'm personally quite comfortable with this.

I've used minimal styling here. I've left in the padding to show the edges of things. You can obviously make this look however you want it to look with rounded corners, drop shadows, etc..

How to set selected value on select using selectpicker plugin from bootstrap

$('selector').selectpicker('val',value);

in place of selector you can give you selector either class or id for example: $('#mySelect').selectpicker('val',your_value)

What is an attribute in Java?

Attributes are also data members and properties of a class. They are Variables declared inside class.

What is the difference between char * const and const char *?

I presume you mean const char * and char * const .

The first, const char *, is a pointer to a constant character. The pointer itself is mutable.

The second, char * const is a constant pointer to a character. The pointer cannot change, the character it points to can.

And then there is const char * const where the pointer and character cannot change.

How print out the contents of a HashMap<String, String> in ascending order based on its values?

the simplest and shortest code i think is this:

public void listPrinter(LinkedHashMap<String, String> caseList) {

    for(Entry entry:caseList.entrySet()) {
        System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
    }
}

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

How to convert a multipart file to File?

if you don't want to use MultipartFile.transferTo(). You can write file like this

    val dir = File(filePackagePath)
    if (!dir.exists()) dir.mkdirs()

    val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
        createNewFile()
    }

    FileOutputStream(file).use {
        it.write(multipartFile.bytes)
    }

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

Catch checked change event of a checkbox

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>

How to make circular background using css?

If you want to do it with only 1 element, you can use the ::before and ::after pseudo elements for the same div instead of a wrapper.
See http://css-tricks.com/pseudo-element-roundup/

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.

:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

How to check if a network port is open on linux?

Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except

>>> def port_check(ip_port):
...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...     s.settimeout(1)
...     r = s.connect_ex(ip_port)
...     return r == 0
... 
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>> 

flutter remove back button on appbar

You can remove the back button by passing an empty new Container() as the leading argument to your AppBar.

If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed, try calling Navigator.pushReplacementNamed to cause the earlier route to disappear.

The function pushReplacementNamed will remove the previous route in the backstack and replace it with the new route.

Full code sample for the latter is below.

import 'package:flutter/material.dart';

class LogoutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Logout Page"),
      ),
      body: new Center(
        child: new Text('You have been logged out'),
      ),
    );
  }

}
class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Remove Back Button"),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.fullscreen_exit),
        onPressed: () {
          Navigator.pushReplacementNamed(context, "/logout");
        },
      ),
    );
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      routes: {
        "/logout": (_) => new LogoutPage(),
      },
    );
  }
}

Adding elements to a C# array

Use List<string> instead of string[].

List allows you to add and remove items with good performance.

Count number of columns in a table row

Count all td in table1:

_x000D_
_x000D_
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Count all td into each tr of table1.

_x000D_
_x000D_
table1.querySelectorAll("tr").forEach(function(e){_x000D_
 console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Sorting by date & time in descending order?

I used a simpler solution found partly here:
How to sort details with Date and time in sql server ?
I used this query to get my results:

SELECT TOP (5) * FROM My_Table_Name WHERE id=WhateverValueINeed ORDER BY DateTimeColumnName DESC

This is more straight forward and worked for me.

Notice: the column of the Date has the "datetime" type

How do I sort a two-dimensional (rectangular) array in C#?

This is an old question, but here's a class I just built based on the article from Jim Mischel at InformIt linked by Doug L.

class Array2DSort : IComparer<int>
{
    // maintain a reference to the 2-dimensional array being sorted
    string[,] _sortArray;
    int[] _tagArray;
    int _sortIndex;

    protected string[,] SortArray { get { return _sortArray; } }

    // constructor initializes the sortArray reference
    public Array2DSort(string[,] theArray, int sortIndex)
    {
        _sortArray = theArray;
        _tagArray = new int[_sortArray.GetLength(0)];
        for (int i = 0; i < _sortArray.GetLength(0); ++i) _tagArray[i] = i;
        _sortIndex = sortIndex;
    }

    public string[,] ToSortedArray()
    {
        Array.Sort(_tagArray, this);
        string[,] result = new string[
            _sortArray.GetLength(0), _sortArray.GetLength(1)];
        for (int i = 0; i < _sortArray.GetLength(0); i++)
        {
            for (int j = 0; j < _sortArray.GetLength(1); j++)
            {
                result[i, j] = _sortArray[_tagArray[i], j];
            }
        }
        return result;
    }

    // x and y are integer row numbers into the sortArray
    public virtual int Compare(int x, int y)
    {
        if (_sortIndex < 0) return 0;
        return CompareStrings(x, y, _sortIndex);
    }

    protected int CompareStrings(int x, int y, int col)
    {
        return _sortArray[x, col].CompareTo(_sortArray[y, col]);
    }
}

Given an unsorted 2D array data of arbitrary size that you want to sort on column 5 you just do this:

        Array2DSort comparer = new Array2DSort(data, 5);
        string[,] sortedData = comparer.ToSortedArray();

Note the virtual Compare method and protected SortArray so you can create specialized subclasses that always sort on a particular column or do specialized sorting on multiple columns or whatever you want to do. That's also why CompareStrings is broken out and protected - any subclasses can use it for simple comparisons instead of typing out the full SortArray[x, col].CompareTo(SortArray[y, col]) syntax.

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

Get local IP address

Tested with one or multiple LAN cards and Virtual machines

public static string DisplayIPAddresses()
    {
        string returnAddress = String.Empty;

        // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface network in networkInterfaces)
        {
            // Read the IP configuration for each network
            IPInterfaceProperties properties = network.GetIPProperties();

            if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
                   network.OperationalStatus == OperationalStatus.Up &&
                   !network.Description.ToLower().Contains("virtual") &&
                   !network.Description.ToLower().Contains("pseudo"))
            {
                // Each network interface may have multiple IP addresses
                foreach (IPAddressInformation address in properties.UnicastAddresses)
                {
                    // We're only interested in IPv4 addresses for now
                    if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                        continue;

                    // Ignore loopback addresses (e.g., 127.0.0.1)
                    if (IPAddress.IsLoopback(address.Address))
                        continue;

                    returnAddress = address.Address.ToString();
                    Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");
                }
            }
        }

       return returnAddress;
    }

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

Disable password authentication for SSH

I followed these steps (for Mac).

In /etc/ssh/sshd_config change

#ChallengeResponseAuthentication yes
#PasswordAuthentication yes

to

ChallengeResponseAuthentication no
PasswordAuthentication no

Now generate the RSA key:

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

(For me an RSA key worked. A DSA key did not work.)

A private key will be generated in ~/.ssh/id_rsa along with ~/.ssh/id_rsa.pub (public key).

Now move to the .ssh folder: cd ~/.ssh

Enter rm -rf authorized_keys (sometimes multiple keys lead to an error).

Enter vi authorized_keys

Enter :wq to save this empty file

Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Restart the SSH:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

How do I count unique visitors to my site?

I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.

I added this code to his script at the top of the function:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

Afther that I edited his code.

Find the line that says the following:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

and replace it with this:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

This will work.

Here is the full code if anything happens:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

Haven't tested this on the Sql script yet.

SQL WHERE.. IN clause multiple columns

Why use WHERE EXISTS or DERIVED TABLES when you can just do a normal inner join:

SELECT t.*
FROM table1 t
INNER JOIN CRM_VCM_CURRENT_LEAD_STATUS s
    ON t.CM_PLAN_ID = s.CM_PLAN_ID
    AND t.Individual_ID = s.Individual_ID
WHERE s.Lead_Key = :_Lead_Key

If the pair of (CM_PLAN_ID, Individual_ID) isn't unique in the status table, you might need a SELECT DISTINCT t.* instead.

How to change fontFamily of TextView in Android

You can do it easy way by using following library

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

its light weight and easy to implement, just copy your fonts in asset folder and use name in xml.

Assign keyboard shortcut to run procedure

Write a vba proc like:

Sub E_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
    Range("AG" & (ActiveCell.Row)).Select 'go to column AG in the same row
End Sub

then go to developer tab, macros, select the macro, click options, then add a shortcut letter or button.

Split array into two parts without for loop in java

You can use System.arraycopy().

int[] source = new int[1000];

int[] part1 = new int[500];
int[] part2 = new int[500];

//              (src   , src-offset  , dest , offset, count)
System.arraycopy(source, 0           , part1, 0     , part1.length);
System.arraycopy(source, part1.length, part2, 0     , part2.length);

Pointer to class data member "::*"

One way I've used it is if I have two implementations of how to do something in a class and I want to choose one at run-time without having to continually go through an if statement i.e.

class Algorithm
{
public:
    Algorithm() : m_impFn( &Algorithm::implementationA ) {}
    void frequentlyCalled()
    {
        // Avoid if ( using A ) else if ( using B ) type of thing
        (this->*m_impFn)();
    }
private:
    void implementationA() { /*...*/ }
    void implementationB() { /*...*/ }

    typedef void ( Algorithm::*IMP_FN ) ();
    IMP_FN m_impFn;
};

Obviously this is only practically useful if you feel the code is being hammered enough that the if statement is slowing things done eg. deep in the guts of some intensive algorithm somewhere. I still think it's more elegant than the if statement even in situations where it has no practical use but that's just my opnion.

How to implement the --verbose or -v option into a script?

What I need is a function which prints an object (obj), but only if global variable verbose is true, else it does nothing.

I want to be able to change the global parameter "verbose" at any time. Simplicity and readability to me are of paramount importance. So I would proceed as the following lines indicate:

ak@HP2000:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> verbose = True
>>> def vprint(obj):
...     if verbose:
...         print(obj)
...     return
... 
>>> vprint('Norm and I')
Norm and I
>>> verbose = False
>>> vprint('I and Norm')
>>> 

Global variable "verbose" can be set from the parameter list, too.

Setting focus to a textbox control

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    TextBox1.Select()
End Sub

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

****Following solution is working for me**** Manually deleted all files from C:\Users\Admin.gradle\wrapper\dists\

where Admin is my user name