Programs & Examples On #Occi

Oracle C++ Call Interface (OCCI) is a high-performance and comprehensive API to access the Oracle database.

Cannot find module cv2 when using OpenCV

pip install opencv-python

or

pip install opencv-python3 

will definately works fine

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

$(document).ready(function(){
   // Your code here
});

Would seem to do what you are after.

How can I present a file for download from an MVC controller?

You can do the same in Razor or in the Controller, like so..

@{
    //do this on the top most of your View, immediately after `using` statement
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}

Or in the Controller..

public ActionResult Receipt() {
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");

    return View();
}

I tried this in Chrome and IE9, both is downloading the pdf file.

I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF

Unable to convert MySQL date/time value to System.DateTime

Let MySql convert your unix timestamp to string. Use the mysql function FROM_UNIXTIME( 113283901 )

How to add an extra column to a NumPy array

Assuming M is a (100,3) ndarray and y is a (100,) ndarray append can be used as follows:

M=numpy.append(M,y[:,None],1)

The trick is to use

y[:, None]

This converts y to a (100, 1) 2D array.

M.shape

now gives

(100, 4)

forEach is not a function error with JavaScript array

You can use childNodes instead of children, childNodes is also more reliable considering browser compatibility issues, more info here:

parent.childNodes.forEach(function (child) {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

Tensorflow: Using Adam optimizer

You need to call tf.global_variables_initializer() on you session, like

init = tf.global_variables_initializer()
sess.run(init)

Full example is available in this great tutorial https://www.tensorflow.org/get_started/mnist/mechanics

Disable click outside of bootstrap modal area to close modal

For Bootstrap 4.x, you can do like this :

$('#modal').data('bs.modal')._config.backdrop = 'static';
$('#modal').data('bs.modal')._config.keyboard = false;

Node.js – events js 72 throw er unhandled 'error' event

Check your terminal it happen only when you have your application running on another terminal..

The port is already listening..

if-else statement inside jsx: ReactJS

What about switch case instead of if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
      default: 
        return <></>;
    }

Moment JS - check if a date is today or in the future

Simplest answer will be:

const firstDate = moment('2020/10/14'); // the date to be checked
const secondDate = moment('2020/10/15'); // the date to be checked

firstDate.startOf('day').diff(secondDate.startOf('day'), 'days'); // result = -1
secondDate.startOf('day').diff(firstDate.startOf('day'), 'days'); // result = 1

It will check with the midnight value and will return an accurate result. It will work also when time diff between two dates is less than 24 hours also.

How do I mock an autowired @Value field in Spring with Mockito?

You can also mock your property configuration into your test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest 
{ 
   @Configuration
   public static class MockConfig{
       @Bean
       public Properties myProps(){
             Properties properties = new Properties();
             properties.setProperty("default.url", "myUrl");
             properties.setProperty("property.value2", "value2");
             return properties;
        }
   }
   @Value("#{myProps['default.url']}")
   private String defaultUrl;

   @Test
   public void testValue(){
       Assert.assertEquals("myUrl", defaultUrl);
   }
}

How to get all table names from a database?

@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{ 

    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
    DatabaseMetaData md = con.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
    List<String> tables = new ArrayList<String>();
    String db = "";
    while (rs.next()) {
        tables.add(rs.getString(3));
        db = rs.getString(1);
    }
    List<String> database = new ArrayList<String>();
    database.add(db);
    databaseTables.put("database", database);
    Collections.reverse(tables);
    databaseTables.put("tables", tables);
    return new ObjectMapper().writeValueAsString(databaseTables);
}

@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{ 
    System.out.println("...tablename......"+tablename);
    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();       
     Statement st = con.createStatement();
     String sql = "select * from "+tablename;
     ResultSet rs = st.executeQuery(sql);
     ResultSetMetaData metaData = rs.getMetaData();
     int rowCount = metaData.getColumnCount();    
     List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
     HashMap<String,String> columnDetails = new HashMap<String,String>();
     for (int i = 0; i < rowCount; i++) {
         columnDetails = new HashMap<String,String>();
         Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
         method.setAccessible(true);
         com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
         columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
         columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
         columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
         columnDetails.put("columnColl", field.getCollation());
         columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
         if (field.isPrimaryKey()) {
             columnDetails.put("columnKEY", "PRI");
         } else if(field.isMultipleKey()) {
             columnDetails.put("columnKEY", "MUL");
         } else if(field.isUniqueKey()) {
             columnDetails.put("columnKEY", "UNI");
         } else {
             columnDetails.put("columnKEY", "");
         }
         columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
         databaseColumns.add(columnDetails);
     }
    HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
    Collections.reverse(databaseColumns);
    tableColumns.put("columns", databaseColumns);
    return new ObjectMapper().writeValueAsString(tableColumns);
}

jQuery select change show/hide div event

change your jquery method to

$(function () { /* DOM ready */
    $("#type").change(function () {
        alert('The option with value ' + $(this).val());
        //hide the element you want to hide here with
        //("id").attr("display","block"); // to show
        //("id").attr("display","none"); // to hide
    });
});

How can I convert an HTML table to CSV?

Based on audiodude's answer, but simplified by using the built-in CSV library

require 'nokogiri'
require 'csv'

doc = Nokogiri::HTML(table_string)
csv = CSV.open("output.csv", 'w')

doc.xpath('//table//tr').each do |row|
    tarray = [] #temporary array
    row.xpath('td').each do |cell|
        tarray << cell.text #Build array of that row of data.
    end
    csv << tarray #Write that row out to csv file
end

csv.close

I did wonder if there was any way to take the Nokogiri NodeSet (row.xpath('td')) and write this out as an array to the csv file in one step. But I could only figure out doing it by iterating over each cell and building the temporary array of each cell's content.

How to clear a data grid view

If it's bound to a datasource -

dataGridView.DataSource=null;
dataGridView.Rows.Clear();

Worked for me.

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

Python group by

Python's built-in itertools module actually has a groupby function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:

from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), 
 ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), 
 ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')] 
input.sort(key=sortkeyfn)

Now input looks like:

[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
 ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
 ('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]

groupby returns a sequence of 2-tuples, of the form (key, values_iterator). What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:

from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
    result.append(dict(type=key, items=list(v[0] for v in valuesiter)))

Now result contains your desired dict, as stated in your question.

You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby, this would look like:

result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
    result[key] = list(v[0] for v in valuesiter)

result now contains this dict (this is similar to the intermediate res defaultdict in @KennyTM's answer):

{'NOT': ['9085267', '11788544'], 
 'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 
 'KAT': ['11013331', '9843236']}

(If you want to reduce this to a one-liner, you can:

result = dict((key,list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn))

or using the newfangled dict-comprehension form:

result = {key:list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn)}

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

I can't install python-ldap

Windows: I completely agree with the accepted answer, but digging through the comments took a while to get to the meat of what I needed. I ran across this specific problem with Reviewboard on Windows using the Bitnami. To give an answer for windows then, I used this link mentioned in the comments:

Then, executed the following commands

easy_install pip
pip install python_ldap-2.4.20-cp27-none_win32.whl

(because I had python 2.7 and a 32bit install at that)

easy_install python-ldap

The transaction log for the database is full

Try this:

If possible restart the services MSSQLSERVER and SQLSERVERAGENT.

Swift 3: Display Image from URL

Use extension for UIImageView to Load URL Images.

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func imageURLLoad(url: URL) {

        DispatchQueue.global().async { [weak self] in
            func setImage(image:UIImage?) {
                DispatchQueue.main.async {
                    self?.image = image
                }
            }
            let urlToString = url.absoluteString as NSString
            if let cachedImage = imageCache.object(forKey: urlToString) {
                setImage(image: cachedImage)
            } else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    imageCache.setObject(image, forKey: urlToString)
                    setImage(image: image)
                }
            }else {
                setImage(image: nil)
            }
        }
    }
}

