Programs & Examples On #Datagridviewcolumn

Search for value in DataGridView in a column

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

How can I right-align text in a DataGridView column?

this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

How to hide column of DataGridView when using custom DataSource?

MyDataGridView.RowHeadersVisible = False; Before binding and rename each columns header and set columns width. To help my failing memory when I search, because I will search ... that's for sure ;-)

The property 'Id' is part of the object's key information and cannot be modified

The entity that was created by the framework doesn't have a contact.ContactTypeId property. It automatically removed it and created the ContactType association inside the Contact entity.

The way to get it to work, as you suggested, is to create a ContactType object by querying the database and assigning it to contact.ContactType. For example:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
ContactType contactType = dbContext.ContactType.Single(c => c.Id == 3);
contact.ContactType = contactType;

Java 8 LocalDate Jackson format

In Spring Boot web app, with Jackson and JSR 310 version "2.8.5"

compile "com.fasterxml.jackson.core:jackson-databind:2.8.5"
runtime "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.5"

The @JsonFormat works:

import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate birthDate;

Use Fieldset Legend with bootstrap

I had this problem and I solved with this way:

fieldset.scheduler-border {
    border: solid 1px #DDD !important;
    padding: 0 10px 10px 10px;
    border-bottom: none;
}

legend.scheduler-border {
    width: auto !important;
    border: none;
    font-size: 14px;
}

Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

How can I merge the columns from two tables into one output?

SELECT col1,
  col2
FROM
  (SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
  (SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;

How to echo out table rows from the db (php)

Expanding on the accepted answer:

function mysql_query_or_die($query) {
    $result = mysql_query($query);
    if ($result)
        return $result;
    else {
        $err = mysql_error();
        die("<br>{$query}<br>*** {$err} ***<br>");
    }
}

...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
    if ($first_row) {
        $first_row = false;
        // Output header row from keys.
        echo '<tr>';
        foreach($row as $key => $field) {
            echo '<th>' . htmlspecialchars($key) . '</th>';
        }
        echo '</tr>';
    }
    echo '<tr>';
    foreach($row as $key => $field) {
        echo '<td>' . htmlspecialchars($field) . '</td>';
    }
    echo '</tr>';
}
echo("</table>");

Benefits:

  • Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.

  • Shows field names as a header row of table.

  • Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.

  • Wrapped in <table> so displays properly.

  • (OPTIONAL) dies with display of query string and mysql_error, if query fails.

Example Output:

Id      Name
777     Aardvark
50      Lion
9999    Zebra

Replacing blank values (white space) with NaN in pandas

If you are exporting the data from the CSV file it can be as simple as this :

df = pd.read_csv(file_csv, na_values=' ')

This will create the data frame as well as replace blank values as Na

detect key press in python?

As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

This code will detect keys until new line is pressed.

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

Get visible items in RecyclerView

First / last visible child depends on the LayoutManager. If you are using LinearLayoutManager or GridLayoutManager, you can use

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

For example:

GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

For LinearLayoutManager, first/last depends on the adapter ordering. Don't query children from RecyclerView; LayoutManager may prefer to layout more items than visible for caching.

Add placeholder text inside UITextView in Swift?

Swift:

Add your TextView @IBOutlet:

@IBOutlet weak var txtViewMessage: UITextView!

In the viewWillAppear method, do add the following :

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    txtViewMessage.delegate = self    // Give TextViewMessage delegate Method

    txtViewMessage.text = "Place Holder Name"
    txtViewMessage.textColor = UIColor.lightGray

}

Please add the Delegate Using extension (UITextViewDelegate):

// MARK: - UITextViewDelegate
extension ViewController: UITextViewDelegate
{

    func textViewDidBeginEditing(_ textView: UITextView)
    {

        if !txtViewMessage.text!.isEmpty && txtViewMessage.text! == "Place Holder Name"
        {
            txtViewMessage.text = ""
            txtViewMessage.textColor = UIColor.black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView)
    {

        if txtViewMessage.text.isEmpty
        {
            txtViewMessage.text = "Place Holder Name"
            txtViewMessage.textColor = UIColor.lightGray
        }
    }
}

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

Detect click outside Angular component

Binding to document click through @Hostlistener is costly. It can and will have a visible performance impact if you overuse(for example, when building a custom dropdown component and you have multiple instances created in a form).

I suggest adding a @Hostlistener() to the document click event only once inside your main app component. The event should push the value of the clicked target element inside a public subject stored in a global utility service.

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {

  constructor(private utilitiesService: UtilitiesService) {}

  @HostListener('document:click', ['$event'])
  documentClick(event: any): void {
    this.utilitiesService.documentClickedTarget.next(event.target)
  }
}

@Injectable({ providedIn: 'root' })
export class UtilitiesService {
   documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}

Whoever is interested for the clicked target element should subscribe to the public subject of our utilities service and unsubscribe when the component is destroyed.

export class AnotherComponent implements OnInit {

  @ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef

  constructor(private utilitiesService: UtilitiesService) { }

  ngOnInit() {
      this.utilitiesService.documentClickedTarget
           .subscribe(target => this.documentClickListener(target))
  }

  documentClickListener(target: any): void {
     if (this.somePopup.nativeElement.contains(target))
        // Clicked inside  
     else
        // Clicked outside
  }

Python os.path.join on Windows

To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

How to check for a Null value in VB.NET

If you are using a strongly-typed dataset then you should do this:

If Not ediTransactionRow.Ispay_id1Null Then
    'Do processing here
End If

You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:

Public Property pay_Id1 Then
   Get
     return DirectCast(me.GetValue("pay_Id1", short)
   End Get
   'Abbreviated for clarity
End Property

The GetValue method is returning DBNull which cannot be converted to a short.

efficient way to implement paging

While LINQ-to-SQL will generate an OFFSET clause (possibly emulated using ROW_NUMBER() OVER() as others have mentioned), there is an entirely different, much faster way to perform paging in SQL. This is often called the "seek method" as described in this blog post here.

SELECT TOP 10 first_name, last_name, score
FROM players
WHERE (score < @previousScore)
   OR (score = @previousScore AND player_id < @previousPlayerId)
ORDER BY score DESC, player_id DESC

The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead.

With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).

This is the best way to implement paging when lazy loading more data in web applications, for instance.

Note, the "seek method" is also called keyset paging.

What is the current choice for doing RPC in Python?

maybe ZSI which implements SOAP. I used the stub generator and It worked properly. The only problem I encountered is about doing SOAP throught HTTPS.

git add only modified changes and ignore untracked files

Not sure if this is a feature or a bug but this worked for us:

git commit '' -m "Message"

Note the empty file list ''. Git interprets this to commit all modified tracked files, even if they are not staged, and ignore untracked files.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

Double precision - decimal places

It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double, and then round the double back to 15 decimal places you'll get the same number. To uniquely represent a double you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double) which is why 17 places are showing up, but not all 17-decimal numbers map to different double values (like in the examples in the other answers).

When should null values of Boolean be used?

There are three quick reasons:

  • to represent Database boolean values, which may be true, false or null
  • to represent XML Schema's xsd:boolean values declared with xsd:nillable="true"
  • to be able to use generic types: List<Boolean> - you can't use List<boolean>

jquery how to use multiple ajax calls one after the end of the other

I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.

function check_ajax_call_count()
{
    if ( window.ajax_call_count==window.ajax_calls_completed )
    {
        // do whatever needs to be done after the last ajax call finished
    }
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);

Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).

Is it possible to get an Excel document's row count without loading the entire document into memory?

This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:

from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)

for _,x in iterparse(xml):

    name= x.tag.split("}")[-1]
    if name=="col":
        print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]

    if name=="cols":
        print "break before reading the rest of the file"
        break

How to set value to form control in Reactive Forms in Angular

In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).

