Programs & Examples On #Frm

FRM is a file extension for formatting used with MySQL. Contains the formatting information or structure data for a MySQL database; specifies the tables stored in the database and defines the fields and structure of each table.

angular2 manually firing click event on particular element

Angular4

Instead of

    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);

use

    this.fileInput.nativeElement.dispatchEvent(event);

because invokeElementMethod won't be part of the renderer anymore.

Angular2

Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent to fire the event:

import { Component, Renderer, ElementRef, ViewChild } from '@angular/core';
@Component({
  ...
  template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
  @ViewChild('fileInput') fileInput:ElementRef;

  constructor(private renderer:Renderer) {}

  showImageBrowseDlg() {
    // from http://stackoverflow.com/a/32010791/217408
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);
  }
}

Update

Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well

this.fileInput.nativeElement.click()

See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Close Bootstrap modal on form submit

Use that Code

 $('#button').submit(function(e) {
    e.preventDefault();
    // Coding
    $('#IDModal').modal('toggle'); //or  $('#IDModal').modal('hide');
    return false;
});

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

Database corruption with MariaDB : Table doesn't exist in engine

You may try to:

  • backup your database folder from C:\xampp\mysql\data (.frm & .ibd files only corresponding your table names)
  • reinstall xampp and recopy DB folder at C:\xampp\mysql\data
  • modify my.ini add

    [mysqld]
    innodb_file_per_table = on
    
  • then open phpmyadmin (or any other DB viewer as Navicat or MYSQL Workbench) and run

    ALTER TABLE tbl_name IMPORT TABLESPACE 
    

    for each table

  • Once you can open your tables make a full mysql dump

  • delete everything and make a clean install

I know, a lot of work to do that you don't need it.

Conversion failed when converting the nvarchar value ... to data type int

You are trying to concatenate a string and an integer.
You need to cast @ID as a string.
try:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

How do I add multiple conditions to "ng-disabled"?

You should be able to && the conditions:

ng-disabled="condition1 && condition2"

MySQL Daemon Failed to Start - centos 6

I just had this error. I could not connect remotely to my mysql server. I tried restarting mysql server with service mysqld restart (I used root). It stopped but did not start again. Turns out my memory was full. Cleared out a few GBs and it is working fine.

show validation error messages on submit in angularjs

// This worked for me.
<form  name="myForm" class="css-form" novalidate ng-submit="Save(myForm.$invalid)">
<input type="text" name="uName" ng-model="User.Name" required/>
<span ng-show="User.submitted && myForm.uName.$error.required">Name is required.</span>
<input ng-click="User.submitted=true" ng-disabled="User.submitted && tForm.$invalid" type="submit" value="Save" />
</form>
// in controller
$scope.Save(invalid)
{
if(invalid) return;
// save form
}

Why is pydot unable to find GraphViz's executables in Windows 8?

For windows 8.1 & python 2.7 , I fixed the problem by following below steps

1 . Download and install graphviz-2.38.msi https://graphviz.gitlab.io/_pages/Download/Download_windows.html

2 . Set the path variable

Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit add 'C:\Program Files (x86)\Graphviz2.38\bin'

  1. Restart your currently running application that requires the path

"Input string was not in a correct format."

You might be trying to access a control inside a control, maybe a GridView or DetailsView.

Try using something like this:

empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

Closing Twitter Bootstrap Modal From Angular Controller

We can achieve the same without using angular-ui. This can be done using angular directives.

First add the directive to the modal.

<div class="modal fade" my-modal ....>...</div>

Create a new angular directive:

app.directive('myModal', function() {
   return {
     restrict: 'A',
     link: function(scope, element, attr) {
       scope.dismiss = function() {
           element.modal('hide');
       };
     }
   } 
});

Now call the dismiss() method from your controller.

app.controller('MyCtrl', function($scope, $http) {
    // You can call dismiss() here
    $scope.dismiss();
});

I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.

The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.

How to submit an HTML form on loading the page?

You don't need Jquery here! The simplest solution here is (based on the answer from charles):

<html>
<body onload="document.frm1.submit()">
   <form action="http://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>
</html>

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

jQuery selector to get form by name

For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}

javascript if number greater than number

You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

Remove values from select list based on condition

Alternatively you can also accomplish this with getElementsByName

<select id="mySelect" name="val" size="1" >
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>                    
</select> 

So in matching on the option value of "C" we could remove Cars from the list.

var selectobject = document.getElementsByName('val')[0];
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == 'C' )
    selectobject.remove(i);
  }

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Chrome javascript debugger breakpoints don't do anything?

So, in addition to Adam Rackis' answer, if you have errors in your javascript file above the breakpoint, you won't reach it regardless if you flag it, or put in debugger;.

Here's an example:

if (nonExistentVar === "something") {
  console.log("this won't happen as the above errors out");
}
debugger;
console.log("this won't print either")

How can I send the "&" (ampersand) character via AJAX?

You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.

data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana') 

OR

var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos&param2="+encodeURIComponent(someValue)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

[HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Restore the mysql database from .frm files

Yes! It is possible

Long approach but you can get all the data's using just .frm files. Of course you need other files in the mysql/data directory.

My Problem

One day my harddisk crashed and got the booting blue screen error. I try connecting with multiple machine and it didn't work. Since it is a booting error i was concered about the files. and i tryed with the secondary harddisk and try to recover the folders and files. I also backed up the full xampp folder c:/xampp just in case, Because I had no back of the recent databases i got really worried how to retrieve the database. we have lot of clients project management and personal doc in the database.

None of the method listed on the stackoverflow comment works, at-least for me. It took me 2 full days googling for the answer to get the data's from the .frm files. Came across multiple approaches from many people but everything was frustration and getting some error or another when implementing. If most of them get it working (based on their comment) then what am i missing.

Because i was so desperate I even reinstall windows which result in loosing all my softwares and tried again. But still the same error

THANKS to Dustin Davis

i found the solution in his blog and i managed to get it working exactly the same way he did. Let me give the credit to this guy, Dustin Davis (https://dustindavis.me/restoring-mysql-innodb-files-on-windows/). You could jump from here to his blog and try his method, pretty clear and easy to follow.

But there are something i discovered when trying his approach which he hasn't explained in his blog and i will try my best to explain how i did and what you need to look for.

Follow this exactly

IMPORTANT: Make sure you to install the same version of XAMPP. You cannot copy paste from older XAMPP to a new version. This will result in __config or __tracking errors.

How to check your XAMPP version

  1. Go to your xampp folder (your backed up xampp).
  2. Open the readme_en.txt file. which is in the root directory of the xampp.
  3. You should see the version on top. ###### ApacheFriends XAMPP Version X.X.XX ######

Files require to restore

xampp(old folder)/mysql/data/

ibdata1
ib_logfile0
ib_logfile1
<databasename>/*.frm
<databasename>/*.ibd

Step 1

  1. After installed the same version of xampp.
  2. Do not start the apache or myql

Step 2

  • Go to the mysql/data folder and replace the ibdata1, ib_logfile0, and ib_logfile1
  • Now copy paste your database folder from your old xampp backup to the newly installed xampp folder c:/xampp/mysql/data/ that contain .frm and .ibd files, If you are not sure try with one database.

Step 3

  • Go to c:/xampp/mysql/bin and look for my.cn.
  • Open the my.cn file and look for #skip-innodb and under that look for the line that says innodb_log_file_size=5M change it to 170M. innodb_log_file_size=170M. This is your log file size and if you are not sure just set it to 170

Step 4

  • Now open the file mysql_start.bat (Windows Batch file) that is in the c:/xampp/ directory.
  • Add –innodb_force_recovery=6 after the ... --console

    ....
    
    mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
    –innodb_force_recovery=6
    if errorlevel 1 goto error
    goto finish
    

Step 5

  • Now Start your Apache and Mysql.
  • Go to your phpmyadmin and check for your database and its tables. if you do not get any errors you are on the right track.
  • Stop the Apache and Mysql and copy paste the rest of the databases.

How to set cursor to input box in Javascript?

Sometimes you do get focus but no cursor in a text field. In this case you would do this:

document.getElementById(frmObj.id).select();

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

How to "grep" for a filename instead of the contents of a file?

You can find the relative path of a file using tree, just pipe the output to grep to filter down

tree -f | grep filename

Here is a function you can put into your .bash_profile, .bashrc, .zshrc or other...

findfile(){ tree -f | grep $1; } # $1 = filename, -f is full path

What is the exact location of MySQL database tables in XAMPP folder?

Just in case you forgot or avoided to copy through PHPMYADMIN export feature..

Procedure: You can manually copy: Procedure For MAC OS, for latest versions of XAMPP

Location : Find the database folders here /Users/XXXXUSER/XAMPP/xamppfiles/var/mysql..

Solution: Copy the entire folder with database names into your new xampp in similar folder.

Hope it helps, happy coding.

Drawing in Java using Canvas

You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

Sorting by date & time in descending order?

SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY date ASC

"DESC" stands for descending but you need ascending order ("ASC").

C# windows application Event: CLR20r3 on application start

.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.

How to execute a MySQL command from a shell script?

mysql -h "hostname" -u usr_name -pPASSWD "db_name" < sql_script_file

(use full path for sql_script_file if needed)

If you want to redirect the out put to a file

mysql -h "hostname" -u usr_name -pPASSWD "db_name" < sql_script_file > out_file

How to use document.getElementByName and getElementByTag?

  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById



A great alternative is


In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

How do I disable TextBox using JavaScript?

Here was my solution:

Markup:

<div id="name" disabled="disabled">

Javascript:

document.getElementById("name").disabled = true;

This the best solution for my applications - hope this helps!

How to get Text BOLD in Alert or Confirm box?

The alert() dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.

You'd need to use a custom modal to achieve that.

How to return a value from a Form in C#?

I use MDI quite a lot, I like it much more (where it can be used) than multiple floating forms.

But to get the best from it you need to get to grips with your own events. It makes life so much easier for you.

A skeletal example.

Have your own interupt types,

//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
    IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
    CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT, 
   CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}

Then your own Args type

public class ControlArgs
{
    //MDI form source
    public InteruptSource source { get; set; }
    //Interrupt type
    public EVInterupts clockInt { get; set; }
    //in this case only a date is needed
    //but normally I include optional data (as if a C UNION type)
    //the form that responds to the event decides if
    //the data is for it.
    public DateTime date { get; set; }
    //CI_STOCKIN
    public StockClass inStock { get; set; }

}

Then use the delegate within your namespace, but outside of a class

namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
  public partial class Form1 : Form
{
  //your main form
}

Now either manually or using the GUI, have the MDIparent respond to the events of the child forms.

But with your owr Args, you can reduce this to a single function. and you can have provision to interupt the interupts, good for debugging, but can be usefull in other ways too.

Just have al of your mdiparent event codes point to the one function,

        calendar.Friday += new StoreHandler(MyEvents);
        calendar.Saturday += new StoreHandler(MyEvents);
        calendar.Sunday += new StoreHandler(MyEvents);
        calendar.PayDay += new StoreHandler(MyEvents);
        calendar.NewYear += new StoreHandler(MyEvents);

A simple switch mechanism is usually enough to pass events on to appropriate forms.

how to change onclick event with jquery?

Updating this post (2015) : unbind/bind should not be used anymore with jQuery 1.7+. Use instead the function off(). Example :

$('#id').off('click');
$('#id').click(function(){
    myNewFunction();
    //Other code etc.
});

Be sure that you call a non-parameter function in .click, otherwise it will be ignored.

MySQL: Can't create table (errno: 150)

Try:

CREATE TABLE `data` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(100) NOT NULL,
  `value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1`,
FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;  

You need to put a "," between CONSTRAINT and FOREIGN.

How to reset (clear) form through JavaScript?

Clear the form as follows

document.forms[0].reset();

You can simply clear the form elements within the group. by using this forms[0].

Checking the form field values before submitting that page

While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()" instead.

You may want to considering replacing this method with onsubmit="return checkform()" in the form tag instead, though both will work for clicking the button.

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

I got this completely worthless and uninformative error when I tried to:

ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

My problem was in my comments table, user_id was defined as:

`user_id` int(10) unsigned NOT NULL

So... in my case, the problem was with the conflict between NOT NULL, and ON DELETE SET NULL.

Can I use jQuery to check whether at least one checkbox is checked?

$("#show").click(function() {
    var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
        if(count_checked == 0) 
        {
            alert("Please select any record to delete.");
            return false;
        }
        if(count_checked == 1) {
            alert("Record Selected:"+count_checked);

        } else {
            alert("Record Selected:"+count_checked);
          }
});

jQuery - checkbox enable/disable

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#InventoryMasterError').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').attr('disabled', 'disabled');_x000D_
      });_x000D_
    } else {_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').removeAttr('disabled', 'disabled');_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
_x000D_
});_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#selecctall').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').attr('disabled', 'disabled');_x000D_
      });_x000D_
_x000D_
    } else {_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').removeAttr('disabled', 'disabled');_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="selecctall" name="selecctall" value="All" />_x000D_
<input type="checkbox" name="data[InventoryMaster][error]" label="" value="error" id="InventoryMasterError" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="1" id="InventoryMasterId" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="2" id="InventoryMasterId" />
_x000D_
_x000D_
_x000D_

How to uncheck a radio button?

Rewrite of Igor's code as plugin.

Use:

$('input[type=radio]').uncheckableRadio();

Plugin:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

MySQL server has gone away - in exactly 60 seconds

Please see this link http://bugs.php.net/bug.php?id=45150 seems like they moved to native MYSQL support in PHP5.3 and it has some trouble working with IPV6. Try using "127.0.0.1" instead of "localhost"

how to set default main class in java?

If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main() method you want to use to start execution.

In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF

There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.

The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.

As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.

C# Get a control's position on a form

You could walk up through the parents, noting their position within their parent, until you arrive at the Form.

Edit: Something like (untested):

public Point GetPositionInForm(Control ctrl)
{
   Point p = ctrl.Location;
   Control parent = ctrl.Parent;
   while (! (parent is Form))
   {
      p.Offset(parent.Location.X, parent.Location.Y);
      parent = parent.Parent;
   }
   return p;
}

How to recover MySQL database from .myd, .myi, .frm files

I think .myi you can repair from inside mysql.

If you see these type of error messages from MySQL: Database failed to execute query (query) 1016: Can't open file: 'sometable.MYI'. (errno: 145) Error Msg: 1034: Incorrect key file for table: 'sometable'. Try to repair it thenb you probably have a crashed or corrupt table.

You can check and repair the table from a mysql prompt like this:

check table sometable;
+------------------+-------+----------+----------------------------+
| Table | Op | Msg_type | Msg_text | 
+------------------+-------+----------+----------------------------+ 
| yourdb.sometable | check | warning | Table is marked as crashed | 
| yourdb.sometable | check | status | OK | 
+------------------+-------+----------+----------------------------+ 

repair table sometable;
+------------------+--------+----------+----------+ 
| Table | Op | Msg_type | Msg_text | 
+------------------+--------+----------+----------+ 
| yourdb.sometable | repair | status | OK | 
+------------------+--------+----------+----------+

and now your table should be fine:

check table sometable;
+------------------+-------+----------+----------+ 
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------+ 
| yourdb.sometable | check | status | OK |
+------------------+-------+----------+----------+

"Submit is not a function" error in JavaScript

What I used is

var enviar = document.getElementById("enviar");
enviar.type = "submit"; 

Just because everything else didn´t work.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Your website folder needs network service security. Especially the web.config. It uses this account to access your registry for the certificates. This will stop the need to add a hack to your code.

Resize iframe height according to content height in it

Below is my onload event handler.

I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

Restoring MySQL database from physical files

A MySQL MyISAM table is the combination of three files:

  • The FRM file is the table definition.
  • The MYD file is where the actual data is stored.
  • The MYI file is where the indexes created on the table are stored.

You should be able to restore by copying them in your database folder (In linux, the default location is /var/lib/mysql/)

You should do it while the server is not running.

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Looping over elements in jQuery

for me all these didn't work. What worked for me was something really simple:

$("#formID input[type=text]").each(function() {
alert($(this).val());
});

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

Is there a C# String.Format() equivalent in JavaScript?

Try sprintf() for javascript.

Or

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

Both answers pulled from JavaScript equivalent to printf/string.format

Is there any way I can define a variable in LaTeX?

I think you probably want to use a token list for this purpose: to set up the token list \newtoks\packagename to assign the name: \packagename={New Name for the package} to put the name into your output: \the\packagename.

AttributeError("'str' object has no attribute 'read'")

AttributeError("'str' object has no attribute 'read'",)

This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).

The error occurred here:

json.load (jsonofabitch)['data']['children']

Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonofabitch, which currently names a string (which you created by calling .read on the response).

Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.

You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .

Amazon Interview Question: Design an OO parking lot

Here is a quick start to get the gears turning...

ParkingLot is a class.

ParkingSpace is a class.

ParkingSpace has an Entrance.

Entrance has a location or more specifically, distance from Entrance.

ParkingLotSign is a class.

ParkingLot has a ParkingLotSign.

ParkingLot has a finite number of ParkingSpaces.

HandicappedParkingSpace is a subclass of ParkingSpace.

RegularParkingSpace is a subclass of ParkingSpace.

CompactParkingSpace is a subclass of ParkingSpace.

ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.

ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()

Parker is a class.

Parker can Park().

Parker can Unpark().

Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.

Parker has a ParkingSpace.

Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().

Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().

HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)

In this solution, it is possible that Parker should be renamed to be Car.

What exactly is Apache Camel?

Assume you create an ecommerce company like Amazon, and you want to only focus on strategy/choice of products to sell. unlike amazon delivery fleet, instead of yourself handling moving of goods from sellers to warehouse, making changes to it in warehouse like packaging and sending it out to other city and customers. You hire a company that does all this and just give them info of all your warehouse locations, vehicle types, delivery locations and a list of when to do what. Then they handle that by themselves, that would be Apache Camel. They take care of moving things from one end to other, once you handover stuff to them, so that you are free to focus on other things.

Auto increment in phpmyadmin

You cannot set a maximum value (other than choosing a datatype which cannot hold large numbers, but there are none that have the limit you're asking for). You can check that with LAST_INSERT_ID() after inserting to get the id of the newly created member, and if it is too big handle it in your application code (e.g., delete and reject the member).

Why do you want an upper limit?

How do I test if a string is empty in Objective-C?

You have 2 methods to check whether the string is empty or not:

Let's suppose your string name is NSString *strIsEmpty.

Method 1:

if(strIsEmpty.length==0)
{
    //String is empty
}

else
{
    //String is not empty
}

Method 2:

if([strIsEmpty isEqualToString:@""])
{
    //String is empty
}

else
{
    //String is not empty
}

Choose any of the above method and get to know whether string is empty or not.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

Select the top N values by group

This seems more straightforward using data.table as it performs the sort while setting the key.

So, if I were to get the top 3 records in sort (ascending order), then,

require(data.table)
d <- data.table(mtcars, key="cyl")
d[, head(.SD, 3), by=cyl]

does it.

And if you want the descending order

d[, tail(.SD, 3), by=cyl] # Thanks @MatthewDowle

Edit: To sort out ties using mpg column:

d <- data.table(mtcars, key="cyl")
d.out <- d[, .SD[mpg %in% head(sort(unique(mpg)), 3)], by=cyl]

#     cyl  mpg  disp  hp drat    wt  qsec vs am gear carb rank
#  1:   4 22.8 108.0  93 3.85 2.320 18.61  1  1    4    1   11
#  2:   4 22.8 140.8  95 3.92 3.150 22.90  1  0    4    2    1
#  3:   4 21.5 120.1  97 3.70 2.465 20.01  1  0    3    1    8
#  4:   4 21.4 121.0 109 4.11 2.780 18.60  1  1    4    2    6
#  5:   6 18.1 225.0 105 2.76 3.460 20.22  1  0    3    1    7
#  6:   6 19.2 167.6 123 3.92 3.440 18.30  1  0    4    4    1
#  7:   6 17.8 167.6 123 3.92 3.440 18.90  1  0    4    4    2
#  8:   8 14.3 360.0 245 3.21 3.570 15.84  0  0    3    4    7
#  9:   8 10.4 472.0 205 2.93 5.250 17.98  0  0    3    4   14
# 10:   8 10.4 460.0 215 3.00 5.424 17.82  0  0    3    4    5
# 11:   8 13.3 350.0 245 3.73 3.840 15.41  0  0    3    4    3

# and for last N elements, of course it is straightforward
d.out <- d[, .SD[mpg %in% tail(sort(unique(mpg)), 3)], by=cyl]

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

How to cat <<EOF >> a file containing code?

You only need a minimal change; single-quote the here-document delimiter after <<.

cat <<'EOF' >> brightup.sh

or equivalently backslash-escape it:

cat <<\EOF >>brightup.sh

Without quoting, the here document will undergo variable substitution, backticks will be evaluated, etc, like you discovered.

If you need to expand some, but not all, values, you need to individually escape the ones you want to prevent.

cat <<EOF >>brightup.sh
#!/bin/sh
# Created on $(date # : <<-- this will be evaluated before cat;)
echo "\$HOME will not be evaluated because it is backslash-escaped"
EOF

will produce

#!/bin/sh
# Created on Fri Feb 16 11:00:18 UTC 2018
echo "$HOME will not be evaluated because it is backslash-escaped"

As suggested by @fedorqui, here is the relevant section from man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

clearing select using jquery

Here is a small jQuery plugin that (among other things) can empty an dropdown list.

Just write:

$('your-select-element').selectUtils('setEmpty');

React.js: Wrapping one component into another

Using children

const Wrapper = ({children}) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
  <Wrapper>
    <App name={name}/>
  </Wrapper>
);

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>
  </div>
);

const appElement = (
  <AppLayout 
    header={<div>header</div>}
    footer={<div>footer</div>}
  >
    <div>body</div>
  </AppLayout>
);

render(appElement,node);

This is simple and fine for many usecases, and I'd recommend this for most consumer apps.


render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times
      </div>
    )}
  </State>
); 

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
  {{
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,
  }}
</Promise>

Note you don't necessarily need to use children, it is a matter of taste/API.

<Promise 
  promise={somePromise}
  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}
/>

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.


Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
        <div>
          <div>header</div>
          <div><WrappedComponent {...this.props}/></div>
          <div>footer</div>
        </div>
      );
    }  
  }
  return Wrapper;
}

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Conclusion

Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

What is the correct XPath for choosing attributes that contain "foo"?

Have you tried something like:

//a[contains(@prop, "Foo")]

I've never used the contains function before but suspect that it should work as advertised...

Where can I find the assembly System.Web.Extensions dll?

The assembly was introduced with .NET 3.5 and is in the GAC.

Simply add a .NET reference to your project.

Project -> Right Click References -> Select .NET tab -> System.Web.Extensions

If it is not there, you need to install .NET 3.5 or 4.0.

Regular expression that matches valid IPv6 addresses

If you use Perl try Net::IPv6Addr

use Net::IPv6Addr;

if( defined Net::IPv6Addr::is_ipv6($ip_address) ){
  print "Looks like an ipv6 address\n";
}

NetAddr::IP

use NetAddr::IP;

my $obj = NetAddr::IP->new6($ip_address);

Validate::IP

use Validate::IP qw'is_ipv6';

if( is_ipv6($ip_address) ){
  print "Looks like an ipv6 address\n";
}

Get exception description and stack trace which caused an exception, all as a string

For those using Python-3

Using traceback module and exception.__traceback__ one can extract the stack-trace as follows:

  • grab the current stack-trace using traceback.extract_stack()
  • remove the last three elements (as those are entries in the stack that got me to my debug function)
  • append the __traceback__ from the exception object using traceback.extract_tb()
  • format the whole thing using traceback.format_list()
import traceback
def exception_to_string(excp):
   stack = traceback.extract_stack()[:-3] + traceback.extract_tb(excp.__traceback__)  # add limit=?? 
   pretty = traceback.format_list(stack)
   return ''.join(pretty) + '\n  {} {}'.format(excp.__class__,excp)

A simple demonstration:

def foo():
    try:
        something_invalid()
    except Exception as e:
        print(exception_to_string(e))

def bar():
    return foo()

We get the following output when we call bar():

  File "./test.py", line 57, in <module>
    bar()
  File "./test.py", line 55, in bar
    return foo()
  File "./test.py", line 50, in foo
    something_invalid()

  <class 'NameError'> name 'something_invalid' is not defined

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

List of strings to one string

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I just encountered this and my problem was caused by having two entities both with the System.ComponentModel.DataAnnotations.Schema.TableAttribute referring to the same table.

for example:

[Table("foo")]
public class foo
{
    // some stuff here
}

[Table("foo")]
public class fooExtended
{
    // more stuff here
}

changing the second one from foo to foo_extended fixed this for me and I'm now using Table Per Type (TPT)

Screen width in React Native

Simply declare this code to get device width

let deviceWidth = Dimensions.get('window').width

Maybe it's obviously but, Dimensions is an react-native import

import { Dimensions } from 'react-native'

Dimensions will not work without that

Find stored procedure by name

Assuming you're in the Object Explorer Details (F7) showing the list of Stored Procedures, click the Filters button and enter the name (or partial name).

alt text

Is it possible to use if...else... statement in React render function?

There actually is a way to do exactly what OP is asking. Just render and call an anonymous function like so:

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}

CSS3 Transition - Fade out effect

Here is another way to do the same.

fadeIn effect

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

fadeOut effect

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}

UPDATE 1: I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.

UPDATE 2: (Added details requested by @big-money)

When showing the element (by switching to the visible class), we want the visibility:visible to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.

I know I am too late to answer but posting this answer to save others time. Hope it helps you!!

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

Use this snippet for get all profile info

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();

            // Facebook Email address
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {
                            Log.v("LoginActivity Response ", response.toString());

                            try {
                                Name = object.getString("name");

                                FEmail = object.getString("email");
                                Log.v("Email = ", " " + FEmail);
                                Toast.makeText(getApplicationContext(), "Name " + Name, Toast.LENGTH_LONG).show();


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            LoginManager.getInstance().logOut();

        }

        @Override
        public void onError(FacebookException e) {

        }
    };

Add a new item to a dictionary in Python

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

>>> class Dict(dict):
...     def __add__(self, other):
...         copy = self.copy()
...         copy.update(other)
...         return copy
...     def __radd__(self, other):
...         copy = other.copy()
...         copy.update(self)
...         return copy
... 
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}

Note that this is more overhead then using dict[key] = value or dict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.

"SMTP Error: Could not authenticate" in PHPMailer

If you still face error in sending email, with the same error message. Try this:

$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';

just Before the line:

$send = $mail->Send();

or in other sense, before calling the Send() Function.

Tested and Working.

Change onClick attribute with javascript

The line onclick = writeLED(1,1) means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:

    var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
    document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;

Difference between document.addEventListener and window.addEventListener?

The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.

For example, there is a "resize" event on the window object that is not on the document object.

For example, the "DOMContentLoaded" event is only on the document object.

So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.

Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference


If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).

Error 405 (Method Not Allowed) Laravel 5

This might help someone so I'll put my inputs here as well.

I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148

After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.

I whitelisted those rules and voila, the 405 error was gone.

Hope this helps someone.

setting request headers in selenium

Had the same issue today, except that I needed to set different referer per test. I ended up using a middleware and a class to pass headers to it. Thought I'd share (or maybe there's a cleaner solution?):

lib/request_headers.rb:

class CustomHeadersHelper
  cattr_accessor :headers
end

class RequestHeaders
  def initialize(app, helper = nil)
    @app, @helper = app, helper
  end

  def call(env)
    if @helper
      headers = @helper.headers

      if headers.is_a?(Hash)
        headers.each do |k,v|
          env["HTTP_#{k.upcase.gsub("-", "_")}"] = v
        end
      end
    end

    @app.call(env)
  end
end

config/initializers/middleware.rb

require 'request_headers'

if %w(test cucumber).include?(Rails.env)
  Rails.application.config.middleware.insert_before Rack::Lock, "RequestHeaders", CustomHeadersHelper
end

spec/support/capybara_headers.rb

require 'request_headers'

module CapybaraHeaderHelpers
  shared_context "navigating within the site" do
    before(:each) { add_headers("Referer" => Capybara.app_host + "/") }
  end

  def add_headers(custom_headers)
    if Capybara.current_driver == :rack_test
      custom_headers.each do |name, value|
        page.driver.browser.header(name, value)
      end
    else
      CustomHeadersHelper.headers = custom_headers
    end
  end
end

spec/spec_helper.rb

...
config.include CapybaraHeaderHelpers

Then I can include the shared context wherever I need, or pass different headers in another before block. I haven't tested it with anything other than Selenium and RackTest, but it should be transparent, as header injection is done before the request actually hits the application.

OpenCV error: the function is not implemented

Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .

Java : Convert formatted xml file to one line string

The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.

However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.

The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.

String regex, updatedXml;

// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );

// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );

// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );

NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.

This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

How about negative margins?

textarea {
    border:1px solid #999999;
    width:100%;
    margin:5px -4px; /* 4px = border+padding on one side */
    padding:3px;
}

Location of hibernate.cfg.xml in project?

Give the path relative to your project.

Create a folder called resources in your src and put your config file there.

   configuration.configure("/resources/hibernate.cfg.xml");

And If you check your code

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();

In two lines you are creating two configuration objects.

That should work(haven't tested) if you write,

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return  configuration.buildSessionFactory();

But It fails after you deploy on the server,Since you are using system path than project relative path.

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

mysql -> insert into tbl (select from another table) and some default values

If you want to insert all the columns then

insert into def select * from abc;

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc; 

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just do it in the Base, that way any child can be Serialized, less code cleaner code.

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.

How do I size a UITextView to its content?

Another method is the find the size a particular string will take up using the NSString method:

-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

This returns the size of the rectangle that fits the given string with the given font. Pass in a size with the desired width and a maximum height, and then you can look at the height returned to fit the text. There is a version that lets you specify line break mode also.

You can then use the returned size to change the size of your view to fit.

Java Enum Methods - return opposite direction enum

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

How to implement LIMIT with SQL Server?

Starting with SQL SERVER 2012, you can use the OFFSET FETCH Clause:

USE AdventureWorks;
GO
SELECT SalesOrderID, OrderDate
FROM Sales.SalesOrderHeader 
ORDER BY SalesOrderID
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY;
GO

http://msdn.microsoft.com/en-us/library/ms188385(v=sql.110).aspx

This may not work correctly when the order by is not unique.

If the query is modified to ORDER BY OrderDate, the result set returned is not as expected.

How do I download a file using VBA (without Internet Explorer)

I was struggling for hours on this until I figured out it can be done in one line of powershell:

invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials

I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.

Simple.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

How to get the version of ionic framework?

At some point in time the object changed from ionic to an uppercase Ionic.

As of July 2017 you need to put Ionic.version into your console to get the version number.

How to Calculate Jump Target Address and Branch Target Address?

For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.

  • chris

Redirecting to a certain route based on condition

In your app.js file:

.run(["$rootScope", "$state", function($rootScope, $state) {

      $rootScope.$on('$locationChangeStart', function(event, next, current) {
        if (!$rootScope.loggedUser == null) {
          $state.go('home');
        }    
      });
}])

Linq select to new object

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

ASP.NET MVC DropDownListFor with model of type List<string>

I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:

https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:

yourRecord.FieldName = Request.Form["FieldNameInModel"];

As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.

No, I did not dig down to see how th4e magic works under the covers. I just know it works...

I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

How to compile C++ under Ubuntu Linux?

Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.

g++ source.cpp -o source

If you omit the -o parameter, the resultant executable will be named a.out. In any case, executable permissions have already been set, so no need to chmod anything.

Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.

SQL 'like' vs '=' performance

See https://web.archive.org/web/20150209022016/http://myitforum.com/cs2/blogs/jnelson/archive/2007/11/16/108354.aspx

Quote from there:

the rules for index usage with LIKE are loosely like this:

  • If your filter criteria uses equals = and the field is indexed, then most likely it will use an INDEX/CLUSTERED INDEX SEEK

  • If your filter criteria uses LIKE, with no wildcards (like if you had a parameter in a web report that COULD have a % but you instead use the full string), it is about as likely as #1 to use the index. The increased cost is almost nothing.

  • If your filter criteria uses LIKE, but with a wildcard at the beginning (as in Name0 LIKE '%UTER') it's much less likely to use the index, but it still may at least perform an INDEX SCAN on a full or partial range of the index.

  • HOWEVER, if your filter criteria uses LIKE, but starts with a STRING FIRST and has wildcards somewhere AFTER that (as in Name0 LIKE 'COMP%ER'), then SQL may just use an INDEX SEEK to quickly find rows that have the same first starting characters, and then look through those rows for an exact match.

(Also keep in mind, the SQL engine still might not use an index the way you're expecting, depending on what else is going on in your query and what tables you're joining to. The SQL engine reserves the right to rewrite your query a little to get the data in a way that it thinks is most efficient and that may include an INDEX SCAN instead of an INDEX SEEK)

remove script tag from HTML content

I would use BeautifulSoup if it's available. Makes this sort of thing very easy.

Don't try to do it with regexps. That way lies madness.

Change the background color in a twitter bootstrap modal?

I used couple of hours trying to figure how to remove background from launched modal, so far tried

.modal-backdrop {    background: none; }

Didn't work even I have tried to work with javascript like

 <script type="text/javascript">   
 $('#modal-id').on('shown.bs.modal',  function () {
       $(".modal-backdrop.in").hide();     })
</script>

Also didn't work either. I just added

data-backdrop="false"

to

<div class="modal fade" id="myModal" data-backdrop="false">......</div>

And Applying css CLASS

.modal {     background-color: transparent !important;  }

Now its working like a charm This worked with Bootstrap 3

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

jQuery text() and newlines

Alternatively, try using .html and then wrap with <pre> tags:

$(someElem).html('this\n has\n newlines').wrap('<pre />');

Center text output from Graphics.DrawString()

To draw a centered text:

TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor, 
  TextFormatFlags.HorizontalCenter | 
  TextFormatFlags.VerticalCenter |
  TextFormatFlags.GlyphOverhangPadding);

Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits.

Font FindBestFitFont(Graphics g, String text, Font font, 
  Size proposedSize, TextFormatFlags flags)
{ 
  // Compute actual size, shrink if needed
  while (true)
  {
    Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);

    // It fits, back out
    if ( size.Height <= proposedSize.Height && 
         size.Width <= proposedSize.Width) { return font; }

    // Try a smaller font (90% of old size)
    Font oldFont = font;
    font = new Font(font.FontFamily, (float)(font.Size * .9)); 
    oldFont.Dispose();
  }
}