How to display length of filtered ng-repeat data

For Angular 1.3+ (credits to @Tom)

Use an alias expression (Docs: Angular 1.3.0: ngRepeat, scroll down to the Arguments section):

<div ng-repeat="person in data | filter:query as filtered">
</div>

For Angular prior to 1.3

Assign the results to a new variable (e.g. filtered) and access it:

<div ng-repeat="person in filtered = (data | filter: query)">
</div>

Display the number of results:

Showing {{filtered.length}} Persons

Fiddle a similar example. Credits go to Pawel Kozlowski

Vertical and horizontal align (middle and center) with CSS

This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.

The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.

Example: http://jsbin.com/ipawe/edit

Basic CSS:

#mydiv { 
    position: absolute;
    top: 50%;
    left: 50%;
    height: 400px;
    width: 700px;
    margin-top: -200px; /* -(1/2 height) */
    margin-left: -350px; /* -(1/2 width) */
  }

Git keeps prompting me for a password

This happened to me when I upgraded to macOS v10.12 (Sierra). Looks like the SSH agent got cleared upon upgrade.

$ ssh-add -L
The agent has no identities.

Simply running ssh-add located my existing identity. I entered the password and was good to go again.

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

Writing to a file in a for loop

The main problem was that you were opening/closing files repeatedly inside your loop.

Try this approach:

with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:  
    for line in text_file:
        var1, var2 = line.split(",");
        myfile.write(var1+'\n')

We open both files at once and because we are using with they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.

We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).

Note that write() doesn't append a newline ('\n') so you'll have to do that yourself if you need it (I replaced your writelines() with write() as you are writing a single item, not a list of items).

When opening a file for rread, the 'r' is optional since it's the default mode.

How to set environment variables in Python?

to Set Variable:

item Assignment method using key:

import os    
os.environ['DEBUSSY'] = '1'  #Environ Variable must be string not Int

to get or to check whether its existed or not,

since os.environ is an instance you can try object way.

Method 1:

os.environ.get('DEBUSSY') # this is error free method if not will return None by default

will get '1' as return value

Method 2:

os.environ['DEBUSSY'] # will throw an key error if not found!

Method 3:

'DEBUSSY' in os.environ  # will return Boolean True/False

Method 4:

os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements

mysql: get record count between two date-time

for speed you can do this

WHERE date(created_at) ='2019-10-21'

PHP session handling errors

I had the same error everything was correct like the setting the folder permissions.

It looks like an bug in php in my case because when i delete my PHPSESSID cookie it was working again so aperently something was messed up and the session got removed but the cookie was still active so php had to define the cause differently and checking first if the session file is still they and give another error and not the permission error

PHPMailer character encoding issues

I was getting &oacute; in $mail->Subject /w PHPMailer.

So for me the complete solution is:

// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';

$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);

Hope it helps.

C++ static virtual members?

Well , quite a late answer but it is possible using the curiously recurring template pattern. This wikipedia article has the info you need and also the example under static polymorphism is what you are asked for.

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

Sort ObservableCollection<string> through C#

Introduction

Basically, if there is a need to display a sorted collection, please consider using the CollectionViewSource class: assign ("bind") its Source property to the source collection — an instance of the ObservableCollection<T> class.

The idea is that CollectionViewSource class provides an instance of the CollectionView class. This is kind of "projection" of the original (source) collection, but with applied sorting, filtering, etc.

References:

Live Shaping

WPF 4.5 introduces "Live Shaping" feature for CollectionViewSource.

References:

Solution

If there still a need to sort an instance of the ObservableCollection<T> class, here is how it can be done. The ObservableCollection<T> class itself does not have sort method. But, the collection could be re-created to have items sorted:

// Animals property setter must raise "property changed" event to notify binding clients.
// See INotifyPropertyChanged interface for details.
Animals = new ObservableCollection<string>
    {
        "Cat", "Dog", "Bear", "Lion", "Mouse",
        "Horse", "Rat", "Elephant", "Kangaroo",
        "Lizard", "Snake", "Frog", "Fish",
        "Butterfly", "Human", "Cow", "Bumble Bee"
    };
...
Animals = new ObservableCollection<string>(Animals.OrderBy(i => i));

Additional details

Please note that OrderBy() and OrderByDescending() methods (as other LINQ–extension methods) do not modify the source collection! They instead create a new sequence (i.e. a new instance of the class that implements IEnumerable<T> interface). Thus, it is necessary to re-create the collection.

"Invalid form control" only in Google Chrome

this error get if add decimal format. i just add

step="0.1"

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

Append lines to a file using a StreamWriter

One more simple way is using the File.AppendText it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter

using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{                                                
    sw.WriteLine("this is a log");
}

Django error - matching query does not exist

You can use this:

comment = Comment.objects.filter(pk=comment_id)

Converting an int into a 4 byte char array (C)

Do you want to address the individual bytes of a 32-bit int? One possible method is a union:

union
{
    unsigned int integer;
    unsigned char byte[4];
} foo;

int main()
{
    foo.integer = 123456789;
    printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
}

Note: corrected the printf to reflect unsigned values.

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Angular File Upload

Personally I'm doing this using ngx-material-file-input for the front-end, and Firebase for the back-end. More precisely Cloud Storage for Firebase for the back-end combined with Cloud Firestore. Below an example, which limits file to be not larger than 20 MB, and accepts only certain file extensions. I'm also using Cloud Firestore for storing links to the uploaded files, but you can skip this.

contact.component.html

<mat-form-field>
  <!--
    Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
  -->
  <ngx-mat-file-input
    [accept]="[
      '.doc',
      '.docx',
      '.jpg',
      '.jpeg',
      '.pdf',
      '.png',
      '.xls',
      '.xlsx'
    ]"
    (change)="uploadFile($event)"
    formControlName="fileUploader"
    multiple
    aria-label="Here you can add additional files about your project, which can be helpeful for us."
    placeholder="Additional files"
    title="Additional files"
    type="file"
  >
  </ngx-mat-file-input>
  <mat-icon matSuffix>folder</mat-icon>
  <mat-hint
    >Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
    maximum files upload size: 20 MB.
  </mat-hint>
  <!--
    Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
  -->
  <mat-error
    *ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
  >
    This size is too large,
    <strong
      >maximum acceptable upload size is
      {{
        contactForm.get('fileUploader')?.getError('maxContentSize')
          .maxSize | byteFormat
      }}</strong
    >
    (uploaded size:
    {{
      contactForm.get('fileUploader')?.getError('maxContentSize')
        .actualSize | byteFormat
    }}).
  </mat-error>
</mat-form-field>

contact.component.ts (size validator part)

import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

/**
 * @constructor
 * @description Creates a new instance of this component.
 * @param  {formBuilder} - an abstraction class object to create a form group control for the contact form.
 */
constructor(
  private angularFirestore: AngularFirestore,
  private angularFireStorage: AngularFireStorage,
  private formBuilder: FormBuilder
) {}

public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
    fileUploader: [
      '',
      Validators.compose([
        FileValidator.maxContentSize(this.maxFileSize),
        Validators.maxLength(512),
        Validators.minLength(2)
      ])
    ]
})

contact.component.ts (file uploader part)