setValue:

  • Initialize Model Structure in Constructor:

    this.newForm = this.formBuilder.group({  
       firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
       lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
    });
    
  • If you want to update all fields of form:

    this.newForm.setValue({
       firstName: 'abc',
       lastName: 'def'
    });
    
  • If you want to update specific field of form:

    this.newForm.controls.firstName.setValue('abc');
    

Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.

patchValue:

  • If you want to update some/ specific fields of form:

    this.newForm.patchValue({
       firstName: 'abc'
    });
    

Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

This view is not constrained

you can go to the XML file then focus your mouse cursor into your button, text view or whatever you choose for your layout, then press Alt + Enter to fix it, after that the error will be gone.it works for me.

Creating an Array from a Range in VBA

Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:

Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
    
    Dim arr() As Variant, slicedArr() As Variant
    arr = rng.value   'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
    
    If UBound(arr, 1) > UBound(arr, 2) Then
        slicedArr = Application.WorksheetFunction.Transpose(arr)
    Else
        slicedArr = Application.WorksheetFunction.index(arr, 1, 0)  'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
                                                                   'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
                                                                   'and in a vertical range of cells for a column.
                                                                   'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
    End If
convertVecToArr = slicedArr
End Function

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

I know its too late to post answer, but i found completely differently scenario. I tried all possible solution given above but that not works for me. I found very silly mistake / ignorance in my case I checked IIS manager window carefully and found asp.net section was missing there. I have made Turn Windows features on for ASP.net, below is the steps

  1. Open Control Panel
  2. Programs\Turn Windows Features on or off Internet
  3. Information Services World Wide Web Services Application development
  4. Check for - >Features ASP.Net

I have closed IIS manager window and reopened it, now ASP.NET section is visible. enter image description here just browse hosted website and it's up on browser.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

how to set radio option checked onload with jQuery

//If you are doing it on javascript or a framework like backbone, you will encounter this a lot you could have something like this

$MobileRadio = $( '#mobileUrlRadio' );

while

$MobileRadio.checked = true;

will not work,

$MobileRadio[0].checked = true;

will.

your selector can be as the other guys above recommended too.

Simple JavaScript Checkbox Validation

var confirm=document.getElementById("confirm").value;
         if((confirm.checked==false)
         {
         alert("plz check the checkbox field");
         document.getElementbyId("confirm").focus();
         return false;
         }

Iterating through a variable length array

for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

or

for(String value : array)
{
    System.out.println(value);
}

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)
{
  final String value;

  value = myArray[index];
  System.out.println(value);
  index++;
}

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

Smooth scroll to specific div on click

I played around with nico's answer a little and it felt jumpy. Did a bit of investigation and found window.requestAnimationFrame which is a function that is called on each repaint cycle. This allows for a more clean-looking animation. Still trying to hone in on good default values for step size but for my example things look pretty good using this implementation.

var smoothScroll = function(elementId) {
    var MIN_PIXELS_PER_STEP = 16;
    var MAX_SCROLL_STEPS = 30;
    var target = document.getElementById(elementId);
    var scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do {
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                 (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);

    var stepFunc = function() {
        scrollContainer.scrollTop =
            Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);

        if (scrollContainer.scrollTop >= targetY) {
            return;
        }

        window.requestAnimationFrame(stepFunc);
    };

    window.requestAnimationFrame(stepFunc);
}

How to reset the state of a Redux store?

With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).

const appReducer = combineReducers({
  tabs,
  user
})

const initialState = appReducer({}, {})

const rootReducer = (state, action) => {
  if (action.type === 'LOG_OUT') {
    state = initialState
  }

  return appReducer(state, action)
}

How to center an element horizontally and vertically

Another approach is to use table:

_x000D_
_x000D_
<div style="border:2px solid #8AC007; height:200px; width:200px;">_x000D_
  <table style="width:100%; height:100%">_x000D_
    <tr style="height:100%">_x000D_
      <td style="height:100%; text-align:center">hello, multiple lines here, this is super long, and that is awesome, dude</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get value (String) of ArrayList<ArrayList<String>>(); in Java

listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);

You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");

ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");

collection.Add(listOfSomething1);    
collection.Add(listOfSomething2);

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

Creating layout constraints programmatically

When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.

Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.

The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero or simply init.

To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"V:|-[myView(>=748)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"H:[myView(==200)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

Verbally describing this layout reads as follows starting with the vertical constraint:

myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.

If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748) parameter in the visual format text. If you think that the (>=748) parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|) or bar with space (|-, -|) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.

In regards to your second question:

Using NSDictionaryOfVariableBindings(self.myView) (if you had an property setup for myView) and feeding that into your VFL to use self.myView in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:. See here for a similar question and answer.

ng-repeat: access key and value for each object in array of objects

A repeater inside a repeater

<div ng-repeat="step in steps">
    <div ng-repeat="(key, value) in step">
        {{key}} : {{value}}
    </div>
</div>

Best C++ IDE or Editor for Windows

vi or gvim if you don't like terminals.

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins> in <pluginManagement> tested with Eclipse Indigo SR1, maven 2.2.1

How to create an on/off switch with Javascript/CSS?

Initial answer from 2013

If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like those.

Modern 2018 Switch

How to ignore ansible SSH authenticity checking?

If you don't want to modify ansible.cfg or the playbook.yml then you can just set an environment variable:

export ANSIBLE_HOST_KEY_CHECKING=False

How to disable logging on the standard error stream in Python?

To fully disable logging:

logging.disable(sys.maxint) # Python 2

logging.disable(sys.maxsize) # Python 3

To enable logging:

logging.disable(logging.NOTSET)

Other answers provide work arounds which don't fully solve the problem, such as

logging.getLogger().disabled = True

and, for some n greater than 50,

logging.disable(n)

The problem with the first solution is that it only works for the root logger. Other loggers created using, say, logging.getLogger(__name__) are not disabled by this method.

The second solution does affect all logs. But it limits output to levels above that given, so one could override it by logging with a level greater than 50.

That can be prevented by

logging.disable(sys.maxint)

which as far as I can tell (after reviewing the source) is the only way to fully disable logging.

Codeigniter - no input file specified

I found the answer to this question here..... The problem was hosting server... I thank all who tried .... Hope this will help others

Godaddy Installation Tips

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

How to find unused/dead code in java projects

One thing I've been known to do in Eclipse, on a single class, is change all of its methods to private and then see what complaints I get. For methods that are used, this will provoke errors, and I return them to the lowest access level I can. For methods that are unused, this will provoke warnings about unused methods, and those can then be deleted. And as a bonus, you often find some public methods that can and should be made private.

But it's very manual.

What is a user agent stylesheet?