You'd use this as:

Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)

Validating URL in Java

For the benefit of the community, since this thread is top on Google when searching for
"url validator java"


Catching exceptions is expensive, and should be avoided when possible. If you just want to verify your String is a valid URL, you can use the UrlValidator class from the Apache Commons Validator project.

For example:

String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("URL is valid");
} else {
   System.out.println("URL is invalid");
}

How to change default Anaconda python environment

I got this when installing a library using anaconda. My version went from Python 3.* to 2.7 and a lot of my stuff stopped working. The best solution I found was to first see the most recent version available:

conda search python

Then update to the version you want:

conda install python=3.*.*

Source: http://chris35wills.github.io/conda_python_version/

Other helpful commands:

conda info
python --version

Why should we include ttf, eot, woff, svg,... in a font-face

Answer in 2019:

Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format

(svg and eot are dead formats, ttf and otf are full system fonts, and should not be used for web purposes)

Original answer from 2012:

In short, font-face is very old, but only recently has been supported by more than IE.

  • eot is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.

  • ttf and otf are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.

  • Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.

  • Then, woff gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.

  • 2019 edit A few years later, woff2 gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.

If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)

@font-face {
  font-family: 'MyWebFont';
  src:  url('myfont.woff2') format('woff2'),
        url('myfont.woff') format('woff');
}