import { AngularFirestore } from '@angular/fire/firestore';
import {
  AngularFireStorage,
  AngularFireStorageReference,
  AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';

public downloadURL: string[] = [];
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
   * @param {event} - object of sent files.
   * @returns {void}
   */
  public uploadFile(event: any): void {
    // Iterate through all uploaded files.
    for (let i = 0; i < event.target.files.length; i++) {
      const randomId = Math.random()
        .toString(36)
        .substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.

      const file = event.target.files[i]; // Get each uploaded file.

      // Get file reference.
      const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
        randomId
      );

      // Create upload task.
      const task: AngularFireUploadTask = this.angularFireStorage.upload(
        randomId,
        file
      );

      // Upload file to Cloud Firestore.
      task
        .snapshotChanges()
        .pipe(
          finalize(() => {
            fileRef.getDownloadURL().subscribe((downloadURL: string) => {
              this.angularFirestore
                .collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
                .add({ downloadURL: downloadURL });
              this.downloadURL.push(downloadURL);
            });
          }),
          catchError((error: any) => {
            return throwError(error);
          })
        )
        .subscribe();
    }
  }

storage.rules

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
        allow read; // Required in order to send this as attachment.
      // Allow write files Firebase Storage, only if:
      // 1) File is no more than 20MB
      // 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
      allow write: if request.resource.size <= 20 * 1024 * 1024
        && (request.resource.contentType.matches('application/msword')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        || request.resource.contentType.matches('image/jpg')
        || request.resource.contentType.matches('image/jpeg')
        || request.resource.contentType.matches('application/pdf')
                || request.resource.contentType.matches('image/png')
        || request.resource.contentType.matches('application/vnd.ms-excel')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    }
  }
}

How do I print bold text in Python?

print '\033[1m  Your Name  \033[0m'

\033[1m is the unicode for bold in the terminal \033[0m is the unicode for end the edited text and back default text formate!!!!!

if you do not use \033[0m than all upcoming text of the terminal will become bold!!!!!!!!!

Python csv string to array

Simple - the csv module works with lists, too:

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]

How to kill a child process after a given timeout in Bash?

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

If you don't mind downloading something, use timeout (sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils)

timeout 10 ping www.goooooogle.com

If you don't want to download something, do what timeout does internally:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )

In case that you want to do a timeout for longer bash code, use the second option as such:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 www.goooooogle.com 
     do 
         echo crap; 
     done )

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

How do I compare two DateTime objects in PHP 5.2.8?

As of PHP 7.x, you can use the following:

$aDate = new \DateTime('@'.(time()));
$bDate = new \DateTime('@'.(time() - 3600));

$aDate <=> $bDate; // => 1, `$aDate` is newer than `$bDate`

C# declare empty string array

Your syntax is invalid.

string[] arr = new string[5];

That will create arr, a referenced array of strings, where all elements of this array are null. (Since strings are reference types)

This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null.

Single-Dimensional Arrays (C# Programming Guide)

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

android.content.Context.getPackageName()' on a null object reference

Use can use in global

Context context;

and create a constructor and passing the context. LoginClass is name of the class

LoginClass(Context context)
{this.context=context;}

and also when we call the class then use getApplicationContext like LoginClass lclass = new LoginClass(getApplicationContext) thats it.

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

Hi everyone I found the solution regarding this github issue and it works for me no longer able to use private ssh key

Try following theses steps:

1 - Use HTTPS if possible. That will avoid SSH keys entirely.
2 - Manually add the SSH key to the running SSH agent. See manually generate ssh key
3 - If the two others doesn't work, delete all your ssh keys and generate some new one thats what I did after weeks of issues.

Hope it will help you..

Package php5 have no installation candidate (Ubuntu 16.04)

Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.

Mine PHP version is 7.0, so i tried the below command.

apt-get install php-pgsql

Remember to restart Apache.

/etc/init.d/apache2 restart

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...

I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops. In a recent case I used the following solution:

$("#content").on('click', '#replace', (function(event){ return confirm('Are you sure you want to do that?') }));

Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!

How to pass command line arguments to a shell alias?

I found that functions cannot be written in ~/.cshrc file. Here in alias which takes arguments

for example, arguments passed to 'find' command

alias fl "find . -name '\!:1'"     
Ex: >fl abc

where abc is the argument passed as !:1

Check if String contains only letters

Faster way is below. Considering letters are only a-z,A-Z.

public static void main( String[] args ){ 
        System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
        System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));

        System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
        System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
    }

    public static boolean bettertWay(String name) {
        char[] chars = name.toCharArray();
        long startTimeOne = System.nanoTime();
        for(char c : chars){
            if(!(c>=65 && c<=90)&&!(c>=97 && c<=122) ){
                System.out.println(System.nanoTime() - startTimeOne);
                    return false;
            }
        }
        System.out.println(System.nanoTime() - startTimeOne);
        return true;
    }


    public static boolean isAlpha(String name) {
        char[] chars = name.toCharArray();
        long startTimeOne = System.nanoTime();
        for (char c : chars) {
            if(!Character.isLetter(c)) {
                System.out.println(System.nanoTime() - startTimeOne);
                return false;
            }
        }
        System.out.println(System.nanoTime() - startTimeOne);
        return true;
    }

Runtime is calculated in nano seconds. It may vary system to system.

5748//bettertWay without numbers
true
89493 //isAlpha without  numbers
true
3284 //bettertWay with numbers
false
22989 //isAlpha with numbers
false

How do you make an element "flash" in jQuery

Here's a solution that uses a mix of jQuery and CSS3 animations.

http://jsfiddle.net/padfv0u9/2/

Essentially you start by changing the color to your "flash" color, and then use a CSS3 animation to let the color fade out. You need to change the transition duration in order for the initial "flash" to be faster than the fade.

$(element).removeClass("transition-duration-medium");
$(element).addClass("transition-duration-instant");
$(element).addClass("ko-flash");
setTimeout(function () {
    $(element).removeClass("transition-duration-instant");
    $(element).addClass("transition-duration-medium");
    $(element).removeClass("ko-flash");
}, 500);

Where the CSS classes are as follows.

.ko-flash {
    background-color: yellow;
}
.transition-duration-instant {
    -webkit-transition-duration: 0s;
    -moz-transition-duration: 0s;
    -o-transition-duration: 0s;
    transition-duration: 0s;
}
.transition-duration-medium {
    -webkit-transition-duration: 1s;
    -moz-transition-duration: 1s;
    -o-transition-duration: 1s;
    transition-duration: 1s;
}

Copy all the lines to clipboard

I know ten years on this should be settled but the first two answers did not work for me so I kept digging. On a Redhat (remote server) - Windows 10 (local machine), if you cannot select the whole thing with a mouse, you are stuck because the usual copies do not work between the remote and the local machine clipboards.

So, to copy on the remote Linux and to paste on the local Windows, specify the primary buffer with the * and do a nice double yank

Use gg" * yy.

Making a button invisible by clicking another button in HTML

For Visible:

document.getElementById("test").style.visibility="visible";

For Invisible:

document.getElementById("test").style.visibility="hidden";

MySQL DROP all tables, ignoring foreign keys

You can do:

select concat('drop table if exists ', table_name, ' cascade;')
  from information_schema.tables;

Then run the generated queries. They will drop every single table on the current database.

Here is some help on drop table command.

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

This will solve your problem in macOS:

pico ~/.bash_profile

export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export ANDROID_SDK_HOME=/Users/$USER/Library/Android/sdk
export ANDROID_AVD_HOME=/Users/$USER/.android/avd
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$ANDROID_AVD_HOME

source ~/.bash_profile

Type.GetType("namespace.a.b.ClassName") returns null

I cheated. Since the types I want to create (by name) are all in In a dll I control, I just put a static method in the dll in the assembly that takes a simple name, and calls type.GetType from that context and returns the result.