Answering the question in title, what is the user agent stylesheet, the set of default styles in the browser: Here are some of them (and most relevant ones also in today's web):

Personal opinion: Don't fight with them. They have good default values, for example, in rtl/bidi cases and are consistent nowadays. Reset what you see irrelevant to you, not all of them at once.

Free space in a CMD shell

df.exe

Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.

You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.

df -h will show all your drive's used and available disk space. For example:

M:\>df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/cygwin/bin   932G   78G  855G   9% /usr/bin
C:/cygwin/lib   932G   78G  855G   9% /usr/lib
C:/cygwin       932G   78G  855G   9% /
C:              932G   78G  855G   9% /cygdrive/c
E:              1.9T  1.3T  621G  67% /cygdrive/e
F:              1.9T  201G  1.7T  11% /cygdrive/f
H:              1.5T  524G  938G  36% /cygdrive/h
M:              1.5T  524G  938G  36% /cygdrive/m
P:               98G   67G   31G  69% /cygdrive/p
R:               98G   14G   84G  15% /cygdrive/r

Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:

M:\>df -h | grep M: | awk '{print $4}'

SQL - How to select a row having a column with max value

In Oracle DB:

create table temp_test1 (id number, value number, description varchar2(20));

insert into temp_test1 values(1, 22, 'qq');
insert into temp_test1 values(2, 22, 'qq');
insert into temp_test1 values(3, 22, 'qq');
insert into temp_test1 values(4, 23, 'qq1');
insert into temp_test1 values(5, 23, 'qq1');
insert into temp_test1 values(6, 23, 'qq1');

SELECT MAX(id), value, description FROM temp_test1 GROUP BY value, description;

Result:
    MAX(ID) VALUE DESCRIPTION
    -------------------------
    6         23    qq1
    3         22    qq

How to count occurrences of a column value efficiently in SQL?

This should work:

SELECT age, count(age) 
  FROM Students 
 GROUP by age

If you need the id as well you could include the above as a sub query like so:

SELECT S.id, S.age, C.cnt
  FROM Students  S
       INNER JOIN (SELECT age, count(age) as cnt
                     FROM Students 
                    GROUP BY age) C ON S.age = C.age

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

Checking whether a string starts with XXXX

In case you want to match multiple words to your magic word, you can pass the words to match as a tuple:

>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True

startswith takes a string or a tuple of strings.

How to store an output of shell script to a variable in Unix?

Suppose you want to store the result of an echo command

echo hello   
x=$(echo hello)  
echo "$x",world!  

output:

hello  
hello,world!

Reading an integer from user input

Use this simple line:

int x = int.Parse(Console.ReadLine());

SQL Server ORDER BY date and nulls last

Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:

select * 
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

How to clear textarea on click?

Try:

<input name="mytextbox" onfocus="if (this.value=='Please describe why') this.value = ''" type="text" value="Please Describe why">

Insert, on duplicate update in PostgreSQL?

With PostgreSQL 9.1 this can be achieved using a writeable CTE (common table expression):

WITH new_values (id, field1, field2) as (
  values 
     (1, 'A', 'X'),
     (2, 'B', 'Y'),
     (3, 'C', 'Z')

),
upsert as
( 
    update mytable m 
        set field1 = nv.field1,
            field2 = nv.field2
    FROM new_values nv
    WHERE m.id = nv.id
    RETURNING m.*
)
INSERT INTO mytable (id, field1, field2)
SELECT id, field1, field2
FROM new_values
WHERE NOT EXISTS (SELECT 1 
                  FROM upsert up 
                  WHERE up.id = new_values.id)

See these blog entries:


Note that this solution does not prevent a unique key violation but it is not vulnerable to lost updates.
See the follow up by Craig Ringer on dba.stackexchange.com

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

Update your jdk to latest minimum version for your elasticsearch.

moving changed files to another branch for check-in

A soft git reset will put committed changes back into your index. Next, checkout the branch you had intended to commit on. Then git commit with a new commit message.

  1. git reset --soft <commit>

  2. git checkout <branch>

  3. git commit -m "Commit message goes here"

From git docs:

git reset [<mode>] [<commit>] This form resets the current branch head to and possibly updates the index (resetting it to the tree of ) and the working tree depending on . If is omitted, defaults to --mixed. The must be one of the following:

--soft Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

SQL Error: ORA-01861: literal does not match format string 01861

If you provide proper date format it should work please recheck once if you have given correct date format in insert values

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

T-SQL query to show table definition?

Have you tried sp_help?

sp_help 'TableName'

Numpy matrix to array

ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.

Ravel:

A = M.ravel()
print A, A.shape
>>> [1 2 3 4] (4,)

Flatten:

M = np.array([[1], [2], [3], [4]])
A = M.flatten()
print A, A.shape
>>> [1 2 3 4] (4,)

numpy.ravel() is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are using numpy.ravel().

numpy.flatten() is slower than numpy.ravel(). But if you are using numpy.flatten() to create A, then changes in A will not get carried over to the original array M.

numpy.squeeze() and M.reshape(-1) are slower than numpy.flatten() and numpy.ravel().

%timeit M.ravel()
>>> 1000000 loops, best of 3: 309 ns per loop

%timeit M.flatten()
>>> 1000000 loops, best of 3: 650 ns per loop

%timeit M.reshape(-1)
>>> 1000000 loops, best of 3: 755 ns per loop

%timeit np.squeeze(M)
>>> 1000000 loops, best of 3: 886 ns per loop

Purpose of "%matplotlib inline"

If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

%matplotlib inline: only draw static images in the notebook

Pass mouse events through absolutely-positioned element

The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)

Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.

Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!

What is the difference between a Docker image and a container?

Dockerfile is like your Bash script that produce a tarball (Docker image).

Docker containers is like extracted version of the tarball. You can have as many copies as you like in different folders (the containers).

Hive query output to file

To directly save the file in HDFS, use the below command:

hive> insert overwrite  directory '/user/cloudera/Sample' row format delimited fields terminated by '\t' stored as textfile select * from table where id >100;

This will put the contents in the folder /user/cloudera/Sample in HDFS.

How to export and import a .sql file from command line with options?

Well you can use below command to export,

mysqldump --databases --user=root --password your_db_name > export_into_db.sql

and the generated file will be available in the same directory where you had ran this command.

Now login to mysql using command,

mysql -u[username] -p

then use "source" command with the file path.

UIDevice uniqueIdentifier deprecated - What to do now?

iOS 11 has introduced the DeviceCheck framework. It has a fullproof solution for uniquely identifying the device.

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

npm install won't install devDependencies

So the way I got around this was in the command where i would normally run npm install or npm ci, i added NODE_ENV=build, and then NODE_ENV=production after the command, so my entire command came out to:

RUN NODE_ENV=build && npm ci && NODE_ENV=production

So far I haven't had any bad reactions, and my development dependencies which are used for building the application all worked / loaded correctly.

I find this to be a better solution than adding an additional command like npm install --only=dev because it takes less time, and enables me to use the npm ci command, which is faster and specifically designed to be run inside CI tools / build scripts. (See npi-ci documentation for more information on it)

Wamp Server not goes to green color

I've had the above solutions work for me on many occasions, except one; that was after I buggered up an alias file - ie a file that allows the website folder to be located in another location other than the www folder. Here's the solution:

  1. Go to c:/wamp/alias
  2. Cut all of the alias files and paste in a temp folder somewhere
  3. Restart all WAMP services
  4. If the WAMP icon goes green, then add each alias file back to the alias folder one by one, restart WAMP, and when WAMP doesn't start, you know that alias file has some bad data in it. So, fix that file or delete it. Your choice.

How does facebook, gmail send the real time notification?

According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.

In the picture below, the phrase "channel clusters" means "comet servers".

System overview

Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.

You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push
        alert(msg.content);
    }
});

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

Run a batch file with Windows task scheduler

Make sure "Start In" does NOT end with a BACKSLASH.

How to build and run Maven projects after importing into Eclipse IDE

  1. Right Click on your project
  2. Go to Maven>Update Project
  3. Check the Force Update of Snapshots/Releases Checkbox
  4. Click Ok

That's all. You can see progression of build in left below corner.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Use of Java's Collections.singletonList()?

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

glob exclude pattern

If the position of the character isn't important, that is for example to exclude manifests files (wherever it is found _) with glob and re - regular expression operations, you can use:

import glob
import re
for file in glob.glob('*.txt'):
    if re.match(r'.*\_.*', file):
        continue
    else:
        print(file)

Or with in a more elegant way - list comprehension

filtered = [f for f in glob.glob('*.txt') if not re.match(r'.*\_.*', f)]

for mach in filtered:
    print(mach)

break/exit script

Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with

if (n >= 500) {

.... long running code here

}

If breaking out of a function, you'll probably just want return(), either explicitly or implicitly.

For example, an explicit double return

foo <- function(x) {
  if(x < 10) {
    return(NA)
  } else {
    xx <- seq_len(x)
    xx <- cumsum(xx)
  }
  xx ## return(xx) is implied here
}

> foo(5)
[1] 0
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

By return() being implied, I mean that the last line is as if you'd done return(xx), but it is slightly more efficient to leave off the call to return().

Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else () clause. Such a modification to foo() would be