Support for woff can be checked at http://caniuse.com/woff
Support for woff2 can be checked at http://caniuse.com/woff2

Make a div fill the height of the remaining screen space

I had the same problem but I could not make work the solution with flexboxes above. So I created my own template, that includes:

  • a header with a fixed size element
  • a footer
  • a side bar with a scrollbar that occupies the remaining height
  • content

I used flexboxes but in a more simple way, using only properties display: flex and flex-direction: row|column:

I do use angular and I want my component sizes to be 100% of their parent element.

The key is to set the size (in percents) for all parents inorder to limit their size. In the following example myapp height has 100% of the viewport.

The main component has 90% of the viewport, because header and footer have 5%.

I posted my template here: https://jsfiddle.net/abreneliere/mrjh6y2e/3

       body{
        margin: 0;
        color: white;
        height: 100%;
    }
    div#myapp
    {
        display: flex;
        flex-direction: column;
        background-color: red; /* <-- painful color for your eyes ! */
        height: 100%; /* <-- if you remove this line, myapp has no limited height */
    }
    div#main /* parent div for sidebar and content */
    {
        display: flex;
        width: 100%;
        height: 90%; 
    }
    div#header {
        background-color: #333;
        height: 5%;
    }
    div#footer {
        background-color: #222;
        height: 5%;
    }
    div#sidebar {
        background-color: #666;
        width: 20%;
        overflow-y: auto;
     }
    div#content {
        background-color: #888;
        width: 80%;
        overflow-y: auto;
    }
    div.fized_size_element {
        background-color: #AAA;
        display: block;
        width: 100px;
        height: 50px;
        margin: 5px;
    }

Html:

<body>
<div id="myapp">
    <div id="header">
        HEADER
        <div class="fized_size_element"></div>

    </div>
    <div id="main">
        <div id="sidebar">
            SIDEBAR
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
        </div>
        <div id="content">
            CONTENT
        </div>
    </div>
    <div id="footer">
        FOOTER
    </div>
</div>
</body>

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

   a  b
 1  2  4
 2  3  3
 3  4  2
 4  5  1

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

Disable cross domain web security in Firefox

While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.

For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.

phantomjs.exe --web-security=no script.js

See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes

How do I get Flask to run on port 80?

set the port with app.run(port=80,debug=True) you should set debug to true when on dev

Lotus Notes email as an attachment to another email

answer from Alexey creates MS Outlook eml files, so if you don't have Outlook e-mail client doesn't help. Answer from Chris is not possible because there is no save mail option (at least in version 8.5) in LN. So one of the possible solutions would be to hold control, select all mails you want to attach, right click on the selected mails, from the menu select Forward and it will open the new message with all selected mails in the body of the new message.

What's your most controversial programming opinion?

UML diagrams are highly overrated

Of course there are useful diagrams e.g. class diagram for the Composite Pattern, but many UML diagrams have absolutely no value.

Combine or merge JSON on node.js without jQuery

You can also use this lightweight npm package called absorb

It is 27 lines of code, 1kb and uses recursion to perform deep object merges.

var absorb = require('absorb');
var obj1, obj2;

obj1 = { foo: 123, bar: 456 };
obj2 = { bar: 123, key: 'value' }

absorb(obj1, obj2);

console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }

You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

How to change lowercase chars to uppercase using the 'keyup' event?

Plain ol' javascript:

var input = document.getElementById('inputID');

input.onkeyup = function(){
    this.value = this.value.toUpperCase();
}

Javascript with jQuery:

$('#inputID').keyup(function(){
    this.value = this.value.toUpperCase();
});

How to check undefined in Typescript

Adding this late answer to check for object.propertie that can help in some cases:

Using a juggling-check, you can test both null and undefined in one hit:

if (object.property == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (object.property === null) {

Typescript does NOT have a function to check if a variable is defined.

Update October 2020

You can now also use the nullish coallesing operator introduced in Typescript.

let neverNullOrUndefined = someValue ?? anotherValue;

Here, anotherValue will only be returned if someValue is null or undefined.

How do I POST urlencoded form data with $http without jQuery?

I think you need to do is to transform your data from object not to JSON string, but to url params.

From Ben Nadel's blog.

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Example from here.

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).then(function () {});

UPDATE

To use new services added with AngularJS V1.4, see

How to master AngularJS?

Please keep an eye on the mailing list for problems/solutions discussed by community members. https://groups.google.com/forum/?fromgroups#!forum/angular . It's been really useful to me.

Find p-value (significance) in scikit-learn LinearRegression

This is kind of overkill but let's give it a go. First lets use statsmodel to find out what the p-values should be

import pandas as pd
import numpy as np
from sklearn import datasets, linear_model
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
from scipy import stats

diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
est2 = est.fit()
print(est2.summary())

and we get

                         OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.518
Model:                            OLS   Adj. R-squared:                  0.507
Method:                 Least Squares   F-statistic:                     46.27
Date:                Wed, 08 Mar 2017   Prob (F-statistic):           3.83e-62
Time:                        10:08:24   Log-Likelihood:                -2386.0
No. Observations:                 442   AIC:                             4794.
Df Residuals:                     431   BIC:                             4839.
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const        152.1335      2.576     59.061      0.000     147.071     157.196
x1           -10.0122     59.749     -0.168      0.867    -127.448     107.424
x2          -239.8191     61.222     -3.917      0.000    -360.151    -119.488
x3           519.8398     66.534      7.813      0.000     389.069     650.610
x4           324.3904     65.422      4.958      0.000     195.805     452.976
x5          -792.1842    416.684     -1.901      0.058   -1611.169      26.801
x6           476.7458    339.035      1.406      0.160    -189.621    1143.113
x7           101.0446    212.533      0.475      0.635    -316.685     518.774
x8           177.0642    161.476      1.097      0.273    -140.313     494.442
x9           751.2793    171.902      4.370      0.000     413.409    1089.150
x10           67.6254     65.984      1.025      0.306     -62.065     197.316
==============================================================================
Omnibus:                        1.506   Durbin-Watson:                   2.029
Prob(Omnibus):                  0.471   Jarque-Bera (JB):                1.404
Skew:                           0.017   Prob(JB):                        0.496
Kurtosis:                       2.726   Cond. No.                         227.
==============================================================================

Ok, let's reproduce this. It is kind of overkill as we are almost reproducing a linear regression analysis using Matrix Algebra. But what the heck.

lm = LinearRegression()
lm.fit(X,y)
params = np.append(lm.intercept_,lm.coef_)
predictions = lm.predict(X)

newX = pd.DataFrame({"Constant":np.ones(len(X))}).join(pd.DataFrame(X))
MSE = (sum((y-predictions)**2))/(len(newX)-len(newX.columns))

# Note if you don't want to use a DataFrame replace the two lines above with
# newX = np.append(np.ones((len(X),1)), X, axis=1)
# MSE = (sum((y-predictions)**2))/(len(newX)-len(newX[0]))

var_b = MSE*(np.linalg.inv(np.dot(newX.T,newX)).diagonal())
sd_b = np.sqrt(var_b)
ts_b = params/ sd_b

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX[0])))) for i in ts_b]

sd_b = np.round(sd_b,3)
ts_b = np.round(ts_b,3)
p_values = np.round(p_values,3)
params = np.round(params,4)

myDF3 = pd.DataFrame()
myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilities"] = [params,sd_b,ts_b,p_values]
print(myDF3)

And this gives us.

    Coefficients  Standard Errors  t values  Probabilities
0       152.1335            2.576    59.061         0.000
1       -10.0122           59.749    -0.168         0.867
2      -239.8191           61.222    -3.917         0.000
3       519.8398           66.534     7.813         0.000
4       324.3904           65.422     4.958         0.000
5      -792.1842          416.684    -1.901         0.058
6       476.7458          339.035     1.406         0.160
7       101.0446          212.533     0.475         0.635
8       177.0642          161.476     1.097         0.273
9       751.2793          171.902     4.370         0.000
10       67.6254           65.984     1.025         0.306

So we can reproduce the values from statsmodel.

How can I get the image url in a Wordpress theme?

You need to use

 <?php bloginfo('template_directory'); ?>

It returns the directory of the current WordPress theme.