The original purpose was so that the type could be specified by name in configuration data. I've since change the code so that the user specified a format to process. The format handler classes implement a interface that determines if the type can parse the specified format. I then use reflection to find types that implement the interface, and find one that handles the format. So now the configuration specifies a format name, a not a specific type. The reflection code can look at adjacent dlls and load, them so I have a sort poor man's plug-in architecture.

How to change 1 char in the string?

I suggest you to use StringBuilder class for it and than parse it to string if you need.

System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();

You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower() it makes new string and your previous string doesn't change.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

I had this issue with JetBrains Rider, specifically for port 80 and 90 bit it was working with other ports as well as visual studio.

after running as admin this resolved the issue.

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

How to restore the menu bar in Visual Studio Code

Press Alt to make the menu visible and then in the View menu choose Appearance -> Show Menu Bar.

macOS: If you are in Full-Screen mode you can either move the cursor to the top of the screen to see the menu, or you can exit Full-Screen using Ctrl+Cmd+F, or ^?F in alien's script.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

There is also some more detail on the use of <mvc:annotation-driven /> in the Spring docs. In a nutshell, <mvc:annotation-driven /> gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.

Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven /> enables the use of the @Transaction annotation, <task:annotation-driven /> is required for @Scheduled et al...

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

Convert seconds to Hour:Minute:Second

In java you can use this way.

   private String getHmaa(long seconds) {
    String string;
    int hours = (int) seconds / 3600;
    int remainder = (int) seconds - hours * 3600;
    int mins = remainder / 60;
    //remainder = remainder - mins * 60;
    //int secs = remainder;

    if (hours < 12 && hours > 0) {
        if (mins < 10) {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    } else if (hours >= 12) {
        if (mins < 10) {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? "0" + mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        } else {
            string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
        }
    } else {
        if (mins < 10) {
            string = String.valueOf("0" + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
        } else {
            string = String.valueOf("0" + ":" + (mins > 0 ? mins : "0") + " AM");
        }
    }
    return string;
}

Asus Zenfone 5 not detected by computer

I had the same problem. I solved it the following way :

1. Go to Settings->Storage->Click the USB icon at top
2. Make sure that MTP is selected

Sending an HTTP POST request on iOS

Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs

This method fills html forms inside Google Forms. Hope it helps someone using Swift.

var url = NSURL(string: urlstring)

var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)

Get all Attributes from a HTML element with Javascript/jQuery

Does this help?

This property returns all the attributes of an element into an array for you. Here is an example.

_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  var result = document.getElementById('result');_x000D_
  var spanAttributes = document.getElementsByTagName('span')[0].attributes;_x000D_
  for (var i = 0; i != spanAttributes.length; i++) {_x000D_
    result.innerHTML += spanAttributes[i].value + ',';_x000D_
  }_x000D_
});
_x000D_
<span name="test" message="test2"></span>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.

This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.