foo <- function(x) {
  ## out is NA or cumsum(xx) depending on x
  out <- if(x < 10) {
    NA
  } else {
    xx <- seq_len(x)
    cumsum(xx)
  }
  out ## return(out) is implied here
}

> foo(5)
[1] NA
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

How to define an enum with string value?

Maybe it's too late, but here it goes.

We can use the attribute EnumMember to manage Enum values.

public enum EUnitOfMeasure
{
    [EnumMember(Value = "KM")]
    Kilometer,
    [EnumMember(Value = "MI")]
    Miles
}

This way the result value for EUnitOfMeasure will be KM or MI. This also can be seen in Andrew Whitaker answer.

How to set delay in vbscript

if it is VBScript, it should be

WScript.Sleep 100

If it is JavaScript

WScript.Sleep(100);

Time in milliseconds. WScript.Sleep 1000 results in a 1 second sleep.

SQL Server copy all rows from one table into another i.e duplicate table

Either you can use RAW SQL:

INSERT INTO DEST_TABLE (Field1, Field2) 
SELECT Source_Field1, Source_Field2 
FROM SOURCE_TABLE

Or use the wizard:

  1. Right Click on the Database -> Tasks -> Export Data
  2. Select the source/target Database
  3. Select source/target table and fields
  4. Copy the data

Then execute:

TRUNCATE TABLE SOURCE_TABLE

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

Lombok is not generating getter and setter

If you use STS. You must have Lombok installed in your Eclipse by running lombok-abc.jar

Please Following the Steps:

-Include pom in Maven . -Exit/Shutdown STS(must) -Find lombok Jar in ~.m2\repository\org\projectlombok\lombok\1.18.12 -From Command enter image description here

After then enter image description here

After then select the STS.exe enter image description here

After then click to update/update

enter image description here

then Quit Installer

Happy Coding

Blockquote

Can functions be passed as parameters?

Yes, consider some of these examples:

package main

import "fmt"

// convert types take an int and return a string value.
type convert func(int) string

// value implements convert, returning x as string.
func value(x int) string {
    return fmt.Sprintf("%v", x)
}

// quote123 passes 123 to convert func and returns quoted string.
func quote123(fn convert) string {
    return fmt.Sprintf("%q", fn(123))
}

func main() {
    var result string

    result = value(123)
    fmt.Println(result)
    // Output: 123

    result = quote123(value)
    fmt.Println(result)
    // Output: "123"

    result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
    fmt.Println(result)
    // Output: "1111011"

    foo := func(x int) string { return "foo" }
    result = quote123(foo)
    fmt.Println(result)
    // Output: "foo"

    _ = convert(foo) // confirm foo satisfies convert at runtime

    // fails due to argument type
    // _ = convert(func(x float64) string { return "" })
}

Play: http://play.golang.org/p/XNMtrDUDS0

Tour: https://tour.golang.org/moretypes/25 (Function Closures)

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I had the same problem, but solution for my case is not listed in answers. My antivirus program (AVG) determined file MyProg.exe as a virus and put it into the 'virus storehouse'. You need to check this storehouse and if file is there - then just restore it. It helped me out.

Link to "pin it" on pinterest without generating a button

The standard Pinterest button code (which you can generate here), is an <a> tag wrapping an <img> of the Pinterest button.

If you don't include the pinit.js script on your page, this <a> tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank" to the tag to make it open clicks in a new window.

The tag syntax would look like:

<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>

If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.

Find and extract a number from a string

You can also try this

string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));

How to validate domain credentials?

C# in .NET 3.5 using System.DirectoryServices.AccountManagement.

 bool valid = false;
 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
 {
     valid = context.ValidateCredentials( username, password );
 }

This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.

release Selenium chromedriver.exe from memory

Kill Multiple Processes From the Command Line The first thing you’ll need to do is open up a command prompt, and then use the taskkill command with the following syntax:

taskkill /F /IM <processname.exe> /T

These parameters will forcibly kill any process matching the name of the executable that you specify. For instance, to kill all iexplore.exe processes, we’d use:

taskkill /F /IM iexplore.exe

enter image description here

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

How do I convert from int to String?

There are three ways of converting to Strings

  1. String string = "" + i;
  2. String string = String.valueOf(i);
  3. String string = Integer.toString(i);

changing source on html5 video tag

Try moving the OGG source to the top. I've noticed Firefox sometimes gets confused and stops the player when the one it wants to play, OGG, isn't first.

Worth a try.

get name of a variable or parameter

What you are passing to GETNAME is the value of myInput, not the definition of myInput itself. The only way to do that is with a lambda expression, for example:

var nameofVar = GETNAME(() => myInput);

and indeed there are examples of that available. However! This reeks of doing something very wrong. I would propose you rethink why you need this. It is almost certainly not a good way of doing it, and forces various overheads (the capture class instance, and the expression tree). Also, it impacts the compiler: without this the compiler might actually have chosen to remove that variable completely (just using the stack without a formal local).

Show git diff on file in staging area

In order to see the changes that have been staged already, you can pass the -–staged option to git diff (in pre-1.6 versions of Git, use –-cached).

git diff --staged
git diff --cached

Java - Relative path of a file in a java web application

Do you really need to load it from a file? If you place it along your classes (in WEB-INF/classes) you can get an InputStream to it using the class loader:

InputStream csv = 
   SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to set the authorization header using curl

(for those who are looking for php-curl answer)

$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate

$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);

var_dump($response);

What is the difference between T(n) and O(n)?

one is Big "O"

one is Big Theta

http://en.wikipedia.org/wiki/Big_O_notation

Big O means your algorithm will execute in no more steps than in given expression(n^2)

Big Omega means your algorithm will execute in no fewer steps than in the given expression(n^2)

When both condition are true for the same expression, you can use the big theta notation....

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

How to rename a single column in a data.frame?

I would simply change a column name to the dataset with the new name I want with the following code: names(dataset)[index_value] <- "new_col_name"

How to convert integer into date object python?

Here is what I believe answers the question (Python 3, with type hints):

from datetime import date


def int2date(argdate: int) -> date:
    """
    If you have date as an integer, use this method to obtain a datetime.date object.

    Parameters
    ----------
    argdate : int
      Date as a regular integer value (example: 20160618)

    Returns
    -------
    dateandtime.date
      A date object which corresponds to the given value `argdate`.
    """
    year = int(argdate / 10000)
    month = int((argdate % 10000) / 100)
    day = int(argdate % 100)

    return date(year, month, day)


print(int2date(20160618))

The code above produces the expected 2016-06-18.

Changing minDate and maxDate on the fly using jQuery DatePicker

I have changed min date property of date time picker by using this

$('#date').data("DateTimePicker").minDate(startDate);

I hope this one help to someone !

Change Git repository directory location.

A more Git based approach would be to make the changes to your local copy using cd or copy and pasting and then pushing these changes from local to remote repository.

If you try checking status of your local repo, it may show "untracked changes" which are actually the relocated files. To push these changes forcefully, you need to stage these files/directories by using

$ git add -A
#And commiting them
$ git commit -m "Relocating image demo files"
#And finally, push
$ git push -u local_repo -f HEAD:master

Hope it helps.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Difference between "char" and "String" in Java

In layman's term, char is a letter, while String is a collection of letter (or a word). The distinction of ' and " is important, as 'Test' is illegal in Java.

char is a primitive type, String is a class

Concatenate multiple result rows of one column into one, group by another column

Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl
GROUP  BY 1;

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other character types (varchar, character, "char"), and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl
GROUP  BY 1;

But it's typically faster to sort rows in a subquery. See:

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

Update ViewPager dynamically?

Instead of returning POSITION_NONE from getItemPosition() and causing full view recreation, do this:

//call this method to update fragments in ViewPager dynamically
public void update(UpdateData xyzData) {
    this.updateData = xyzData;
    notifyDataSetChanged();
}