Now for example, if your theme has some image named example.jpg inside some folder name subfolder folder in the images folder.

 themes
   |-> your theme
          |-> images
                |->subfolder
                      |-> examples.jpg

You access it like this

 <img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">

What happened to console.log in IE8?

I'm using Walter's approach from above (see: https://stackoverflow.com/a/14246240/3076102)

I mix in a solution I found here https://stackoverflow.com/a/7967670 to properly show Objects.

This means the trap function becomes:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

I hope this is helpful:-)

Editable text to string

This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string

EditText dob=(EditText)findviewbyid(R.id.edit_id);
String  str=dob.getText().toString();

Getting a machine's external IP address with Python

import requests
import re


def getMyExtIp():
    try:
        res = requests.get("http://whatismyip.org")
        myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group()
        if myIp != "":
            return myIp
    except:
        pass
    return "n/a"

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

How to parse a CSV in a Bash script?

In a CSV file, each field is separated by a comma. The problem is, a field itself might have an embedded comma:

Name,Phone
"Woo, John",425-555-1212

You really need a library package that offer robust CSV support instead of relying on using comma as a field separator. I know that scripting languages such as Python has such support. However, I am comfortable with the Tcl scripting language so that is what I use. Here is a simple Tcl script which does what you are asking for:

#!/usr/bin/env tclsh

package require csv 
package require Tclx

# Parse the command line parameters
lassign $argv fileName columnNumber expectedValue

# Subtract 1 from columnNumber because Tcl's list index starts with a
# zero instead of a one
incr columnNumber -1

for_file line $fileName {
    set columns [csv::split $line]
    set columnValue [lindex $columns $columnNumber]
    if {$columnValue == $expectedValue} {
        puts $line
    }   
}

Save this script to a file called csv.tcl and invoke it as:

$ tclsh csv.tcl filename indexNumber expectedValue

Explanation

The script reads the CSV file line by line and store the line in the variable $line, then it split each line into a list of columns (variable $columns). Next, it picks out the specified column and assigned it to the $columnValue variable. If there is a match, print out the original line.

Java 256-bit AES Password-Based Encryption

Use this class for encryption. It works.

public class ObjectCrypter {


    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(mes);

    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException, ClassNotFoundException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(bytes);

    }
}

And these are ivBytes and a random key;

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");

Is there a max size for POST parameter content?

Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.

Increase max size of each multipart file to 10MB and total payload size of 100MB max

 spring:
    servlet:
      multipart:max-file-size: 10MB
      multipart:max-request-size: 100MB
 

Setting max size of post requests which might just be the formdata in string format to ~10 MB

 server:
    tomcat:
        max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version

You might need to add this for the latest sprintboot version ->

server: tomcat: max-http-form-post-size: 10MB

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

Add a scrollbar to a <textarea>

textarea {
    overflow-y: scroll; /* Vertical scrollbar */
    overflow: scroll; /* Horizontal and vertical scrollbar*/
}

mongod command not recognized when trying to connect to a mongodb server

For add environment variable please add \ after bin like below

C:\Program Files\MongoDB\Server\3.2\bin\

Then try below code in command prompt to run mongo server from parent folder of data folder.

mongod -dbpath ./data

For my case I am unable to run mongo from command prompt(normal mode). You should run as administrator. It also works on git bash.

Java - Convert String to valid URI object

Even if this is an old post with an already accepted answer, I post my alternative answer because it works well for the present issue and it seems nobody mentioned this method.

With the java.net.URI library:

URI uri = URI.create(URLString);

And if you want a URL-formatted string corresponding to it:

String validURLString = uri.toASCIIString();

Unlike many other methods (e.g. java.net.URLEncoder) this one replaces only unsafe ASCII characters (like ç, é...).


In the above example, if URLString is the following String:

"http://www.domain.com/façon+word"

the resulting validURLString will be:

"http://www.domain.com/fa%C3%A7on+word"

which is a well-formatted URL.

How to add external JS scripts to VueJS Components

This can be simply done like this.

  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }

How to position text over an image in css

Why not set sample.png as background image of text or h2 css class? This will give effect as you have written over an image.

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

No more data to read from socket error

I had the same problem. I was able to solve the problem from application side, under the following scenario:

JDK8, spring framework 4.2.4.RELEASE, apache tomcat 7.0.63, Oracle Database 11g Enterprise Edition 11.2.0.4.0

I used the database connection pooling apache tomcat-jdbc:

You can take the following configuration parameters as a reference:

<Resource name="jdbc/exampleDB"
      auth="Container"
      type="javax.sql.DataSource"
      factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
      testWhileIdle="true"
      testOnBorrow="true"
      testOnReturn="false"
      validationQuery="SELECT 1 FROM DUAL"
      validationInterval="30000"
      timeBetweenEvictionRunsMillis="30000"
      maxActive="100"
      minIdle="10"
      maxWait="10000"
      initialSize="10"
      removeAbandonedTimeout="60"
      removeAbandoned="true"
      logAbandoned="true"
      minEvictableIdleTimeMillis="30000"
      jmxEnabled="true"
      jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
        org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
      username="your-username"
      password="your-password"
      driverClassName="oracle.jdbc.driver.OracleDriver"
      url="jdbc:oracle:thin:@localhost:1521:xe"/>

This configuration was sufficient to fix the error. This works fine for me in the scenario mentioned above.

For more details about the setup apache tomcat-jdbc: https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html

SQL Server - Return value after INSERT

You can use scope_identity() to select the ID of the row you just inserted into a variable then just select whatever columns you want from that table where the id = the identity you got from scope_identity()

See here for the MSDN info http://msdn.microsoft.com/en-us/library/ms190315.aspx

Close window automatically after printing dialog closes

I tried many things that didn't work. The only thing that worked for me was:

window.print();
window.onafterprint = function () {
    window.close();
}

tested on chrome.

How to get Printer Info in .NET?

Just for reference, here is a list of all the available properties for a printer ManagementObject.

usage: printer.Properties["PropName"].Value

What is the difference between angular-route and angular-ui-router?

ngRoute is a module developed by the Angular.js team which was earlier part of the Angular core.

ui-router is a framework which was made outside the Angular.js project to improve and enhance routing capabalities.

How to prevent gcc optimizing some statements in C?

Instead of using the new pragmas, you can also use __attribute__((optimize("O0"))) for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.

Usage example:

void __attribute__((optimize("O0"))) foo(unsigned char data) {
    // unmodifiable compiler code
}

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

URL Encoding using C#

If you can't see System.Web, change your project settings. The target framework should be ".NET Framework 4" instead of ".NET Framework 4 Client Profile"

Find unique rows in numpy.array

If you want to avoid the memory expense of converting to a series of tuples or another similar data structure, you can exploit numpy's structured arrays.

The trick is to view your original array as a structured array where each item corresponds to a row of the original array. This doesn't make a copy, and is quite efficient.

As a quick example:

import numpy as np

data = np.array([[1, 1, 1, 0, 0, 0],
                 [0, 1, 1, 1, 0, 0],
                 [0, 1, 1, 1, 0, 0],
                 [1, 1, 1, 0, 0, 0],
                 [1, 1, 1, 1, 1, 0]])

ncols = data.shape[1]
dtype = data.dtype.descr * ncols
struct = data.view(dtype)

uniq = np.unique(struct)
uniq = uniq.view(data.dtype).reshape(-1, ncols)
print uniq

To understand what's going on, have a look at the intermediary results.