_x000D_
_x000D_
window.addEventListener('load',function(){_x000D_
  /*_x000D_
  collect all the elements you want the attributes_x000D_
  for into the variable "elementsToTrack"_x000D_
  */ _x000D_
  var elementsToTrack = $('body span, body div');_x000D_
  //variable to store all attributes for each element_x000D_
  var attributes = [];_x000D_
  //gather all attributes of selected elements_x000D_
  for(var i = 0; i != elementsToTrack.length; i++){_x000D_
    var currentAttr = elementsToTrack[i].attributes;_x000D_
    attributes.push(currentAttr);_x000D_
  }_x000D_
  _x000D_
  //print out all the attrbute names and values_x000D_
  var result = document.getElementById('result');_x000D_
  for(var i = 0; i != attributes.length; i++){_x000D_
    result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  _x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The writer of the database probably did a

sql = "SELECT * FROM STUDENTS WHERE (STUDENT_NAME = '" + student_name + "') AND other stuff";
execute(sql);

If student_name is the one given, that does the selection with the name "Robert" and then drops the table. The "-- " part changes the rest of the given query into a comment.

How do you post to an iframe?

If you want to change inputs in an iframe then submit the form from that iframe, do this

...
var el = document.getElementById('targetFrame');

var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below

if (frame_win) {
  doc = (window.contentDocument || window.document);
}

if (doc) {
  doc.forms[0].someInputName.value = someValue;
  ...
  doc.forms[0].submit();
}
...

Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

Angular 2 two way binding using ngModel is not working

Note : To allow the ngModel exists Independently inside reactive form, we have to use ngModelOptions as follows:

 [ngModelOptions]="{ standalone: true }"

For Example :

 <mat-form-field appearance="outline" class="w-100">
            <input
              matInput 
              [(ngModel)]="accountType"
              [ngModelOptions]="{ standalone: true }"
            />
 </mat-form-field>

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

Remove Server Response Header IIS7

UrlScan can also remove the server header by using AlternateServerName= under [options].

tar: add all files and directories in current directory INCLUDING .svn and so on

10 years later, you have an alternative to tar, illustrated with Git 2.30 (Q1 2021), which uses "git archive"(man) to produce the release tarball instead of tar.
(You don't need Git 2.30 to apply that alternative)

See commit 4813277 (11 Oct 2020), and commit 93e7031 (10 Oct 2020) by René Scharfe (rscharfe).
(Merged by Junio C Hamano -- gitster -- in commit 63e5273, 27 Oct 2020)

Makefile: use git init/add/commit/archive for dist-doc

Signed-off-by: René Scharfe

Reduce the dependency on external tools by generating the distribution archives for HTML documentation and manpages using git(man) commands instead of tar. This gives the archive entries the same meta data as those in the dist archive for binaries.

So instead of:

tar cf ../archive.tar .

You can do using Git only:

git -C workspace init
git -C workspace add .
git -C workspace commit -m workspace
git -C workspace archive --format=tar --prefix=./ HEAD^{tree} > workspace.tar
rm -Rf workspace/.git

That was initially proposed because, as explained here, some exotic platform might have an old tar distribution with lacking options.

UML diagram shapes missing on Visio 2013

If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.

  • Search for UML Sequence in the search box -> Select all shapes and add to My shapes (user defined name).

You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.

How to concatenate two MP4 files using FFmpeg?

ffmpeg \
  -i input_1.mp4 \
  -i input_2.mp4 \
  -filter_complex '[0:v]pad=iw*2:ih[int];[int][1:v]overlay=W/2:0[vid]' \
  -map [vid] \
  -c:v libx264 \
  -crf 23 \
  -preset veryfast \
  output.mp4

Where is NuGet.Config file located in Visual Studio project?

Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.

You can also place the file at %appdata%\NuGet\NuGet.Config and it will be used everywhere.

https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file

Capitalize words in string

There's also locutus: https://locutus.io/php/strings/ucwords/ which defines it this way:

function ucwords(str) {
  //  discuss at: http://locutus.io/php/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva (http://waldo.malqui.info)
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld')
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD')
  //   returns 2: 'HELLO WORLD'
  //   example 3: ucwords('? ???? ??? ????????? ??????? ? ??? ??? ????? ??????')
  //   returns 3: '? ???? ??? ????????? ??????? ? ??? ??? ????? ??????'
  //   example 4: ucwords('t???st? a??p?? ßaf?? ??µ??? ??, d?as?e???e? ?p?? ?????? ?????')
  //   returns 4: '????st? ???p?? ?af?? ??µ??? G?, ??as?e???e? ?p?? ?????? ?????'

  return (str + '').replace(/^(.)|\s+(.)/g, function ($1) {
    return $1.toUpperCase();
  });
};

What is the different between RESTful and RESTless

Any model which don't identify resource and the action associated with is restless. restless is not any term but a slang term to represent all other services that doesn't abide with the above definition. In restful model resource is identified by URL (NOUN) and the actions(VERBS) by the predefined methods in HTTP protocols i.e. GET, POST, PUT, DELETE etc.

clear data inside text file in c++

Deleting the file will also remove the content. See remove file.

fatal: bad default revision 'HEAD'

This seems to occur when .git/HEAD refers to a branch which does not exist. I ran into this error in a repo that had nothing in .git/refs/heads. I have no idea how the repo got into that state, I inherited from someone that left the company.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Request Permission for Camera and Library in iOS 10 - Info.plist

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

Swift 4.0 and 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

Force Internet Explorer to use a specific Java Runtime Environment install?

Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

What issues should be considered when overriding equals and hashCode in Java?

For an inheritance-friendly implementation, check out Tal Cohen's solution, How Do I Correctly Implement the equals() Method?

Summary:

In his book Effective Java Programming Language Guide (Addison-Wesley, 2001), Joshua Bloch claims that "There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." Tal disagrees.

His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways. blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.

Example:

class Point {
    private int x;
    private int y;
    protected boolean blindlyEquals(Object o) {
        if (!(o instanceof Point))
            return false;
        Point p = (Point)o;
        return (p.x == this.x && p.y == this.y);
    }
    public boolean equals(Object o) {
        return (this.blindlyEquals(o) && o.blindlyEquals(this));
    }
}

class ColorPoint extends Point {
    private Color c;
    protected boolean blindlyEquals(Object o) {
        if (!(o instanceof ColorPoint))
            return false;
        ColorPoint cp = (ColorPoint)o;
        return (super.blindlyEquals(cp) && 
        cp.color == this.color);
    }
}

Note that equals() must work across inheritance hierarchies if the Liskov Substitution Principle is to be satisfied.

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Ellipsis for overflow text in dropdown boxes

The simplest solution might be to limit the number of characters in the HTML itself. Rails has a truncate(string, length) helper, and I'm certain that whichever backend you're using provides something similar.

Due to the cross-browser issues you're already familiar with regarding the width of select boxes, this seems to me to be the most straightforward and least error-prone option.

<select>
  <option value="1">One</option>
  <option value="100">One hund...</option>
<select>

How to use "like" and "not like" in SQL MSAccess for the same field?

What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.

I tested these on MS Access 2010 and are all valid:

  1. Like "BB"

  2. (Like "BB")

  3. (Not Like "BB")

Docker-Compose persistent data MySQL

You have to create a separate volume for mysql data.

So it will look like this:

volumes_from:
  - data
volumes:
  - ./mysql-data:/var/lib/mysql

And no, /var/lib/mysql is a path inside your mysql container and has nothing to do with a path on your host machine. Your host machine may even have no mysql at all. So the goal is to persist an internal folder from a mysql container.

EC2 instance has no public DNS

  1. Go to AWS Console.
  2. Go to Services and select VPC
  3. Click on vpc.
  4. select the instance and click on Action.
  5. Select Edit DNS Host name click on yes.

At the end you will get your Public dns.

Android button onClickListener

easy:

launching activity (onclick handler)

 Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
 myIntent.putExtra("key", value); //Optional parameters
 CurrentActivity.this.startActivity(myIntent);

on the new activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.

and add your new activity in the AndroidManifest.xml:

<activity android:label="@string/app_name" android:name="NextActivity"/>

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

Android - Set text to TextView

first your should create an object for text view TextView show_alter

show_alert = (TextView)findViewById(R.id.show_alert);
show_alert.setText("My Awesome Text");

libpng warning: iCCP: known incorrect sRGB profile

Thanks to the fantastic answer from Glenn, I used ImageMagik's "mogrify *.png" functionality. However, I had images buried in sub-folders, so I used this simple Python script to apply this to all images in all sub-folders and thought it might help others:

import os
import subprocess

def system_call(args, cwd="."):
    print("Running '{}' in '{}'".format(str(args), cwd))
    subprocess.call(args, cwd=cwd)
    pass

def fix_image_files(root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        # sys.stdout.write('.')
        for dir in dirs:
            system_call("mogrify *.png", "{}".format(os.path.join(path, dir)))


fix_image_files(os.curdir)

How to `wget` a list of URLs in a text file?

Quick man wget gives me the following:

[..]

-i file

--input-file=file

Read URLs from a local or external file. If - is specified as file, URLs are read from the standard input. (Use ./- to read from a file literally named -.)

If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. If --force-html is not specified, then file should consist of a series of URLs, one per line.

[..]

So: wget -i text_file.txt

Rounding a double to turn it into an int (java)

The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.

int a=Math.round(1.7f);

When it receives a double value, it will give you a long, therefore you have to typecast it to int.

int a=(int)Math.round(1.7);

This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.

What are invalid characters in XML

"XmlWriter and lower ASCII characters" worked for me

string code = Regex.Replace(item.Code, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", "");

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

Generating random numbers with normal distribution in Excel

Use the NORMINV function together with RAND():

=NORMINV(RAND(),10,7)

To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.


Sample output (column A), 500 numbers generated with this formula:

enter image description here

How to get the children of the $(this) selector?

You could also use

$(this).find('img');

which would return all imgs that are descendants of the div

Simplest way to form a union of two lists

The easiest way is to use LINQ's Union method:

var aUb = A.Union(B).ToList();

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

random.seed(): What does it do?

Here is my understanding. Every time we set a seed value, a "label" or " reference" is generated. The next random.function call is attached to this "label", so next time you call the same seed value and random.function, it will give you the same result.

np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186

np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755

np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948

What is the equivalent to getLastInsertId() in Cakephp?

You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?

If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.

Java: Finding the highest value in an array

Same as suggested by others, just mentioning the cleaner way of doing it:

int max = decMax[0];
for(int i=1;i<decMax.length;i++)
    max = Math.max(decMax[i],max);
System.out.println("The Maximum value is : " + max);

Language Books/Tutorials for popular languages

I know this is going to seem old-fashioned, but I don't think much of using online tutorials to learn programming languages or platforms. These generally give you no more than a little taste of the language. To really learn a language, you need the equivalent of a "book", and in many cases, this means a real dead-tree book.

If you want to learn C, read K&R. If you want to learn C++, read Stroustrup. If you want to learn Lisp/Scheme, read SICP. Etc.

If you're not willing to spend more than $30 and a few hours to learn a language, you probably aren't going to learn it.

Right query to get the current number of connections in a PostgreSQL DB

They definitely may give different results. The better one is

select count(*) from pg_stat_activity;

It's because it includes connections to WAL sender processes which are treated as regular connections and count towards max_connections.

See max_wal_senders

How to enable CORS on Firefox?

just type in your browser CORS add in firefox Then download this and install on browser finally you found top right side one Core spell to toggle that green for enable and red for not enable

Can I pass a JavaScript variable to another browser window?

The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain. If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).

What is the difference between Cloud, Grid and Cluster?

Cluster differs from Cloud and Grid in that a cluster is a group of computers connected by a local area network (LAN), whereas cloud and grid are more wide scale and can be geographically distributed. Another way to put it is to say that a cluster is tightly coupled, whereas a Grid or a cloud is loosely coupled. Also, clusters are made up of machines with similar hardware, whereas clouds and grids are made up of machines with possibly very different hardware configurations.

To know more about cloud computing, I recommend reading this paper: «Above the Clouds: A Berkeley View of Cloud Computing», Michael Armbrust, Armando Fox, Rean Griffith, Anthony D. Joseph, Randy H. Katz, Andrew Konwinski, Gunho Lee, David A. Patterson, Ariel Rabkin, Ion Stoica and Matei Zaharia. The following is an abstract from the above paper:

Cloud Computing refers to both the applications delivered as services over the Internet and the hardware and systems software in the datacenters that provide those services. The services themselves have long been referred to as Software as a Service (SaaS). The datacenter hardware and software is what we call a Cloud. When a Cloud is made available in a pay-as-you-go manner to the general public, we call it a Public Cloud; the service being sold is Utility Computing. We use the term Private Cloud to refer to internal datacenters of a business or other organization, not made available to the general public. Thus, Cloud Computing is the sum of SaaS and Utility Computing, but does not include Private Clouds. People can be users or providers of SaaS, or users or providers of Utility Computing.

The difference between a cloud and a grid can be expressed as below:

  1. Resource distribution: Cloud computing is a centralized model whereas grid computing is a decentralized model where the computation could occur over many administrative domains.

  2. Ownership: A grid is a collection of computers which is owned by multiple parties in multiple locations and connected together so that users can share the combined power of resources. Whereas a cloud is a collection of computers usually owned by a single party.

Examples of Clouds: Amazon Web Services (AWS), Google App Engine.

Examples of Grids: FutureGrid.

Examples of cloud computing services: Dropbox, Gmail, Facebook, Youtube, RapidShare.

How do I upload a file to an SFTP server in C# (.NET)?

There is no solution for this within the .net framework.

http://www.eldos.com/sbb/sftpcompare.php outlines a list of un-free options.

your best free bet is to extend SSH using Granados. http://www.routrek.co.jp/en/product/varaterm/granados.html

Appending a list or series to a pandas DataFrame as a row?

As mentioned here - https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, you'll need to first convert the list to a series then append the series to dataframe.

df = pd.DataFrame([[1, 2], [3, 4]], columns = ["a", "b"])
to_append = [5, 6]
a_series = pd.Series(to_append, index = df.columns)
df = df.append(a_series, ignore_index=True)

In reactJS, how to copy text to clipboard?

You should definitely consider using a package like @Shubham above is advising, but I created a working codepen based on what you described: http://codepen.io/dtschust/pen/WGwdVN?editors=1111 . It works in my browser in chrome, perhaps you can see if there's something I did there that you missed, or if there's some extended complexity in your application that prevents this from working.

// html
<html>
  <body>
    <div id="container">

    </div>
  </body>
</html>


// js
const Hello = React.createClass({
  copyToClipboard: () => {
    var textField = document.createElement('textarea')
    textField.innerText = 'foo bar baz'
    document.body.appendChild(textField)
    textField.select()
    document.execCommand('copy')
    textField.remove()
  },
  render: function () {
    return (
      <h1 onClick={this.copyToClipboard}>Click to copy some text</h1>
    )
  }
})

ReactDOM.render(
<Hello/>,
  document.getElementById('container'))

How to hide a navigation bar from first ViewController in Swift?

You could also create an extension for this so you will be able to reuse the extension without implementing this again and again in every view controller.

import UIKit

extension UIViewController {
    func hideNavigationBar(animated: Bool){
        // Hide the navigation bar on the this view controller
        self.navigationController?.setNavigationBarHidden(true, animated: animated)

    }

    func showNavigationBar(animated: Bool) {
        // Show the navigation bar on other view controllers
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

}

So you can use the extension methods as below

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

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        showNavigationBar(animated: animated)
    }

SQL multiple column ordering

The other answers lack a concrete example, so here it goes:

Given the following People table:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826

If you execute the query below:

SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC

The result set will look like this:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

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

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

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

How do I import a specific version of a package using go get?

The approach I've found workable is git's submodule system. Using that you can submodule in a given version of the code and upgrading/downgrading is explicit and recorded - never haphazard.

The folder structure I've taken with this is:

+ myproject
++ src
+++ myproject
+++ github.com
++++ submoduled_project of some kind.

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

How to build x86 and/or x64 on Windows from command line with CMAKE?

try use CMAKE_GENERATOR_PLATFORM

e.g.

// x86
cmake -DCMAKE_GENERATOR_PLATFORM=x86 . 

// x64
cmake -DCMAKE_GENERATOR_PLATFORM=x64 . 

How to embed images in html email

I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.

Regarding displaying embedded (inline) images, here's what's on their documentation:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

To give you a more complete example of how it would work:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

Edit:

Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.

One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.

For example:

You can replace the line that send the email:

$mail->Send();

With this:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

Hope that helps. Let me know if you run into trouble using it.

Delimiter must not be alphanumeric or backslash and preg_match

Maybe not related to original code example, but I received the error "Delimiter must not be alphanumeric or backslash" and Googled here. Reason: I mixed order of parameters for preg_match. Pattern was the second parameter and string to match was first. Be careful :)

How to sum up an array of integers in C#

If you don't prefer LINQ, it is better to use foreach loop to avoid out of index.

int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
foreach (var item in arr)
{
   sum += item;
}

SQL-Server: The backup set holds a backup of a database other than the existing

If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:

-- Queries the backup file for the file list in backup set, where Type denotes 
-- type of file. Can be L,D,F or S
-- info: https://docs.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO

You will get results similar to the following:

enter image description here

And then you can use those logical names in the queries:

    -- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
    RESTORE DATABASE DB 
    FROM DISK='C:\Temp\DB_backup.bak'
    WITH REPLACE,
      MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
      MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above

More info on RESTORE FILELISTONLY can be found from the SQL Server docs.

Determine function name from within that function (without using traceback)

This is pretty easy to accomplish with a decorator.

>>> from functools import wraps

>>> def named(func):
...     @wraps(func)
...     def _(*args, **kwargs):
...         return func(func.__name__, *args, **kwargs)
...     return _
... 

>>> @named
... def my_func(name, something_else):
...     return name, something_else
... 

>>> my_func('hello, world')
('my_func', 'hello, world')

How to make custom dialog with rounded corners in android

Create a xml in drawable ,say customd.xml.

then set it at background in your custom Dialog layout xml:

android:background="@drawable/customd"

finally in the java part for custom Dialog class you need to do this:

public class Customdialoque extends DialogFragment {

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    View view = inflater.inflate(R.layout.activity_customdialoque, container, false);

    return view;
}

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Excel to JSON javascript code?

NOTE: Not 100% Cross Browser

Check browser compatibility @ http://caniuse.com/#search=FileReader

as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..

The Fiddle: http://jsfiddle.net/d2atnbrt/3/

THE HTML CODE:

<input type="file" id="my_file_input" />
<div id='my_file_output'></div>

THE JS CODE:

var oFileIn;

$(function() {
    oFileIn = document.getElementById('my_file_input');
    if(oFileIn.addEventListener) {
        oFileIn.addEventListener('change', filePicked, false);
    }
});


function filePicked(oEvent) {
    // Get The File From The Input
    var oFile = oEvent.target.files[0];
    var sFilename = oFile.name;
    // Create A File Reader HTML5
    var reader = new FileReader();

    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result;
        var cfb = XLS.CFB.read(data, {type: 'binary'});
        var wb = XLS.parse_xlscfb(cfb);
        // Loop Over Each Sheet
        wb.SheetNames.forEach(function(sheetName) {
            // Obtain The Current Row As CSV
            var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);   
            var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);   

            $("#my_file_output").html(sCSV);
            console.log(oJS)
        });
    };

    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);
}