@Override
public int getItemPosition(Object object) {
    if (object instanceof UpdateableFragment) {
        ((UpdateableFragment) object).update(updateData);
    }
    //don't return POSITION_NONE, avoid fragment recreation. 
    return super.getItemPosition(object);
}

Your fragments should implement UpdateableFragment interface:

public class SomeFragment extends Fragment implements
    UpdateableFragment{

    @Override
    public void update(UpdateData xyzData) {
         // this method will be called for every fragment in viewpager
         // so check if update is for this fragment
         if(forMe(xyzData)) {
           // do whatever you want to update your UI
         }
    }
}

and the interface:

public interface UpdateableFragment {
   public void update(UpdateData xyzData);
}

Your data class:

public class UpdateData {
    //whatever you want here
}

How to put sshpass command inside a bash script?

Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.

sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'

Regex Email validation

There's no perfect regular expression, but this one is pretty strong, I think, based on study of RFC5322. And with C# string interpolation, pretty easy to follow, I think, as well.

const string atext = @"a-zA-Z\d!#\$%&'\*\+-/=\?\^_`\{\|\}~";
var localPart = $"[{atext}]+(\\.[{atext}]+)*";
var domain = $"[{atext}]+(\\.[{atext}]+)*";
Assert.That(() => EmailRegex = new Regex($"^{localPart}@{domain}$", Compiled), 
Throws.Nothing);

Vetted with NUnit 2.x.

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

Best way to unselect a <select> in jQuery?

Use removeAttr...

$("option:selected").removeAttr("selected");

Or Prop

$("option:selected").prop("selected", false)

Android: How do bluetooth UUIDs work?

UUID is similar in notion to port numbers in Internet. However, the difference between Bluetooth and the Internet is that, in Bluetooth, port numbers are assigned dynamically by the SDP (service discovery protocol) server during runtime where each UUID is given a port number. Other devices will ask the SDP server, who is registered under a reserved port number, about the available services on the device and it will reply with different services distinguishable from each other by being registered under different UUIDs.

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

How do you specify table padding in CSS? ( table, not cell padding )

table.foobar
{
   padding:30px; /* if border is not collapsed */
}

or 

table.foobar
{
   border-spacing:0;
}
table.foobar>tbody
{
   display:table;
   border-spacing:0; /* or other preferred */
   border:30px solid transparent; /* 30px is the "padding" */
}

Works in Firefox, Chrome, IE11, Edge.

Can I set enum start value in Java?

The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.

Example:

public class TestEnum {
    enum ids {
        OPEN,
        CLOSE,
        OTHER;

        public final int value = 100 + ordinal();
    };

    public static void main(String arg[]) {
        System.out.println("OPEN:  " + ids.OPEN.value);
        System.out.println("CLOSE: " + ids.CLOSE.value);
        System.out.println("OTHER: " + ids.OTHER.value);
    }
};

Gives the output:

OPEN:  100
CLOSE: 101
OTHER: 102

Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">
    $("#hideme").hide();
</script>

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

Best way to stress test a website

The ab (apache bench) tool allows you to send many requests to a single page and you specify how many clients you want to be used and how many concurrent connection you want.

This may be the first step when developing a site. Just test some pages with a specific load. This way of benchmarking may have some problem, like caching being over used.

Later you may want a tool that simulate some concrete traffic and not for a single page. I don't have a refence handy on such tool yet.

in a "using" block is a SqlConnection closed on return or exception?

Using generates a try / finally around the object being allocated and calls Dispose() for you.

It saves you the hassle of manually creating the try / finally block and calling Dispose()

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

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

Here is a python program to use the multiprocessing library to distribute the line counting across machines/cores. My test improves counting a 20million line file from 26 seconds to 7 seconds using an 8 core windows 64 server. Note: not using memory mapping makes things much slower.

import multiprocessing, sys, time, os, mmap
import logging, logging.handlers

def init_logger(pid):
    console_format = 'P{0} %(levelname)s %(message)s'.format(pid)
    logger = logging.getLogger()  # New logger at root level
    logger.setLevel( logging.INFO )
    logger.handlers.append( logging.StreamHandler() )
    logger.handlers[0].setFormatter( logging.Formatter( console_format, '%d/%m/%y %H:%M:%S' ) )

def getFileLineCount( queues, pid, processes, file1 ):
    init_logger(pid)
    logging.info( 'start' )

    physical_file = open(file1, "r")
    #  mmap.mmap(fileno, length[, tagname[, access[, offset]]]

    m1 = mmap.mmap( physical_file.fileno(), 0, access=mmap.ACCESS_READ )

    #work out file size to divide up line counting

    fSize = os.stat(file1).st_size
    chunk = (fSize / processes) + 1

    lines = 0

    #get where I start and stop
    _seedStart = chunk * (pid)
    _seekEnd = chunk * (pid+1)
    seekStart = int(_seedStart)
    seekEnd = int(_seekEnd)

    if seekEnd < int(_seekEnd + 1):
        seekEnd += 1

    if _seedStart < int(seekStart + 1):
        seekStart += 1

    if seekEnd > fSize:
        seekEnd = fSize

    #find where to start
    if pid > 0:
        m1.seek( seekStart )
        #read next line
        l1 = m1.readline()  # need to use readline with memory mapped files
        seekStart = m1.tell()

    #tell previous rank my seek start to make their seek end

    if pid > 0:
        queues[pid-1].put( seekStart )
    if pid < processes-1:
        seekEnd = queues[pid].get()

    m1.seek( seekStart )
    l1 = m1.readline()

    while len(l1) > 0:
        lines += 1
        l1 = m1.readline()
        if m1.tell() > seekEnd or len(l1) == 0:
            break

    logging.info( 'done' )
    # add up the results
    if pid == 0:
        for p in range(1,processes):
            lines += queues[0].get()
        queues[0].put(lines) # the total lines counted
    else:
        queues[0].put(lines)

    m1.close()
    physical_file.close()

if __name__ == '__main__':
    init_logger( 'main' )
    if len(sys.argv) > 1:
        file_name = sys.argv[1]
    else:
        logging.fatal( 'parameters required: file-name [processes]' )
        exit()

    t = time.time()
    processes = multiprocessing.cpu_count()
    if len(sys.argv) > 2:
        processes = int(sys.argv[2])
    queues=[] # a queue for each process
    for pid in range(processes):
        queues.append( multiprocessing.Queue() )
    jobs=[]
    prev_pipe = 0
    for pid in range(processes):
        p = multiprocessing.Process( target = getFileLineCount, args=(queues, pid, processes, file_name,) )
        p.start()
        jobs.append(p)

    jobs[0].join() #wait for counting to finish
    lines = queues[0].get()

    logging.info( 'finished {} Lines:{}'.format( time.time() - t, lines ) )

Simulate limited bandwidth from within Chrome?

If you are on a Mac, the Chrome dev team recommend the 'Network Link Conditioner Tool'

Either:

Xcode > Open Developer Tool > More Developer Tools > Hardware IO Tools for Xcode

Or if you don't want to install Xcode:

Go to the Apple Download Center and search for Hardware IO Tools

https://developer.apple.com/downloads/index.action

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to extract duration time from ffmpeg output?

I recommend using json format, it's easier for parsing

ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner

{
    "streams": [
        {
            "index": 0,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "HE-AACv2",
            "codec_type": "audio",
            "codec_time_base": "1/44100",
            "codec_tag_string": "[0][0][0][0]",
            "codec_tag": "0x0000",
            "sample_fmt": "fltp",
            "sample_rate": "44100",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/28224000",
            "duration_ts": 305349201,
            "duration": "10.818778",
            "bit_rate": "27734",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            }
        }
    ],
    "format": {
        "filename": "your-input-file.mp4",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "aac",
        "format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
        "duration": "10.818778",
        "size": "37506",
        "bit_rate": "27734",
        "probe_score": 51
    }
}

you can find the duration information in format section, works both for video and audio