Once we view things as a structured array, each element in the array is a row in your original array. (Basically, it's a similar data structure to a list of tuples.)

In [71]: struct
Out[71]:
array([[(1, 1, 1, 0, 0, 0)],
       [(0, 1, 1, 1, 0, 0)],
       [(0, 1, 1, 1, 0, 0)],
       [(1, 1, 1, 0, 0, 0)],
       [(1, 1, 1, 1, 1, 0)]],
      dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8')])

In [72]: struct[0]
Out[72]:
array([(1, 1, 1, 0, 0, 0)],
      dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8')])

Once we run numpy.unique, we'll get a structured array back:

In [73]: np.unique(struct)
Out[73]:
array([(0, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0), (1, 1, 1, 1, 1, 0)],
      dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8'), ('f5', '<i8')])

That we then need to view as a "normal" array (_ stores the result of the last calculation in ipython, which is why you're seeing _.view...):

In [74]: _.view(data.dtype)
Out[74]: array([0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0])

And then reshape back into a 2D array (-1 is a placeholder that tells numpy to calculate the correct number of rows, give the number of columns):

In [75]: _.reshape(-1, ncols)
Out[75]:
array([[0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])

Obviously, if you wanted to be more concise, you could write it as:

import numpy as np

def unique_rows(data):
    uniq = np.unique(data.view(data.dtype.descr * data.shape[1]))
    return uniq.view(data.dtype).reshape(-1, data.shape[1])

data = np.array([[1, 1, 1, 0, 0, 0],
                 [0, 1, 1, 1, 0, 0],
                 [0, 1, 1, 1, 0, 0],
                 [1, 1, 1, 0, 0, 0],
                 [1, 1, 1, 1, 1, 0]])
print unique_rows(data)

Which results in:

[[0 1 1 1 0 0]
 [1 1 1 0 0 0]
 [1 1 1 1 1 0]]

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

My remote sql server was expecting connection at a different port and not on the default 1443.

The solution was to add a "," after your sql server IP and then add your port like so 129.0.0.1,2995 (Check the " , " after server IP)

Please find the image for reference below.

enter image description here

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You can also check the local changelog to verify whether or not OpenSSL is patched against the vulnerability with the following command:

rpm -q --changelog openssl | grep CVE-2014-0224

If a result is not returned, then you must patch OpenSSL.

http://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/

Get type name without full namespace

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

CSS class for pointer cursor

I usually just add the following custom CSS, the W3School example prepended with cursor-

_x000D_
_x000D_
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
_x000D_
_x000D_

Changing the space between each item in Bootstrap navbar

Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.

If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.

In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.

@media (min-width: 992px){
    .navbar li {
        margin-left : 1em;
        margin-right : 1em;
    }
}

Is there an auto increment in sqlite?

You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.

If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.

ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.

Also, you should try to avoid:

 INSERT INTO people VALUES ("John", "Smith");

and use

 INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");

instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).

WampServer orange icon

PLEASE NOTE! If you have gone through all of the above, like "I" did, and still get the Orange icon, and, when you test Port 80 you get "Apache", look at the file: c:/wamp/bin/apache/apache2.4.9/conf/httpd.conf (your apache version number may differ).

In the file, about line # 62, you'll find a note saying to fill in this:

Listen 0.0.0.0:80 Listen [::0]:80

Why?

Change this to Listen on specific IP addresses as shown below to prevent Apache from glomming onto all bound IP addresses.

I changed that to match my localhost IP address and when I restarted Wamp, it quickly went from Red to Green. Success!...3 hours later....

Renaming files using node.js

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

What does string::npos mean in this code?

we have to use string::size_type for the return type of the find function otherwise the comparison with string::npos might not work. size_type, which is defined by the allocator of the string, must be an unsigned integral type. The default allocator, allocator, uses type size_t as size_type. Because -1 is converted into an unsigned integral type, npos is the maximum unsigned value of its type. However, the exact value depends on the exact definition of type size_type. Unfortunately, these maximum values differ. In fact, (unsigned long)-1 differs from (unsigned short)-1 if the size of the types differs. Thus, the comparison

idx == std::string::npos

might yield false if idx has the value -1 and idx and string::npos have different types:

std::string s;
...
int idx = s.find("not found"); // assume it returns npos
if (idx == std::string::npos) { // ERROR: comparison might not work
...
}

One way to avoid this error is to check whether the search fails directly:

if (s.find("hi") == std::string::npos) {
...
}

However, often you need the index of the matching character position. Thus, another simple solution is to define your own signed value for npos:

const int NPOS = -1;

Now the comparison looks a bit different and even more convenient:

if (idx == NPOS) { // works almost always
...
}

How to detect when WIFI Connection has been established in Android?

November 2020:

I have dealt too much with items deprecated by Google. Finally I found a solution to my particular requirement using "registerNetworkCallback" as Google currently suggests.

What I needed was a simple way to detect that my device has an IPv4 assigned in WIFI. (I haven't tried other cases, my requirement was very specific, but maybe this method, without deprecated elements, will serve as a basis for other cases).

Tested on APIs 23, 24 and 26 (physical devices) and APIs 28 and 29 (emulated devices).

    ConnectivityManager cm 
            = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();

    cm.registerNetworkCallback
            (
                    builder.build(),
                    new ConnectivityManager.NetworkCallback()
                    {
                        @Override
                        public void onAvailable(Network network)
                        {
                            //Actions to take with Wifi available.
                        }
                        @Override
                        public void onLost(Network network)
                        {
                            //Actions to take with lost Wifi.
                        }
                    }

            );

(Implemented inside "MainActivity.Oncreate")

Note: In manifest needs "android.permission.ACCESS_NETWORK_STATE"

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

Set the maximum character length of a UITextField

I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse.

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {

    @IBInspectable var maxLength: Int {
        get {
            if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                return length
            } else {
                return Int.max
            }
        }
        set {
            objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
            self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
        }
    }

    func checkMaxLength(textField: UITextField) {

        guard !self.isInputMethod(), let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
                return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        text = prospectiveText.substring(to: maxCharIndex)
        selectedTextRange = selection
    }

    //The method is used to cancel the check when use Chinese Pinyin input method.
    //Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
    func isInputMethod() -> Bool {
        if let positionRange = self.markedTextRange {
            if let _ = self.position(from: positionRange.start, offset: 0) {
                return true
            }
        }
        return false
    }

}

Git Checkout warning: unable to unlink files, permission denied

You can change the write permissions to get it done.

sudo chmod -R ug+w . 

This command will give 'w' permissions to all the folders in the current directory.

SQL Server 2008 R2 can't connect to local database in Management Studio

Your "SQL Server Browser" service has to be started too.

Browse to Computer Management > Services. how to browse to computer management

Find find "SQL Server Browser"

  1. set it to Automatic
  2. and also Manually start it (2)

how to edit sql server browser properties and start it

Hope it helps.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

Making HTML page zoom by default

In js you can change zoom by

document.body.style.zoom="90%"

But it doesn't work in FF http://caniuse.com/#search=zoom

For ff you can try

-moz-transform: scale(0.9);

And check next topic How can I zoom an HTML element in Firefox and Opera?

How to create a HTTP server in Android?

NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.

The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.

Writing Unicode text to a text file?

Preface: will your viewer work?

Make sure your viewer/editor/terminal (however you are interacting with your utf-8 encoded file) can read the file. This is frequently an issue on Windows, for example, Notepad.

Writing Unicode text to a text file?

In Python 2, use open from the io module (this is the same as the builtin open in Python 3):

import io

Best practice, in general, use UTF-8 for writing to files (we don't even have to worry about byte-order with utf-8).

encoding = 'utf-8'

utf-8 is the most modern and universally usable encoding - it works in all web browsers, most text-editors (see your settings if you have issues) and most terminals/shells.

On Windows, you might try utf-16le if you're limited to viewing output in Notepad (or another limited viewer).

encoding = 'utf-16le' # sorry, Windows users... :(

And just open it with the context manager and write your unicode characters out:

with io.open(filename, 'w', encoding=encoding) as f:
    f.write(unicode_object)

Example using many Unicode characters

Here's an example that attempts to map every possible character up to three bits wide (4 is the max, but that would be going a bit far) from the digital representation (in integers) to an encoded printable output, along with its name, if possible (put this into a file called uni.py):

from __future__ import print_function
import io
from unicodedata import name, category
from curses.ascii import controlnames
from collections import Counter

try: # use these if Python 2
    unicode_chr, range = unichr, xrange
except NameError: # Python 3
    unicode_chr = chr

exclude_categories = set(('Co', 'Cn'))
counts = Counter()
control_names = dict(enumerate(controlnames))
with io.open('unidata', 'w', encoding='utf-8') as f:
    for x in range((2**8)**3): 
        try:
            char = unicode_chr(x)
        except ValueError:
            continue # can't map to unicode, try next x
        cat = category(char)
        counts.update((cat,))
        if cat in exclude_categories:
            continue # get rid of noise & greatly shorten result file
        try:
            uname = name(char)
        except ValueError: # probably control character, don't use actual
            uname = control_names.get(x, '')
            f.write(u'{0:>6x} {1}    {2}\n'.format(x, cat, uname))
        else:
            f.write(u'{0:>6x} {1}  {2}  {3}\n'.format(x, cat, char, uname))
# may as well describe the types we logged.
for cat, count in counts.items():
    print('{0} chars of category, {1}'.format(count, cat))

This should run in the order of about a minute, and you can view the data file, and if your file viewer can display unicode, you'll see it. Information about the categories can be found here. Based on the counts, we can probably improve our results by excluding the Cn and Co categories, which have no symbols associated with them.

$ python uni.py

It will display the hexadecimal mapping, category, symbol (unless can't get the name, so probably a control character), and the name of the symbol. e.g.

I recommend less on Unix or Cygwin (don't print/cat the entire file to your output):

$ less unidata

e.g. will display similar to the following lines which I sampled from it using Python 2 (unicode 5.2):

     0 Cc NUL
    20 Zs     SPACE
    21 Po  !  EXCLAMATION MARK
    b6 So  ¶  PILCROW SIGN
    d0 Lu  Ð  LATIN CAPITAL LETTER ETH
   e59 Nd  ?  THAI DIGIT NINE
  2887 So  ?  BRAILLE PATTERN DOTS-1238
  bc13 Lo  ?  HANGUL SYLLABLE MIH
  ffeb Sm  ?  HALFWIDTH RIGHTWARDS ARROW

My Python 3.5 from Anaconda has unicode 8.0, I would presume most 3's would.

Error 1053 the service did not respond to the start or control request in a timely fashion

I know this is old question, I used to write my own VB.NET windows service, and it has no issue to start on MS windows 7 and MS windows 10.

I have this issue when I install the windows services on latest MS windows 10 patch. The reason the windows service doesn't run it is because the .NET version that needed for the window services to run is not presented in the installed PC.

After you have installed the windows services. go to the install folder for example C:\Program files (x86)\Service1\Service1.exe and double click to run it. If there is missing .NET framework package, it will prompt the user to download it. Just download and and wait for it to install.

After that restart the windows services in services.msc. Hope this answer will help someone who face the issue. I know issue is caused by .NET framework version.

Changing CSS style from ASP.NET code

C#, because I don't want to typo the VB syntax.

Markup:

<div runat="server" id="divControl">...</div>

Class of the Page:

protected System.Web.UI.HtmlControls.HtmlGenericControl divControl;

OnLoad/Other function:

divControl.Style.Add("height", number / anotherNumer);

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

React this.setState is not a function

The callback is made in a different context. You need to bind to this in order to have access inside the callback:

VK.api('users.get',{fields: 'photo_50'},function(data){
    if(data.response){
        this.setState({ //the error happens here
            FirstName: data.response[0].first_name
        });
        console.info(this.state.FirstName);
    }

}.bind(this));

EDIT: Looks like you have to bind both the init and api calls:

VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                this.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(this.state.FirstName);
            }

        }.bind(this));
    }.bind(this), function(){
    console.info("API initialisation failed");

    }, '5.34');

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

Generate a random date between two other dates

# needed to create data for 1000 fictitious employees for testing code 
# code relating to randomly assigning forenames, surnames, and genders
# has been removed as not germaine to the question asked above but FYI
# genders were randomly assigned, forenames/surnames were web scrapped,
# there is no accounting for leap years, and the data stored in mySQL
   
import random 
from datetime import datetime
from datetime import timedelta

for employee in range(1000):
    # assign a random date of birth (employees are aged between sixteen and sixty five)
    dlt = random.randint(365*16, 365*65)
    dob = datetime.today() - timedelta(days=dlt)
    # assign a random date of hire sometime between sixteenth birthday and yesterday
    doh = datetime.today() - timedelta(days=random.randint(1, dlt-365*16))
    print("born {} hired {}".format(dob.strftime("%d-%m-%y"), doh.strftime("%d-%m-%y")))

Passing ArrayList through Intent

I have done this one by Passing ArrayList in form of String.

  1. Add compile 'com.google.code.gson:gson:2.2.4' in dependencies block build.gradle.

  2. Click on Sync Project with Gradle Files

Cars.java:

public class Cars {
    public String id, name;
}

FirstActivity.java

When you want to pass ArrayList:

List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));

Gson gson = new Gson();

String jsonCars = gson.toJson(cars);

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);

Get CarsModel by Function:

private Cars getCarModel(String id, String name){
       Cars cars = new Cars();
       cars.id = id;
       cars.name = name;
    return cars;
 }

SecondActivity.java

You have to import java.lang.reflect.Type ;

on onCreate() to retrieve ArrayList:

String carListAsString = getIntent().getStringExtra("list_as_string");

Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
   Log.i("Car Data", cars.id+"-"+cars.name);
}

Hope this will save time, I saved it.

Done

How to define hash tables in Bash?

Two things, you can use memory instead of /tmp in any kernel 2.6 by using /dev/shm (Redhat) other distros may vary. Also hget can be reimplemented using read as follows:

function hget {

  while read key idx
  do
    if [ $key = $2 ]
    then
      echo $idx
      return
    fi
  done < /dev/shm/hashmap.$1
}

In addition by assuming that all keys are unique, the return short circuits the read loop and prevents having to read through all entries. If your implementation can have duplicate keys, then simply leave out the return. This saves the expense of reading and forking both grep and awk. Using /dev/shm for both implementations yielded the following using time hget on a 3 entry hash searching for the last entry :

Grep/Awk:

hget() {
    grep "^$2 " /dev/shm/hashmap.$1 | awk '{ print $2 };'
}

$ time echo $(hget FD oracle)
3

real    0m0.011s
user    0m0.002s
sys     0m0.013s

Read/echo:

$ time echo $(hget FD oracle)
3

real    0m0.004s
user    0m0.000s
sys     0m0.004s

on multiple invocations I never saw less then a 50% improvement. This can all be attributed to fork over head, due to the use of /dev/shm.

Run batch file as a Windows service