This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed

This is as basic as i could get it,

EDIT - Generating A Table

The Fiddle: http://jsfiddle.net/d2atnbrt/5/

This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..

One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least

Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls

This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

The tilde operator in Python

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

Access elements of parent window from iframe

Have the below js inside the iframe and use ajax to submit the form.

$(function(){

   $("form").submit(e){
        e.preventDefault();

       //Use ajax to submit the form
       $.ajax({
          url: this.action,
          data: $(this).serialize(),
          success: function(){
             window.parent.$("#target").load("urlOfThePageToLoad");
          });
       });

   });

});

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

How to get html to print return value of javascript function?

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

see column-constraint .

And insert a row without providing any value.

INSERT INTO "test" DEFAULT VALUES;

I ran into a merge conflict. How can I abort the merge?

git merge --abort

Abort the current conflict resolution process, and try to reconstruct the pre-merge state.

If there were uncommitted worktree changes present when the merge started, git merge --abort will in some cases be unable to reconstruct these changes. It is therefore recommended to always commit or stash your changes before running git merge.

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

http://www.git-scm.com/docs/git-merge

Catch paste input

$("#textboxid").on('input propertychange', function () {
    //perform operation
        });

It will work fine.

Error: Segmentation fault (core dumped)

In my case: I forgot to activate virtualenv