How to dynamically set bootstrap-datepicker's date value?

You can do also this way:

  $("#startDateText").datepicker({
                toValue: function (date, format, language) {
                    var d = new Date(date);
                    d.setDate(d.getDate());
                    return new Date(d);
                },
                autoclose: true
            });

http://bootstrap-datepicker.readthedocs.org/en/latest/options.html#format

Resize an Array while keeping current elements in Java?

It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.

It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}

How to get a time zone from a location using latitude and longitude coordinates?

_x000D_
_x000D_
  function jsonpRequest(url, data)_x000D_
{_x000D_
    let params = "";_x000D_
    for (let key in data)_x000D_
    {_x000D_
        if (data.hasOwnProperty(key))_x000D_
        {_x000D_
            if (params.length == 0)_x000D_
            {_x000D_
                params += "?";_x000D_
            }_x000D_
            else_x000D_
            {_x000D_
                params += "&";_x000D_
            }_x000D_
            let encodedKey = encodeURIComponent(key);_x000D_
            let encodedValue = encodeURIComponent(data[key]);_x000D_
            params += encodedKey + "=" + encodedValue;_x000D_
         }_x000D_
    }_x000D_
    let script = document.createElement('script');_x000D_
    script.src = url + params;_x000D_
    document.body.appendChild(script);_x000D_
}_x000D_
_x000D_
function getLocation() {_x000D_
  if (navigator.geolocation) {_x000D_
    navigator.geolocation.getCurrentPosition(showPosition);_x000D_
  } else {_x000D_
    x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
  }_x000D_
}_x000D_
let lat_ini=[]; let lon_ini=[];_x000D_
function showPosition(position) {_x000D_
  lat_ini= position.coords.latitude;_x000D_
  lon_ini= position.coords.longitude;_x000D_
}_x000D_
////delay time between lines_x000D_
function sleep(ms) {_x000D_
  return new Promise(resolve => setTimeout(resolve, ms));_x000D_
}_x000D_
///////_x000D_
function getGMT()_x000D_
{_x000D_
  getfinalGMT()_x000D_
  getLocation()_x000D_
  async function sample() {_x000D_
    await sleep(2000);_x000D_
let lat_str=lat_ini.toString();_x000D_
let lng_str=" "+lon_ini.toString();_x000D_
_x000D_
  let url = "https://api.opencagedata.com/geocode/v1/json";_x000D_
  let data = {_x000D_
    callback: "displayGMT",_x000D_
    q: lat_str + lng_str,_x000D_
    key: "fac4471073a347019196c1291e6a97d7"_x000D_
  }_x000D_
  jsonpRequest(url, data)_x000D_
}_x000D_
 sample();_x000D_
 }_x000D_
let your_GMT=[];_x000D_
function displayGMT(data)_x000D_
{_x000D_
your_GMT=(Number(data.results[0].annotations.timezone.offset_string))_x000D_
console.log(your_GMT)_x000D_
}_x000D_
/////_x000D_
function getfinalGMT()_x000D_
{_x000D_
let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value;_x000D_
let lat_str=lat.toString();_x000D_
let lng_str=" "+lng.toString();_x000D_
_x000D_
  let url = "https://api.opencagedata.com/geocode/v1/json";_x000D_
  let data = {_x000D_
    callback: "displayfinalGMT",_x000D_
    q: lat + lng_str,_x000D_
    key: "fac4471073a347019196c1291e6a97d7"_x000D_
  }_x000D_
  jsonpRequest(url, data)_x000D_
 }_x000D_
let final_GMT=[];_x000D_
function displayfinalGMT(data)_x000D_
{_x000D_
final_GMT=(Number(data.results[0].annotations.timezone.offset_string))_x000D_
console.log(final_GMT)_x000D_
}_x000D_
/////clock_x000D_
_x000D_
_x000D_
const hourHand = document.querySelector('[data-hour-hand]')_x000D_
const minuteHand = document.querySelector('[data-minute-hand]')_x000D_
const secondHand = document.querySelector('[data-second-hand]')_x000D_
  let dif_overall=[];_x000D_