As Doug Currie says use RunAsService.

From my past experience you must remember that the Service you generate will

  • have a completely different set of environment variables
  • have to be carefully inspected for rights/permissions issues
  • might cause havoc if it opens dialogs asking for any kind of input

not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

Parsing HTML using Python

I recommend using justext library:

https://github.com/miso-belica/jusText

Usage: Python2:

import requests
import justext

response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print paragraph.text

Python3:

import requests
import justext

response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print (paragraph.text)

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

Android canvas draw rectangle

paint.setStrokeWidth(3);

paint.setColor(BLACK);

and either one of your drawRect should work.

How can I pass data from Flask to JavaScript in a template?

Working answers are already given but I want to add a check that acts as a fail-safe in case the flask variable is not available. When you use:

var myVariable = {{ flaskvar | tojson }};

if there is an error that causes the variable to be non existent, resulting errors may produce unexpected results. To avoid this:

{% if flaskvar is defined and flaskvar %}
var myVariable = {{ flaskvar | tojson }};
{% endif %}

Java - How do I make a String array with values?

You could do something like this

String[] myStrings = { "One", "Two", "Three" };

or in expression

functionCall(new String[] { "One", "Two", "Three" });

or

String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };

How to get selected value of a dropdown menu in ReactJS

If you want to get value from a mapped select input then you can refer to this example:

class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          fruit: "banana",
        };
    
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        console.log("Fruit Selected!!");
        this.setState({ fruit: e.target.value });
      }
    
      render() {
        return (
          <div id="App">
            <div className="select-container">
              <select value={this.state.fruit} onChange={this.handleChange}>
                {options.map((option) => (
                  <option value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
          </div>
        );
      }
    }
    
    export default App;

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

Spark - repartition() vs coalesce()

One additional point to note here is that, as the basic principle of Spark RDD is immutability. The repartition or coalesce will create new RDD. The base RDD will continue to have existence with its original number of partitions. In case the use case demands to persist RDD in cache, then the same has to be done for the newly created RDD.

scala> pairMrkt.repartition(10)
res16: org.apache.spark.rdd.RDD[(String, Array[String])] =MapPartitionsRDD[11] at repartition at <console>:26

scala> res16.partitions.length
res17: Int = 10

scala>  pairMrkt.partitions.length
res20: Int = 2

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

Html- how to disable <a href>?

You can use CSS to accomplish this:

_x000D_
_x000D_
.disabled {
  pointer-events: none;
  cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
_x000D_
_x000D_

Or you can use JavaScript to prevent the default action like this:

$('.disabled').click(function(e){
    e.preventDefault();
})

C# Telnet Library

I am currently evaluating two .NET (v2.0) C# Telnet libraries that may be of interest:

Hope this helps.

Regards, Andy.

How to split a string literal across multiple lines in C / Objective-C?

I am having this problem all the time, so I made a tiny tool to convert text to an escaped multi-line Objective-C string:

http://multilineobjc.herokuapp.com/

Hope this saves you some time.

Installing specific laravel version with composer create-project

From the composer help create-project command

The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.

[version]
You can also specify the version with the package name using = or : as separator.

To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).

This command works:

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

This works with the * notation.

Calling a JavaScript function named in a variable

If it´s in the global scope it´s better to use:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

Exactly like Nosredna said 40 seconds before me that is >.<

Bootstrap: change background color

You could hard code it.

<div class="col-md-6" style="background-color:blue;">
</div>

<div class="col-md-6" style="background-color:white;">
</div>

Change label text using JavaScript

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

Sorting a list using Lambda/Linq to objects

You could use reflection to access the property.

public List<Employee> Sort(List<Employee> list, String sortBy, String sortDirection)
{
   PropertyInfo property = list.GetType().GetGenericArguments()[0].
                                GetType().GetProperty(sortBy);

   if (sortDirection == "ASC")
   {
      return list.OrderBy(e => property.GetValue(e, null));
   }
   if (sortDirection == "DESC")
   {
      return list.OrderByDescending(e => property.GetValue(e, null));
   }
   else
   {
      throw new ArgumentOutOfRangeException();
   }
}

Notes

  1. Why do you pass the list by reference?
  2. You should use a enum for the sort direction.
  3. You could get a much cleaner solution if you would pass a lambda expression specifying the property to sort by instead of the property name as a string.
  4. In my example list == null will cause a NullReferenceException, you should catch this case.

How to insert an item at the beginning of an array in PHP?

Use array_unshift() to insert the first element in an array.

User array_shift() to removes the first element of an array.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

How to query the permissions on an Oracle directory?

This should give you the roles, users and permissions granted on a directory:

SELECT * 
  FROM all_tab_privs 
 WHERE table_name = 'your_directory';  --> needs to be upper case

And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    SELECT last id, without INSERT

    You can get maximum column value and increment it:

    InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:

    SELECT MAX(ai_col) FROM t FOR UPDATE;
    

    InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.

    Also you can use SHOW TABLE STATUS and its "Auto_increment" value.

    Codeigniter displays a blank page instead of error messages

    This behavior occurs when you have basic php syntax error in your code. In case when you have syntax errors the php parser does not parse the code completely and didnot display anything so all of the above suggestion would work only if you have other than syntax errors.

    How to get row count using ResultSet in Java?

    Most drivers support forward only resultset - so method like last, beforeFirst etc are not supported.

    The first approach is suitable if you are also getting the data in the same loop - otherwise the resultSet has already been iterated and can not be used again.

    In most cases the requirement is to get the number of rows a query would return without fetching the rows. Iterating through the result set to find the row count is almost same as processing the data. It is better to do another count(*) query instead.

    Java switch statement: Constant expression required, but it IS constant

    I recommend you to use enums :)

    Check this out:

    public enum Foo 
    {
        BAR("bar"),
        BAZ("baz"),
        BAM("bam");
    
        private final String description;
    
        private Foo(String description)
        {
            this.description = description;
        }
    
        public String getDescription()
        {
            return description;
        }
    }
    

    Then you can use it like this:

    System.out.println(Foo.BAR.getDescription());
    

    setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

    Forget setAttribute(): it's badly broken and doesn't always do what you might expect in old IE (IE <= 8 and compatibility modes in later versions). Use the element's properties instead. This is generally a good idea, not just for this particular case. Replace your code with the following, which will work in all major browsers:

    var hiddenInput = document.createElement("input");
    hiddenInput.id = "uniqueIdentifier";
    hiddenInput.type = "hidden";                     
    hiddenInput.value = ID;
    hiddenInput.className = "ListItem";
    

    Update

    The nasty hack in the second code block in the question is unnecessary, and the code above works fine in all major browsers, including IE 6. See http://www.jsfiddle.net/timdown/aEvUT/. The reason why you get null in your alert() is that when it is called, the new input is not yet in the document, hence the document.getElementById() call cannot find it.

    How to check if a service is running on Android?

    Inside TheServiceClass define:

     public static Boolean serviceRunning = false;
    

    Then In onStartCommand(...)

     public int onStartCommand(Intent intent, int flags, int startId) {
    
        serviceRunning = true;
        ...
    }
    
     @Override
    public void onDestroy()
    {
        serviceRunning = false;
    
    } 
    

    Then, call if(TheServiceClass.serviceRunning == true) from any class.

    IndentationError: unexpected indent error

    import urllib.request
    import requests
    from bs4 import BeautifulSoup
    
            r = requests.get('https://icons8.com/icons/set/favicon')
    

    If you try to connect to such a site, you will get an indent error.

    import urllib.request
    import requests
    from bs4 import BeautifulSoup
    
    
    r = requests.get('https://icons8.com/icons/set/favicon')
    

    Python cares about indents

    How can I convert radians to degrees with Python?

    Python convert radians to degrees or degrees to radians:

    What are Radians and what problem does it solve?:

    Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

    https://en.wikipedia.org/wiki/Radian

    Conversion from radians to degrees

    Python examples using libraries calculating degrees from radians:

    >>> import math
    >>> math.degrees(0)                       #0 radians == 0 degrees
    0.0
    >>> math.degrees(math.pi/2)               #pi/2 radians is 90 degrees
    90.0
    >>> math.degrees(math.pi)                 #pi radians is 180 degrees
    180.0      
    >>> math.degrees(math.pi+(math.pi/2))     #pi+pi/2 radians is 270 degrees
    270.0 
    >>> math.degrees(math.pi+math.pi)         #2*pi radians is 360 degrees
    360.0      
    

    Python examples using libraries calculating radians from degrees:

    >>> import math
    >>> math.radians(0)           #0 degrees == 0 radians
    0.0
    >>> math.radians(90)          #90 degrees is pi/2 radians
    1.5707963267948966
    >>> math.radians(180)         #180 degrees is pi radians
    3.141592653589793
    >>> math.radians(270)         #270 degrees is pi+(pi/2) radians
    4.71238898038469
    >>> math.radians(360)         #360 degrees is 2*pi radians
    6.283185307179586
    

    Source: https://docs.python.org/3/library/math.html#angular-conversion

    The mathematical notation:

    Mathematical notation of degrees and radians

    You can do degree/radian conversion without libraries:

    If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

    Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.

    Lets crash that orbiter and Roll our own Radians to Degrees:

    Invalid radians as input return garbage output.

    >>> 0 * 180.0 / math.pi                         #0 radians is 0 degrees
    0.0
    >>> (math.pi/2) * 180.0 / math.pi               #pi/2 radians is 90 degrees
    90.0
    >>> (math.pi) * 180.0 / math.pi                 #pi radians is 180 degrees
    180.0
    >>> (math.pi+(math.pi/2)) * 180.0 / math.pi     #pi+(pi/2) radians is 270 degrees
    270.0
    >>> (2 * math.pi) * 180.0 / math.pi             #2*pi radians is 360 degrees
    360.0
    

    Degrees to radians:

    >>> 0 * math.pi / 180.0              #0 degrees in radians
    0.0
    >>> 90 * math.pi / 180.0             #90 degrees in radians
    1.5707963267948966
    >>> 180 * math.pi / 180.0            #180 degrees in radians
    3.141592653589793
    >>> 270 * math.pi / 180.0            #270 degrees in radians
    4.71238898038469
    >>> 360 * math.pi / 180.0            #360 degrees in radians
    6.283185307179586
    

    Expressing multiple rotations with degrees and radians

    Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

    >>> import math
    >>> math.radians(360)                 #one complete rotation
    6.283185307179586
    >>> math.radians(360+360)             #two rotations
    12.566370614359172
    >>> math.degrees(12.566370614359172)  #math.degrees and math.radians preserve the
    720.0                                 #number of rotations
    

    Collapsing multiple rotations:

    You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

    >>> import math
    >>> math.radians(720+90)        #2 whole rotations plus 90 is 14.14 radians
    14.137166941154069
    >>> math.radians((720+90)%360)  #14.1 radians brings you to 
    1.5707963267948966              #the end point as 1.57 radians.
    
    >>> math.degrees((2*math.pi)+(math.pi/2))            #one rotation plus a quarter 
    450.0                                                #rotation is 450 degrees.
    >>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
    90.0                                                    #rotation brings you to 90.
    

    Protip

    Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics: https://www.khanacademy.org/math/algebra2/trig-functions/intro-to-radians-alg2/v/introduction-to-radians

    Escaping quotation marks in PHP

    Use the addslashes function:

     $str = "Is your name O'Reilly?";
    
     // Outputs: Is your name O\'Reilly?
       echo addslashes($str);
    

    How to use EOF to run through a text file in C?

    I would suggest you to use fseek-ftell functions.

    FILE *stream = fopen("example.txt", "r");
    
    if(!stream) {
        puts("I/O error.\n");
        return;
    }
    
    fseek(stream, 0, SEEK_END);
    long size = ftell(stream);
    fseek(stream, 0, SEEK_SET);
    
    while(1) {
    
        if(ftell(stream) == size) {
            break;
        }
    
        /* INSERT ROUTINE */
    
    }
    
    fclose(stream);
    

    Exception thrown in catch and finally clause

    To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:

    try:
       fh = open("testfile", "w")
       try:
          fh.write("This is my test file for exception handling!!")
       finally:
          print "Going to close the file"
          fh.close()
    except IOError:
       print "Error: can\'t find file or read data"
    

    How to print (using cout) a number in binary form?

    Is there a standard way in C++ to show the binary representation in memory of a number [...]?

    No. There's no std::bin, like std::hex or std::dec, but it's not hard to output a number binary yourself:

    You output the left-most bit by masking all the others, left-shift, and repeat that for all the bits you have.

    (The number of bits in a type is sizeof(T) * CHAR_BIT.)

    USB Debugging option greyed out

    Connect the phone to a PC, make sure your developer options are enabled. Then, connection type must be MTP or File Transfer. Charge only does not allow USB debugging(disables the option).

    Is there any "font smoothing" in Google Chrome?

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

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

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

    CORS with POSTMAN

    CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.

    Related to clients

    • Most Browsers do enforce it to prevent issues related to CSRF attack.
    • Most Development tools don't care about it.

    Is it acceptable and safe to run pip install under sudo?

    It looks like your permissions are messed up. Type chown -R markwalker ~ in the Terminal and try pip again? Let me know if you're sorted.

    initialize a const array in a class initializer in C++

    With C++11 the answer to this question has now changed and you can in fact do:

    struct a {
        const int b[2];
        // other bits follow
    
        // and here's the constructor
        a();
    };
    
    a::a() :
        b{2,3}
    {
         // other constructor work
    }
    
    int main() {
     a a;
    }
    

    How to iterate through range of Dates in Java?

    Here is Java 8 code. I think this code will solve your problem.Happy Coding

        LocalDate start = LocalDate.now();
        LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
        Long duration = start.until(end, ChronoUnit.DAYS);
        System.out.println(duration);
         // Do Any stuff Here there after
        IntStream.iterate(0, i -> i + 1)
                 .limit(duration)
                 .forEach((i) -> {});
         //old way of iteration
        for (int i = 0; i < duration; i++)
         System.out.print("" + i);// Do Any stuff Here
    

    NameError: name 'reduce' is not defined in Python

    Or if you use the six library

    from six.moves import reduce
    

    Common CSS Media Queries Break Points

    I can tell you I am using just a single breakpoint at 768 - that is min-width: 768px to serve tablets and desktops, and max-width: 767px to serve phones.

    I haven't looked back since. It makes the responsive development easy and not a chore, and provides a reasonable experience on all devices at minimal cost to development time without the need to fear a new Android device with a new resolution you haven't factored in.

    Assigning strings to arrays of characters

    What I would use is

    char *s = "abcd";
    

    What is the difference between max-device-width and max-width for mobile web?

    If you are making a cross-platform app (eg. using phonegap/cordova) then,

    Don't use device-width or device-height. Rather use width or height in CSS media queries because Android device will give problems in device-width or device-height. For iOS it works fine. Only android devices doesn't support device-width/device-height.

    jQuery callback on image load (even when the image is cached)

    I had this problem with IE where the e.target.width would be undefined. The load event would fire but I couldn't get the dimensions of the image in IE (chrome + FF worked).

    Turns out you need to look for e.currentTarget.naturalWidth & e.currentTarget.naturalHeight.

    Once again, IE does things it's own (more complicated) way.

    Difference between java.lang.RuntimeException and java.lang.Exception

    An Exception is checked, and a RuntimeException is unchecked.

    Checked means that the compiler requires that you handle the exception in a catch, or declare your method as throwing it (or one of its superclasses).

    Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.

    Java - How to convert type collection into ArrayList?

    As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

    http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

    So you need to do:

    ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());
    

    However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

    I think your code should look like this:

    public V getNode(int nodeId){
            ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
            return myNodeList(nodeId);
    }
    

    But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

    WCF Exception: Could not find a base address that matches scheme http for the endpoint

    My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https

    Choose 'IIS Express Development Certificate' and set port to 443

    How to to send mail using gmail in Laravel?

    your MAIL_PASSWORD=must a APPpasword after change the .env stop the server then clear configuratios cahce php artisan config:cahce and start the server again

    reference Cannot send message without a sender address in laravel 5.2 I have set .env and mail.php both

    What is the proper use of an EventEmitter?

    Yes, go ahead and use it.

    EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

    As also stated in the docs:

    Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

    Once a reference implementation of the spec is available, switch to it.

    So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

    There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

    Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

    export class MyServiceEvent {
        message: string;
        eventId: number;
    }
    
    export class MyService {
        public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();
    
        public doSomething(message: string) {
            // do something, then...
            this.onChange.emit({message: message, eventId: 42});
        }
    }
    
    export class MyConsumer {
        private _serviceSubscription;
    
        constructor(private service: MyService) {
            this._serviceSubscription = this.service.onChange.subscribe({
                next: (event: MyServiceEvent) => {
                    console.log(`Received message #${event.eventId}: ${event.message}`);
                }
            })
        }
    
        public consume() {
            // do some stuff, then later...
    
            this.cleanup();
        }
    
        private cleanup() {
            this._serviceSubscription.unsubscribe();
        }
    }
    

    All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

    POST unchecked HTML checkboxes

    Add a hidden input for the checkbox with a different ID:

    <input id='testName' type='checkbox' value='Yes' name='testName'>
    <input id='testNameHidden' type='hidden' value='No' name='testName'>
    

    Before submitting the form, disable the hidden input based on the checked condition:

    if(document.getElementById("testName").checked) {
        document.getElementById('testNameHidden').disabled = true;
    }
    

    Perl - If string contains text?

    If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

    if (index($string, $substring) != -1) {
       print "'$string' contains '$substring'\n";
    }
    

    To search a string for a pattern match, use the match operator m//:

    if ($string =~ m/pattern/) {
        print "'$string' matches the pattern\n";       
    }
    

    Remove all multiple spaces in Javascript and replace with single space

    You could use a regular expression replace:

    str = str.replace(/ +(?= )/g,'');
    

    Credit: The above regex was taken from Regex to replace multiple spaces with a single space

    wampserver doesn't go green - stays orange

    But if it does not solve the problem, you probably have installed sql 2008 R2, so the solution that worked to me was this wamp server problems yellow symbol

    Can you nest html forms?

    Before I knew I wasn't supposed to do this I had nested forms for the purpose of having multiple submit buttons. Ran that way for 18 months, thousands of signup transactions, no one called us about any difficulties.

    Nested forms gave me an ID to parse for the correct action to take. Didn't break 'til I tried to attach a field to one of the buttons and Validate complained. Wasn't a big deal to untangle it--I used an explicit stringify on the outer form so it didn't matter the submit and form didn't match. Yeah, yeah, should've taken the buttons from a submit to an onclick.

    Point is there are circumstances where it's not entirely broken. But "not entirely broken" is perhaps too low a standard to shoot for :-)

    How to clear the JTextField by clicking JButton

    Looking for EventHandling, ActionListener?

    or code?

    JButton b = new JButton("Clear");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            textfield.setText("");
            //textfield.setText(null); //or use this
        }
    });
    

    Also See
    How to Use Buttons

    How can I protect my .NET assemblies from decompilation?

    Do you API?

    Instead of trying to protect your one ddl file in one of your products on all of your customers devices, why not create an API service for your precious product features? Let the actual product that is saved on a device consume that API to deliver the product as you want it.

    I Think this way you are 100% sure that your code is not decompiled and you set your own limits in your API so that developers / hackers don't consume your API in a way you don't want it.

    Sure is some more work, but in the end, you are in control.

    Jquery Validate custom error message location

     if (e.attr("name") == "firstName" ) {
         $("#firstName__validate").text($(error).text());
         console.log($(error).html());
     }
    

    Try this get text of error object

    Set padding for UITextField with UITextBorderStyleNone

    Updated version for Swift 3:

    @IBDesignable
    class FormTextField: UITextField {
    
        @IBInspectable var paddingLeft: CGFloat = 0
        @IBInspectable var paddingRight: CGFloat = 0
    
        override func textRect(forBounds bounds: CGRect) -> CGRect {
            return CGRect(x: bounds.origin.x + paddingLeft, y: bounds.origin.y, width: bounds.size.width - paddingLeft - paddingRight, height: bounds.size.height)
        }
    
        override func editingRect(forBounds bounds: CGRect) -> CGRect {
            return textRect(forBounds: bounds)
        }
    }
    

    How do I select child elements of any depth using XPath?

    //form/descendant::input[@type='submit']
    

    Get installed applications in a system

    My requirement is to check if specific software is installed in my system. This solution works as expected. It might help you. I used a windows application in c# with visual studio 2015.

     private void Form1_Load(object sender, EventArgs e)
            {
    
                object line;
                string softwareinstallpath = string.Empty;
                string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
                {
                    using (var key = baseKey.OpenSubKey(registry_key))
                    {
                        foreach (string subkey_name in key.GetSubKeyNames())
                        {
                            using (var subKey = key.OpenSubKey(subkey_name))
                            {
                                line = subKey.GetValue("DisplayName");
                                if (line != null && (line.ToString().ToUpper().Contains("SPARK")))
                                {
    
                                    softwareinstallpath = subKey.GetValue("InstallLocation").ToString();
                                    listBox1.Items.Add(subKey.GetValue("InstallLocation"));
                                    break;
                                }
                            }
                        }
                    }
                }
    
                if(softwareinstallpath.Equals(string.Empty))
                {
                    MessageBox.Show("The Mirth connect software not installed in this system.")
                }
    
    
    
                string targetPath = softwareinstallpath + @"\custom-lib\";
                string[] files = System.IO.Directory.GetFiles(@"D:\BaseFiles");
    
                // Copy the files and overwrite destination files if they already exist. 
                foreach (var item in files)
                {
                    string srcfilepath = item;
                    string fileName = System.IO.Path.GetFileName(item);
                    System.IO.File.Copy(srcfilepath, targetPath + fileName, true);
                }
                return;
    
            }
    

    Remove innerHTML from div

    
    var $div = $('#desiredDiv');
    $div.contents().remove();
    $div.html('<p>This is new HTML.</p>');
    

    That should work just fine.

    Adding elements to an xml file in C#

    <Snippet name="abc"> 
    

    name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet> element.

    root.SetAttribute("name", "name goes here");
    

    is the code you need with what you have.