I installed "pip install example" in the wrong virtualenv

Why do we use arrays instead of other data structures?

Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.

Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.

In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.

  MyArray   [5]
     ^       ^
  Pointer  Offset

All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).

For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================

In an array, we know that each element is next to each other in memory. A C array (Called MyArray here) is simply a pointer to the first element:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^
MyArray

If we wanted to look up MyArray[4], internally it would be accessed like this:

   0     1     2     3     4 
=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
                           ^
MyArray + 4 ---------------/
(Pointer + Offset)

Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000] would take the same amount of time as getting MyArray[5].

An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node

========    ========    ========    ========    ========
| Data |    | Data |    | Data |    | Data |    | Data |
|      | -> |      | -> |      | -> |      | -> |      | 
|  P1  |    |  P2  |    |  P3  |    |  P4  |    |  P5  |        
========    ========    ========    ========    ========

P(X) stands for Pointer to next node.

Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.

If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.

This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.

Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.

You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.

Take our array again. This time, I want to find the array element that holds the value '5'.

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^     ^     ^     ^     ^   FOUND!

In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.

Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.

Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.

A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.

         ==========
         |  Root  |         
         ==========
        /          \ 
  =========       =========
  | Child |       | Child |
  =========       =========
                  /       \
            =========    =========
            | Child |    | Child |
            =========    =========

 Assume that each connector is really a Pointer

When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.

This means that the values in a binary tree could look like this:

         ==========
         |   100  |         
         ==========
        /          \ 
  =========       =========
  |  200  |       |   50  |
  =========       =========
                  /       \
            =========    =========
            |   75  |    |   25  |
            =========    =========

When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:

  • Is 75 less than 100? Look at Right Node
  • Is 75 greater than 50? Look at Left Node
  • There is the 75!

Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.

That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.

This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.

CSS way to horizontally align table

Try this:

<table width="200" style="margin-left:auto;margin-right:auto">

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

Swap x and y axis without manually swapping values

In Numbers, click on the chart. Then in the BOTTOM LEFT corner there is the the option to either 'Plot Rows as Series'or 'Plot Columns as series'

When adding a Javascript library, Chrome complains about a missing source map, why?

Newer files on JsDelivr get the sourcemap added automatically to the end of them. This is fine and doesn't throw any SourceMap-related notice in the console as long as you load the files from JsDelivr. The problem occurs only when you copy then load these files from your own server. In order to fix this for locally loaded files simply remove the last line in the JS file(s) downloaded from JsDelivr. It should look something like this:

//# sourceMappingURL=/sm/64bec5fd901c75766b1ade899155ce5e1c28413a4707f0120043b96f4a3d8f80.map

As you can see it's commented out but Chrome still parses it.

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

Resizing SVG in html?

I have found it best to add viewBox and preserveAspectRatio attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h:

<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>

How to convert list data into json in java

JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

List<String> ls =new  ArrayList<String>();

for(product cj:cities.getList()) {
    ls.add(cj);
    JSONObject formDetailsJson = new JSONObject();
    formDetailsJson.put("id", cj.id);
    formDetailsJson.put("name", cj.name);
    jsonArray.put(formDetailsJson);
}

responseDetailsJson.put("Cities", jsonArray);

return responseDetailsJson;

Finding all objects that have a given property inside a collection

Sounds a lot like something you would use LINQ for in .NET

While there's no "real" LINQ implementation for java yet, you might want to have a look at Quaere which could do what you describe easily enough.

How to get the path of src/test/resources directory in JUnit?

Use the following to inject Hibernate with Spring in your unit tests:

@Bean
public LocalSessionFactoryBean getLocalSessionFactoryBean() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    localSessionFactoryBean.setPackagesToScan("com.example.yourpackage.model");
    return localSessionFactoryBean;
}

If you don't have the hibernate.cfg.xml present in your src/test/resources folder it will automatically fall back to the one in your src/main/resources folder.

Get Unix timestamp with C++

#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
  unsigned long int sec= time(NULL);
  cout<<sec<<endl;
}

MySQL join with where clause

You need to put it in the join clause, not the where:

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON 
    user_category_subscriptions.category_id = categories.category_id
    and user_category_subscriptions.user_id =1

See, with an inner join, putting a clause in the join or the where is equivalent. However, with an outer join, they are vastly different.

As a join condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1 first, and takes the subset of user_category_subscriptions with a user_id of 1 to join to all of the rows in categories. This will give you all of the rows in categories, while only the categories that this particular user has subscribed to will have any information in the user_category_subscriptions columns. Of course, all other categories will be populated with null in the user_category_subscriptions columns.

Conversely, a where clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id doesn't equal 1. You're left with an inefficient way to get an inner join.

Hopefully this helps!

How to best display in Terminal a MySQL SELECT returning too many fields?

Terminate the query with \G in place of ;. For example:

SELECT * FROM sometable\G

This query displays the rows vertically, like this:

*************************** 1. row ***************************
                 Host: localhost
                   Db: mydatabase1
                 User: myuser1
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          ...
*************************** 2. row ***************************
                 Host: localhost
                   Db: mydatabase2
                 User: myuser2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          ...

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

This will achieve what you're asking about:

INSERT INTO table1 (ID, Name)
    VALUES (123, 'Timmy'), 
           (124, 'Jonny'), 
           (125, 'Sally');

For future developers, you can also insert from another table:

INSERT INTO table1 (ID, Name)
    SELECT 
         ID, 
         Name 
    FROM table2

Or even from multiple tables:

INSERT INTO table1 (column2, column3)
    SELECT 
         t2.column, 
         t3.column
    FROM table2 t2
         INNER JOIN table3 t3
         ON t2.ID = t3.ID

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

For me, I was getting latest from source control and this happened.

The applicationhost.config file's virtualDirectory path was different than in my machine.

I restored my own copy and it works. I am using IIS express.

enter image description here

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

Passing base64 encoded strings in URL

Introductory Note I'm inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).

The answer is NO, you cannot simply pass a base64 encoded parameter within a URL query string since plus signs are converted to a SPACE inside the $_GET global array. In other words, if you sent test.php?myVar=stringwith+sign to

//test.php
print $_GET['myVar'];

the result would be:
stringwith sign

The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes. For instance, urlencode("stringwith+sign") returns stringwith%2Bsign

When you process the action, PHP takes care of decoding the query string automatically when it populates the $_GET global. For example, if I sent test.php?myVar=stringwith%2Bsign to

//test.php
print $_GET['myVar'];

the result would is:
stringwith+sign

You do not want to urldecode() the returned $_GET string as +'s will be converted to spaces.
In other words if I sent the same test.php?myVar=stringwith%2Bsign to

//test.php
$string = urldecode($_GET['myVar']);
print $string;

the result is an unexpected:
stringwith sign

It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.

javascript - replace dash (hyphen) with a space

replace() returns an new string, and the original string is not modified. You need to do

str = str.replace(/-/g, ' ');

Convert alphabet letters to number in Python

You can use chr() and ord() to convert betweeen letters and int numbers.