function setClock() {_x000D_
   let gmt_diff=Number(your_GMT-final_GMT)/100_x000D_
   if (gmt_diff>12){_x000D_
      dif_overall=gmt_diff-12_x000D_
   }_x000D_
   else{_x000D_
     dif_overall=gmt_diff_x000D_
   }_x000D_
    console.log(dif_overall)_x000D_
  const currentDate = new Date()_x000D_
  const secondsRatio = currentDate.getSeconds() / 60_x000D_
  const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60_x000D_
  const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12_x000D_
  setRotation(secondHand, secondsRatio)_x000D_
  setRotation(minuteHand, minutesRatio)_x000D_
  setRotation(hourHand, hoursRatio)_x000D_
}_x000D_
_x000D_
function setRotation(element, rotationRatio) {_x000D_
  element.style.setProperty('--rotation', rotationRatio * 360)_x000D_
}_x000D_
function activate_clock(){_x000D_
setClock()_x000D_
setInterval(setClock, 1000)_x000D_
}
_x000D_
*, *::after, *::before {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
body {_x000D_
  background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%));_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  min-height: 100vh;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.clock {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: rgba(255, 255, 255, .8);_x000D_
  border-radius: 50%;_x000D_
  border: 2px solid black;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.clock .number {_x000D_
  --rotation: 0;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  text-align: center;_x000D_
  transform: rotate(var(--rotation));_x000D_
  font-size: 1.5rem;_x000D_
}_x000D_
_x000D_
.clock .number1 { --rotation: 30deg; }_x000D_
.clock .number2 { --rotation: 60deg; }_x000D_
.clock .number3 { --rotation: 90deg; }_x000D_
.clock .number4 { --rotation: 120deg; }_x000D_
.clock .number5 { --rotation: 150deg; }_x000D_
.clock .number6 { --rotation: 180deg; }_x000D_
.clock .number7 { --rotation: 210deg; }_x000D_
.clock .number8 { --rotation: 240deg; }_x000D_
.clock .number9 { --rotation: 270deg; }_x000D_
.clock .number10 { --rotation: 300deg; }_x000D_
.clock .number11 { --rotation: 330deg; }_x000D_
_x000D_
.clock .hand {_x000D_
  --rotation: 0;_x000D_
  position: absolute;_x000D_
  bottom: 50%;_x000D_
  left: 50%;_x000D_
  border: 1px solid white;_x000D_
  border-top-left-radius: 10px;_x000D_
  border-top-right-radius: 10px;_x000D_
  transform-origin: bottom;_x000D_
  z-index: 10;_x000D_
  transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));_x000D_
}_x000D_
_x000D_
.clock::after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  background-color: black;_x000D_
  z-index: 11;_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.clock .hand.second {_x000D_
  width: 3px;_x000D_
  height: 45%;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.clock .hand.minute {_x000D_
  width: 7px;_x000D_
  height: 40%;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.clock .hand.hour {_x000D_
  width: 10px;_x000D_
  height: 35%;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
/* Background Styles Only */_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Raleway');_x000D_
_x000D_
* {_x000D_
    font-family: Raleway;_x000D_
}_x000D_
_x000D_
.side-links {_x000D_
  position: absolute;_x000D_
  top: 15px;_x000D_
  right: 15px;_x000D_
}_x000D_
_x000D_
.side-link {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  text-decoration: none;_x000D_
  margin-bottom: 10px;_x000D_
  color: white;_x000D_
  width: 180px;_x000D_
  padding: 10px 0;_x000D_
  border-radius: 10px;_x000D_
}_x000D_
_x000D_
.side-link-youtube {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.side-link-twitter {_x000D_
  background-color: #1DA1F2;_x000D_
}_x000D_
_x000D_
.side-link-github {_x000D_
  background-color: #6e5494;_x000D_
}_x000D_
_x000D_
.side-link-text {_x000D_
  margin-left: 10px;_x000D_
  font-size: 18px;_x000D_
}_x000D_
_x000D_
.side-link-icon {_x000D_
  color: white;_x000D_
  font-size: 30px;_x000D_
}
_x000D_
   <input type="text" id="lat_id" placeholder="lat"><br><br>_x000D_
  <input type="text" id="lng_id" placeholder="lng"><br><br>_x000D_
<button class="text" onClick="getLocation()">Location</button>_x000D_
<button class="text" onClick="getGMT()"> GMT</button>_x000D_
<button class="text" onClick="activate_clock()"> Activate</button>_x000D_
<div class="clock">_x000D_
  <div class="hand hour" data-hour-hand></div>_x000D_
  <div class="hand minute" data-minute-hand></div>_x000D_
  <div class="hand second" data-second-hand></div>_x000D_
  <div class="number number1">1</div>_x000D_
  <div class="number number2">2</div>_x000D_
  <div class="number number3">3</div>_x000D_
  <div class="number number4">4</div>_x000D_
  <div class="number number5">5</div>_x000D_
  <div class="number number6">6</div>_x000D_
  <div class="number number7">7</div>_x000D_
  <div class="number number8">8</div>_x000D_
  <div class="number number9">9</div>_x000D_
  <div class="number number10">10</div>_x000D_
  <div class="number number11">11</div>_x000D_
  <div class="number number12">12</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good Linux (Ubuntu) SVN client

See my question:

What is the best subversion client for Linux?

I also agree, GUI clients in linux suck.

I use subeclipse in Eclipse and RapidSVN in gnome.

How to find text in a column and saving the row number where it is first found - Excel VBA

Dim FindRow as Range

Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
                   After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
                                                  ' column i.e. the first
                   LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
                   LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
                   SearchOrder:=xlByRows, _ 'This look down the column row by row 
                                            'Larger Ranges with multiple columns can be set to 
                                            ' look column by column then down 
                   MatchCase:=False) ' this says that the search is not case sensitive

If Not FindRow  Is Nothing Then ' if findrow is something (Prevents Errors)
    FirstRow = FindRow.Row      ' set FirstRow to the first time a match is found
End If

If you would like to get addition ones you can use:

Do Until FindRow Is Nothing
    Set FindRow = Range("A:A").FindNext(after:=FindRow)
    If FindRow.row = FirstRow Then
        Exit Do
    Else ' Do what you'd like with the additional rows here.

    End If
Loop

How to create empty constructor for data class in Kotlin Android

From the documentation

NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.

JavaScript Extending Class

For Autodidacts:

function BaseClass(toBePrivate){
    var morePrivates;
    this.isNotPrivate = 'I know';
    // add your stuff
}
var o = BaseClass.prototype;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// MiddleClass extends BaseClass
function MiddleClass(toBePrivate){
    BaseClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = MiddleClass.prototype = Object.create(BaseClass.prototype);
MiddleClass.prototype.constructor = MiddleClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';



// TopClass extends MiddleClass
function TopClass(toBePrivate){
    MiddleClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = TopClass.prototype = Object.create(MiddleClass.prototype);
TopClass.prototype.constructor = TopClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// to be continued...

Create "instance" with getter and setter:

function doNotExtendMe(toBePrivate){
    var morePrivates;
    return {
        // add getters, setters and any stuff you want
    }
}

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

The Clear method is defined as

    public void Clear() { 
        Text = null;
    } 

The Text property's setter starts with

        set { 
            if (value == null) { 
                value = "";
            } 

I assume this answers your question.

What is SuppressWarnings ("unchecked") in Java?

In Java, generics are implemented by means of type erasure. For instance, the following code.

List<String> hello = List.of("a", "b");
String example = hello.get(0);

Is compiled to the following.

List hello = List.of("a", "b");
String example = (String) hello.get(0);

And List.of is defined as.

static <E> List<E> of(E e1, E e2);

Which after type erasure becomes.

static List of(Object e1, Object e2);

The compiler has no idea what are generic types at runtime, so if you write something like this.

Object list = List.of("a", "b");
List<Integer> actualList = (List<Integer>) list;

Java Virtual Machine has no idea what generic types are while running a program, so this compiles and runs, as for Java Virtual Machine, this is a cast to List type (this is the only thing it can verify, so it verifies only that).

But now add this line.

Integer hello = actualList.get(0);

And JVM will throw an unexpected ClassCastException, as Java compiler inserted an implicit cast.

java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.lang.Integer

An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.

Why would you want to do that? Java type system isn't good enough to represent all possible type usage patterns. Sometimes you may know that a cast is safe, but Java doesn't provide a way to say so - to hide warnings like this, @SupressWarnings("unchecked") can be used, so that a programmer can focus on real warnings. For instance, Optional.empty() returns a singleton to avoid allocation of empty optionals that don't store a value.

private static final Optional<?> EMPTY = new Optional<>();
public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}

This cast is safe, as the value stored in an empty optional cannot be retrieved so there is no risk of unexpected class cast exceptions.

Accessing inventory host variable in Ansible playbook

[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:

{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }}

REST API 404: Bad URI, or Missing Resource?

404 is just the HTTP response code. On top of that, you can provide a response body and/or other headers with a more meaningful error message that developers will see.

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

A button is identified by the class ui-button. To disable a button:

$("#myButton").addClass("ui-state-disabled").attr("disabled", true);

Unless you are dynamically creating the dialog (which is possible), you will know the position of the button. So, to disable the first button:

$("#myButton:eq(0)").addClass("ui-state-disabled").attr("disabled", true);

The ui-state-disabled class is what gives a button that nice dimmed style.

./configure : /bin/sh^M : bad interpreter

You can also do this in Kate.

  1. Open the file
  2. Open the Tools menu
  3. Expand the End Of Line submenu
  4. Select UNIX
  5. Save the file.

react-router - pass props to handler component

You can pass props by passing them to <RouteHandler> (in v0.13.x) or the Route component itself in v1.0;

// v0.13.x
<RouteHandler/>
<RouteHandler someExtraProp={something}/>

// v1.0
{this.props.children}
{React.cloneElement(this.props.children, {someExtraProp: something })}

(from the upgrade guide at https://github.com/rackt/react-router/releases/tag/v1.0.0)

All child handlers will receive the same set of props - this may be useful or not depending on the circumstance.

Why do I need to override the equals and hashCode methods in Java?

Assume you have class (A) that aggregates two other (B) (C), and you need to store instances of (A) inside hashtable. Default implementation only allows distinguishing of instances, but not by (B) and (C). So two instances of A could be equal, but default wouldn't allow you to compare them in correct way.

Vim multiline editing like in sublimetext?

Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)

How do I calculate someone's age based on a DateTime type birthday?

Just because I don't think the top answer is that clear:

public static int GetAgeByLoop(DateTime birthday)
{
    var age = -1;

    for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
    {
        age++;
    }

    return age;
}

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

HTTP GET request in JavaScript?

<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>

 <script>
        function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
            var url = "<Enter URL>";``
            xmlhttp.onload = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
                    document.getElementById("demo").innerHTML = this.responseText;
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    </script>

jQuery 'input' event

I think 'input' simply works here the same way 'oninput' does in the DOM Level O Event Model.

Incidentally:

Just as silkfire commented it, I too googled for 'jQuery input event'. Thus I was led to here and astounded to learn that 'input' is an acceptable parameter to jquery's bind() command. In jQuery in Action (p. 102, 2008 ed.) 'input' is not mentionned as a possible event (against 20 others, from 'blur' to 'unload'). It is true that, on p. 92, the contrary could be surmised from rereading (i.e. from a reference to different string identifiers between Level 0 and Level 2 models). That is quite misleading.

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

How can I add new array elements at the beginning of an array in Javascript?

you can reverse your array and push the data , at the end again reverse it:

var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

How can I set a DateTimePicker control to a specific date?

FYI: If you are setting the value, and not seeing anything - you might check to see if you have a 'CustomFormat' set - I just hit this and it was set to ' ' for the 1/1/1900 value (our 'not set' value) and set to MM/dd/yyyy if not.

HTML5 Audio stop function

The simple way to get around this error is to catch the error.

audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:

_x000D_
_x000D_
function playSound(sound) {_x000D_
  sfx.pause();_x000D_
  sfx.currentTime = 0;_x000D_
  sfx.src = sound;_x000D_
  sfx.play().catch(e => e);_x000D_
}
_x000D_
_x000D_
_x000D_

Note: You may want to replace the arrow function with an anonymous function for backward compatibility.

How do I install the OpenSSL libraries on Ubuntu?

  1. Go to the official website and download the source code for the version you need

  2. Then unzip the update package and execute the following command

    ./config --prefix=/usr/local/ssl --openssldir=/usr/local/ssl  -Wl,-rpath,/usr/local/ssl/lib shared
    

Because the default is to generate only static libraries, if you want dynamic libraries, add the "shared" option

  1. make && make install

java.util.NoSuchElementException: No line found

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

Removing the title text of an iOS UIBarButtonItem

This worked for me in iOS10. Call this from viewDidLoad of the view controller.

self.navigationController?.navigationBar.topItem?.title = ""

E11000 duplicate key error index in mongodb mongoose

I had same Issue. Problem was that I have removed one field from model. When I dropped db it fixes

How to set Internet options for Android emulator?

for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon">
        <activity android:name=".WebViewDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

80-characters / right margin line in Sublime Text 3

For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.

This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.

Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts

On stackoverflow, see:

Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?

MattDMo's answer here: What is the default font of Sublime Text?

I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)

Other viewing environments that benefit from shorter lines: github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.

Is it better to return null or empty collection?

Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).

How to check if a String is numeric in Java

Regex Matching

Here is another example upgraded "CraigTP" regex matching with more validations.

public static boolean isNumeric(String str)
{
    return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
  1. Only one negative sign - allowed and must be in beginning.
  2. After negative sign there must be digit.
  3. Only one decimal sign . allowed.
  4. After decimal sign there must be digit.

Regex Test

1                  --                   **VALID**
1.                 --                   INVALID
1..                --                   INVALID
1.1                --                   **VALID**
1.1.1              --                   INVALID

-1                 --                   **VALID**
--1                --                   INVALID
-1.                --                   INVALID
-1.1               --                   **VALID**
-1.1.1             --                   INVALID

Rounding to two decimal places in Python 2.7?

print "financial return of outcome 1 = $%.2f" % (out1)

Converting string "true" / "false" to boolean value

You could simply have: var result = (str == "true").

How to view kafka message

You can use console consumer to view messages produced on some topic:

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

How do I delete multiple rows with different IDs?

If you have to select the id:

 DELETE FROM table WHERE id IN (SELECT id FROM somewhere_else)

If you already know them (and they are not in the thousands):

 DELETE FROM table WHERE id IN (?,?,?,?,?,?,?,?)

Java: How to access methods from another class

Method 1:

If the method DoSomethingBeta was static you need only call:

Beta.DoSomethingBeta();

Method 2:

If Alpha extends from Beta you could call DoSomethingBeta() directly.

public class Alpha extends Beta{
     public void DoSomethingAlpha() {
          DoSomethingBeta();  //?
     }
}

Method 3:

Alternatively you need to have access to an instance of Beta to call the methods from it.

public class Alpha {
     public void DoSomethingAlpha() {
          Beta cbeta = new Beta();
          cbeta.DoSomethingBeta();  //?
     }
}

Incidentally is this homework?

Dynamically adding HTML form field using jQuery

something like so might work:

<script type="text/javascript">
$(document).ready(function(){
    var $input = $("<input name='myField' type='text'>");
    $('#section2').append($input);
});
</script>

<form>
    <div id="section1"><!-- some controls--></div>
    <div id="section2"><!-- for dynamic controls--></div>
</form>

How to update multiple columns in single update statement in DB2

For the sake of completeness and the edge case of wanting to update all columns of a row, you can do the following, but consider that the number and types of the fields must match.

Using a data structure

exec sql UPDATE TESTFILE
         SET ROW = :DataDs
         WHERE CURRENT OF CURSOR; //If using a cursor for update

Source: rpgpgm.com

SQL only

UPDATE t1 SET ROW = (SELECT *
                     FROM   t2
                     WHERE  t2.c3 = t1.c3)

Source: ibm.com

Remove columns from dataframe where ALL values are NA

Late to the game but you can also use the janitor package. This function will remove columns which are all NA, and can be changed to remove rows that are all NA as well.

df <- janitor::remove_empty(df, which = "cols")

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

How to install Java 8 on Mac

brew cask install caskroom/versions/java8

Convert java.util.Date to String

Let's try this

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Or a utility function

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

From Convert Date to String in Java

Tuple unpacking in for loops

The enumerate function returns a generator object which, at each iteration, yields a tuple containing the index of the element (i), numbered starting from 0 by default, coupled with the element itself (a), and the for loop conveniently allows you to access both fields of those generated tuples and assign variable names to them.

How to invoke the super constructor in Python?

I use the following formula that extends previous answers:

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(self.__class__, self).__init__()

B()

This way you don't have to repeat the name of the class in the call to super. It can come handy if you are coding a large number of classes, and want to make your code in the initialiser methods independent of the class name.

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

How to add additional libraries to Visual Studio project?

For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.

Next open Configuration Properties and then Linker.

Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,

Linker -> Input you'll add the actual library files under Additional Dependencies.

For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.

If there is a dll have a copy of it in your main project folder, and done.

I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.

Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.

This was written for Visual Studio 2008. For 2010 it should be roughly the same.

Format string to a 3 digit number

This is how it's done using string interpolation C# 7

$"{myString:000}"

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }
    }
</style>

....

<div id="wrapper">
    <!-- your html for your website -->
</div>
<div id="warning-message">
    this website is only viewable in landscape mode
</div>

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.

Update

I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

Open application after clicking on Notification

This is the way that I have approached.

public class AppFCMService extends FirebaseMessagingService {

    private final static String TAG = "FCM Message";
    String notify, requstId, Notification;
    PendingIntent pendingIntent;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        //split string and getting order id from notification
        String Str = remoteMessage.getNotification().getBody();
        String[] tmp;
        tmp = Str.split(" ");
        String temp1 = tmp[0];
        String temp2 = tmp[1];
        String id = tmp[2];
        notify = temp1 + " " + temp2;
        requstId = id;
        showNotification(remoteMessage.getNotification().getBody());
    }

    private void showNotification(String messageBody) {
        // check whether session has been initiated or not
        if (new SessionHelper(getApplicationContext()).isLoggedIn()) {

            if (notify.equalsIgnoreCase("Travel request")) {

                Intent intent = new Intent(this, ViewTravelDetailsActivity.class);
                intent.putExtra("TravelRequestID", requstId);
                intent.putExtra("BackPress", "Notify");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);

            } else if (notify.equalsIgnoreCase("Timesheet replied")) {

                Intent intent = new Intent(this, ViewReplyActivity.class);
                intent.putExtra("timesheetActivityID", requstId);
                intent.putExtra("BackPress", "Notify");
                intent.putExtra("RealmData", "DeleteRealm");
                intent.putExtra("isToday", "true");
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            } else {

                Intent intent = new Intent(this, Dashboard.class);
                intent.putExtra("timesheetActivityID", requstId);
                pendingIntent = PendingIntent.getActivity(this, 0, intent,
                        PendingIntent.FLAG_ONE_SHOT);
            }
        } else {

            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("timesheetActivityID", requstId);
            pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        Bitmap notifyImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(notifyImage)
                .setColor(Color.parseColor("#FFE74C3C"))
                .setContentTitle("TEST")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

What's the proper way to compare a String to an enum value?

You can use equals().

enum.equals(String)