Here is a simple example.

>>> chr(97)
'a'
>>> ord('a')
97

How to round a number to n decimal places in Java

Suppose you have

double d = 9232.129394d;

you can use BigDecimal

BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();

or without BigDecimal

d = Math.round(d*100)/100.0d;

with both solutions d == 9232.13

Numpy matrix to array

Or you could try to avoid some temps with

A = M.view(np.ndarray)
A.shape = -1

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I think you have put command like java -VERSION. This is in capital letters You need to put all command in lowercase letters

javac -version
java -version

All characters must be in lowercase letter

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

How to add to an NSDictionary

For reference, you can also utilize initWithDictionary to init the NSMutableDictionary with a literal one:

NSMutableDictionary buttons = [[NSMutableDictionary alloc] initWithDictionary: @{
    @"touch": @0,
    @"app": @0,
    @"back": @0,
    @"volup": @0,
    @"voldown": @0
}];

How to open a file / browse dialog using javascript?

Here's is a way of doing it without any Javascript and it's also compatible with any browser.


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

Also, if you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

Killing a process using Java

You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);

p.descendants().forEach(ph -> {
    ph.destroy();
});

p.destroy();

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Try writing the following batch file and executing it:

Echo one
cmd
Echo two
cmd
Echo three
cmd

Only the first two lines get executed. But if you type "exit" at the command prompt, the next two lines are processed. It's a shell loading another.

To be sure that this is not what is happening in your script, just type "exit" when the first command ends.

HTH!

What's a good, free serial port monitor for reverse-engineering?

Oops, can't comment yet (!) but re: Nick and logic analyser, beware: RS232 signal levels not typically Logic Analyser compatible unless you get/make a special serial probe. A 'proper' RS232/Serial port can use +/-12v swings (on all signals) and sometimes more. A laptop sometimes uses 0-5v swings (and often won't work with real serial interfaces) so could work with a vbasic 'ttl-level' LA interface.

Sleep Command in T-SQL?

WAITFOR DELAY 'HH:MM:SS'

I believe the maximum time this can wait for is 23 hours, 59 minutes and 59 seconds.

Here's a Scalar-valued function to show it's use; the below function will take an integer parameter of seconds, which it then translates into HH:MM:SS and executes it using the EXEC sp_executesql @sqlcode command to query. Below function is for demonstration only, i know it's not fit for purpose really as a scalar-valued function! :-)

    CREATE FUNCTION [dbo].[ufn_DelayFor_MaxTimeIs24Hours]
    (
    @sec int
    )
    RETURNS
    nvarchar(4)
    AS
    BEGIN


    declare @hours int = @sec / 60 / 60
    declare @mins int = (@sec / 60) - (@hours * 60)
    declare @secs int = (@sec - ((@hours * 60) * 60)) - (@mins * 60)


    IF @hours > 23 
    BEGIN
    select @hours = 23
    select @mins = 59
    select @secs = 59
    -- 'maximum wait time is 23 hours, 59 minutes and 59 seconds.'
    END


    declare @sql nvarchar(24) = 'WAITFOR DELAY '+char(39)+cast(@hours as nvarchar(2))+':'+CAST(@mins as nvarchar(2))+':'+CAST(@secs as nvarchar(2))+char(39)


    exec sp_executesql @sql

    return ''
    END

IF you wish to delay longer than 24 hours, I suggest you use a @Days parameter to go for a number of days and wrap the function executable inside a loop... e.g..

    Declare @Days int = 5
    Declare @CurrentDay int = 1

    WHILE @CurrentDay <= @Days
    BEGIN

    --24 hours, function will run for 23 hours, 59 minutes, 59 seconds per run.
    [ufn_DelayFor_MaxTimeIs24Hours] 86400

    SELECT @CurrentDay = @CurrentDay + 1
    END

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

Visual Studio Copy Project

Following Shane's answer above (which works great BTW)…

You might encounter a slew of yellow triangles in the reference list. Most of these can be eliminated by a Build->Clean Solution and Build->Rebuild Solution.

I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.

Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.

To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.

WCF ServiceHost access rights

Please open your Visual Studio as administrator:

enter image description here

Where is the Java SDK folder in my computer? Ubuntu 12.04

WAY-1 : Updated for the shortest and easy way

Below command will give you the path, But it will only work if java command is working in other words if java path is configured.

readlink -f $(which java) 

Read more at Where can I find the Java SDK in Linux?


WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.

You need to dig into symbolic links. Below is steps to get Java directory

Step 1:

$ whereis java
java: /usr/bin/java /etc/java /usr/share/java

That tells the command java resides in /usr/bin/java.

Dig again:

Step 2:

$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java.

Dig deeper using the same method above:

Step 3:

$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java

So, thats the actual location of java: /usr/local/jre.....

You could still dig deeper to find other symbolic links.


Reference : where is java's home dir?

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

I faced this issue and fixed by upgrade my php version in apache up to 5.6.x

Shrink a YouTube video to responsive width

I used the CSS in the accepted answer here for my responsive YouTube videos - worked great right up until YouTube updated their system around the start of August 2015. The videos on YouTube are the same dimensions but for whatever reason the CSS in the accepted answer now letterboxes all our videos. Black bands across top and bottom.

I've tickered around with the sizes and settled on getting rid of the top padding and changing the bottom padding to 56.45%. Seems to look good.

.videowrapper {
    position: relative;
    padding-bottom: 56.45%;
    height: 0;
}

JavaScript Chart.js - Custom data formatting to display on tooltip

For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
            }
        }
    }
}

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Angular 2 http post params and body

Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

Sort Dictionary by keys

If you want to iterate over both the keys and the values in a key sorted order, this form is quite succinct

let d = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

Swift 1,2:

for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
    println("\(k):\(v)")
}

Swift 3+:

for (k,v) in Array(d).sorted(by: {$0.0 < $1.0}) {
    println("\(k):\(v)")
}

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.

for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php

to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/

Styling Google Maps InfoWindow

Use the InfoBox plugin from the Google Maps Utility Library. It makes styling/managing map pop-ups much easier.

Note that you'll need to make sure it loads after the google maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap" async defer></script>
<script src="/js/infobox_packed.js" async defer></script>

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

Mark error in form using Bootstrap

For Bootstrap v4 use:
has-danger for form-group wrapper,
form-control-danger for input to show icon (will display ? at the end of input),
form-control-feedback to message wrapper

Example:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="form-group has-danger">_x000D_
  <input type="text" class="form-control form-control-danger">_x000D_
  <div class="form-control-feedback">Not valid :(</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

what exactly is device pixel ratio?

Device Pixel Ratio == CSS Pixel Ratio

In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.

A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:

formula

For example:

Apple iPhone 6s

  • Actual Resolution: 750 x 1334
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.

Some other examples:

Samsung Galaxy S4

  • Actual Resolution: 1080 x 1920
  • CSS Pixel Ratio: 3
  • Logical Resolution:

formula

iPhone 5s

  • Actual Resolution: 640 x 1136
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

Why does the Device Pixel Ratio exist?

The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.

A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.

So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.

Here is a tool that also tells you your current device's pixel density:

http://bjango.com/articles/min-device-pixel-ratio/

Is there a way to 'pretty' print MongoDB shell output to a file?

As answer by Neodan mongoexport is quite useful with -q option for query. It also convert ObjectId to standard format of JSON "$oid". E.g:

mongoexport -d yourdb -c yourcol --jsonArray --pretty -q '{"field": "filter value"}' -o output.json

Dynamically add script tag with src that may include document.write

There is the onload function, that could be called when the script has loaded successfully:

function addScript( src, callback ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  s.onload=callback;
  document.body.appendChild( s );
}