Programs & Examples On #Lsa

LSA stands for Latent Semantic Analysis, a natural language processing technique which involves analysing the relationships between documents and terms they contain by producing a set of related concepts.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I had a similar issue, and discovered that option arguments must be in a certain order. I am only aware of the two arguments that were required to get this working on my Ubuntu 18 machine. This sample code worked on my end:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

d = webdriver.Chrome(executable_path=r'/home/PycharmProjects/chromedriver', chrome_options=options)
d.get('https://www.google.nl/')

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

In my case, I was trying to create a runnable jar on Windows OS with chrome browser and want to run the same on headless mode in unix box with CentOs on it. And I was pointing my binary to a driver that I have downloaded and packaged with my suite. For me, this issue continue to occur irrespective of adding the below:

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--no-sandbox");
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
options.setBinary("/pointing/downloaded/driver/path/in/automationsuite");
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("window-size=1024,768"); // Bypass OS security model
options.addArguments("--log-level=3"); // set log level
options.addArguments("--silent");//
options.setCapability("chrome.verbose", false); //disable logging
driver = new ChromeDriver(options);

Solution that I've tried and worked for me is, download the chrome and its tools on the host VM/Unix box, install and point the binary to this in the automation suite and bingo! It works :)

Download command:

wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

Install command:

sudo yum install -y ./google-chrome-stable_current_*.rpm

Update suite with below binary path of google-chrome:

options.setBinary("/opt/google/chrome/google-chrome");

And.. it works!

Access IP Camera in Python OpenCV

This works with my IP camera:

import cv2

#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")

while True:

    #print('About to start the Read command')
    ret, frame = cap.read()
    #print('About to show frame of Video.')
    cv2.imshow("Capturing",frame)
    #print('Running..')

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

I found the Stream URL in the Camera's Setup screen: IP Camera Setup Screen

Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)

How to show all of columns name on pandas dataframe?

If you just want to see all the columns you can do something of this sort as a quick fix

cols = data_all2.columns

now cols will behave as a iterative variable that can be indexed. for example

cols[11:20]

react-router go back a page how do you configure history?

Update with React v16 and ReactRouter v4.2.0 (October 2017):

class BackButton extends Component {
  static contextTypes = {
    router: () => true, // replace with PropTypes.object if you use them
  }

  render() {
    return (
      <button
        className="button icon-left"
        onClick={this.context.router.history.goBack}>
          Back
      </button>
    )
  }
}

Update with React v15 and ReactRouter v3.0.0 (August 2016):

var browserHistory = ReactRouter.browserHistory;

var BackButton = React.createClass({
  render: function() {
    return (
      <button
        className="button icon-left"
        onClick={browserHistory.goBack}>
        Back
      </button>
    );
  }
});

Created a fiddle with a little bit more complex example with an embedded iframe: https://jsfiddle.net/kwg1da3a/

React v14 and ReacRouter v1.0.0 (Sep 10, 2015)

You can do this:

var React = require("react");
var Router = require("react-router");

var SomePage = React.createClass({
  ...

  contextTypes: {
    router: React.PropTypes.func
  },
  ...

  handleClose: function () {
    if (Router.History.length > 1) {
      // this will take you back if there is history
      Router.History.back();
    } else {
      // this will take you to the parent route if there is no history,
      // but unfortunately also add it as a new route
      var currentRoutes = this.context.router.getCurrentRoutes();
      var routeName = currentRoutes[currentRoutes.length - 2].name;
      this.context.router.transitionTo(routeName);
    }
  },
  ...

You need to be careful that you have the necessary history to go back. If you hit the page directly and then hit back it will take you back in the browser history before your app.

This solution will take care of both scenarios. It will, however, not handle an iframe that can navigate within the page (and add to the browser history), with the back button. Frankly, I think that is a bug in the react-router. Issue created here: https://github.com/rackt/react-router/issues/1874

python save image from url

Python3

import urllib.request
print('Beginning file download with urllib2...')
url = 'https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/modi_instagram_660_020320092717.jpg'
urllib.request.urlretrieve(url, 'modiji.jpg')

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

Spring Boot, Spring Data JPA with multiple DataSources

I have written a complete article at Spring Boot JPA Multiple Data Sources Example. In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application. We will use Spring Boot 2.0.5, JPA, Hibernate 5, Thymeleaf and H2 database to build a simple Spring Boot multiple data sources web application.

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

Match linebreaks - \n or \r\n?

This only applies to question 1.

I have an app that runs on Windows and uses a multi-line MFC editor box.
The editor box expects CRLF linebreaks, but I need to parse the text enterred
with some really big/nasty regexs'.

I didn't want to be stressing about this while writing the regex, so
I ended up normalizing back and forth between the parser and editor so that
the regexs' just use \n. I also trap paste operations and convert them for the boxes.

This does not take much time.
This is what I use.

 boost::regex  CRLFCRtoLF (
     " \\r\\n | \\r(?!\\n) "
     , MODx);

 boost::regex  CRLFCRtoCRLF (
     " \\r\\n?+ | \\n "
     , MODx);


 // Convert (All style) linebreaks to linefeeds 
 // ---------------------------------------
 void ReplaceCRLFCRtoLF( string& strSrc, string& strDest )
 {
    strDest  = boost::regex_replace ( strSrc, CRLFCRtoLF, "\\n" );
 }

 // Convert linefeeds to linebreaks (Windows) 
 // ---------------------------------------
 void ReplaceCRLFCRtoCRLF( string& strSrc, string& strDest )
 {
    strDest  = boost::regex_replace ( strSrc, CRLFCRtoCRLF, "\\r\\n" );
 }

Attempt to set a non-property-list object as an NSUserDefaults

Swift- 4 Xcode 9.1

try this code

you can not store mapper in NSUserDefault, you can only store NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

let myData = NSKeyedArchiver.archivedData(withRootObject: myJson)
UserDefaults.standard.set(myData, forKey: "userJson")

let recovedUserJsonData = UserDefaults.standard.object(forKey: "userJson")
let recovedUserJson = NSKeyedUnarchiver.unarchiveObject(with: recovedUserJsonData)

Bootstrap carousel width and height

If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Third slide">
    </div>
  </div>
</div>

Solution:

The solution is to put "div" around the image, with the class ".container", like this:

<div class="carousel-item active">
  <div class="container">
    <img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
  </div>
</div>

Split a large dataframe into a list of data frames based on common value in column

Stumbled across this answer and I actually wanted BOTH groups (data containing that one user and data containing everything but that one user). Not necessary for the specifics of this post, but I thought I would add in case someone was googling the same issue as me.

df <- data.frame(
     ran_data1=rnorm(125),
     ran_data2=rnorm(125),
     g=rep(factor(LETTERS[1:5]), 25)
 )

test_x = split(df,df$g)[['A']]
test_y = split(df,df$g!='A')[['TRUE']]

Here's what it looks like:

head(test_x)
            x          y g
1   1.1362198  1.2969541 A
6   0.5510307 -0.2512449 A
11  0.0321679  0.2358821 A
16  0.4734277 -1.2889081 A
21 -1.2686151  0.2524744 A

> head(test_y)
            x          y g
2 -2.23477293  1.1514810 B
3 -0.46958938 -1.7434205 C
4  0.07365603  0.1111419 D
5 -1.08758355  0.4727281 E
7  0.28448637 -1.5124336 B
8  1.24117504  0.4928257 C

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I faced a bit of a different issue that returned the same error.

Skipping JaCoCo execution due to missing execution data /target/jacoco.exec

The truth is, this error is returned for many, many reasons. We experimented with the different solutions on Stack Overflow, but found this resource to be best. It tears down the many different potential reasons why Jacoco could be returning the same error.

For us, the solution was to add a prepare-agent to the configuration.

<execution>
   <id>default-prepare-agent</id>
   <goals>
       <goal>prepare-agent</goal>
   </goals>
</execution>

I would imagine most users will be experiencing it for different reasons, so take a look at the aforementioned resource!

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

To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The / seemed to solve this problem for me :)

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Below is the exact code you need to make your sheet look exactly as it is in the attached PDF:

try
        {
            Excel.Application application;
            Excel.Workbook workBook;
            Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;

            application = new Excel.ApplicationClass();
            workBook = application.Workbooks.Add(misValue);
            workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 1;
            workSheet.Cells[i, 2] = "MSS Close Sheet"; 
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;               
            i++;
            workSheet.Cells[i, 2] = "MSS - " + dpsNoTextBox.Text;
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;
            workSheet.Cells[i, 2] = customerNameTextBox.Text;
            i++;                
            workSheet.Cells[i, 2] = "Opening Date : ";
            workSheet.Cells[i, 3] = openingDateTextBox.Value.ToShortDateString();
            i++;
            workSheet.Cells[i, 2] = "Closing Date : ";
            workSheet.Cells[i, 3] = closingDateTextBox.Value.ToShortDateString();
            i++;
            i++;
            i++;

            workSheet.Cells[i, 1] = "SL. No";
            workSheet.Cells[i, 2] = "Month";
            workSheet.Cells[i, 3] = "Amount Deposited";
            workSheet.Cells[i, 4] = "Fine";
            workSheet.Cells[i, 5] = "Cumulative Total";
            workSheet.Cells[i, 6] = "Profit + Cumulative Total";
            workSheet.Cells[i, 7] = "Profit @ " + profitRateComboBox.Text;
            WorkSheet.Cells[i, 1].EntireRow.Font.Bold = true;
            i++;



            /////////////////////////////////////////////////////////
            foreach (RecurringDeposit rd in RecurringDepositList)
            {
                workSheet.Cells[i, 1] = rd.SN.ToString();
                workSheet.Cells[i, 2] = rd.MonthYear;
                workSheet.Cells[i, 3] = rd.InstallmentSize.ToString();
                workSheet.Cells[i, 4] = "";
                workSheet.Cells[i, 5] = rd.CumulativeTotal.ToString();
                workSheet.Cells[i, 6] = rd.ProfitCumulative.ToString();
                workSheet.Cells[i, 7] = rd.Profit.ToString();
                i++;
            }
            //////////////////////////////////////////////////////


            ////////////////////////////////////////////////////////
            workSheet.Cells[i, 2] = "Total (" + RecurringDepositList.Count + " months installment)";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "a) Total Amount Deposited";
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "b) Fine";
            workSheet.Cells[i, 3] = "";
            i++;

            workSheet.Cells[i, 2] = "c) Total Pft Paid";
            workSheet.Cells[i, 3] = totalProfitPaidTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Sub Total";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (totalAmountDepositedTextBox.Value + totalProfitPaidTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Deduction";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;

            workSheet.Cells[i, 2] = "a) Excise Duty";
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "b) Income Tax on Pft. @ " + incomeTaxPercentageTextBox.Text;
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "c) Account Closing Charge ";
            workSheet.Cells[i, 3] = closingChargeCommaNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "d) Outstanding on BAIM(FO) ";
            workSheet.Cells[i, 3] = baimFOLowerTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Total Deduction ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (incomeTaxDeductionTextBox.Value + closingChargeCommaNumberTextBox.Value + baimFOTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Client Paid ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Current Balance ";
            workSheet.Cells[i, 3] = currentBalanceCommaNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "Exp. Pft paid on MSS A/C(PL67054)";
            workSheet.Cells[i, 6] = plTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Total Paid ";
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "IT on Pft (BDT16216)";
            workSheet.Cells[i, 6] = incomeTaxDeductionTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Difference";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (currentBalanceCommaNumberTextBox.Value - customerPayableNumberTextBox.Value).ToString("0.00");
            workSheet.Cells[i, 5] = "Account Closing Charge";
            workSheet.Cells[i, 6] = closingChargeCommaNumberTextBox.Value;
            i++;

            ///////////////////////////////////////////////////////////////

            workBook.SaveAs("D:\\" + dpsNoTextBox.Text.Trim() + "-" + customerNameTextBox.Text.Trim() + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, misValue, misValue);
            application.Quit();

            releaseObject(workSheet);
            releaseObject(workBook);
            releaseObject(application);

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I had this problem, and turns out the problem was that I had used

new SimpleJdbcCall(jdbcTemplate)
    .withProcedureName("foo")

instead of

new SimpleJdbcCall(jdbcTemplate)
    .withFunctionName("foo")

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:

https://stackoverflow.com/a/33481683/1897196

Adding image inside table cell in HTML

You have referenced the image as a path on your computer (C:\etc\etc)......is it located there? You didn't answer what others have asked. I have taken your code, placed it in dreamweaver and it works apart from the image as I don't have that stored.

Check the location and then let us know.

Twitter Bootstrap carousel different height images cause bouncing arrows

 .className{
 width: auto;
  height: 200px;
  max-height: 200px;
   max-width:200px
   object-fit: contain;
}

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Probably in this case you obtained your account object using the merge logic, and persist is used to persist new objects and it will complain if the hierarchy is having an already persisted object. You should use saveOrUpdate in such cases, instead of persist.

Reading Data From Database and storing in Array List object

Try creating new instance of customer every time e.g.

         while (rs.next()) {

        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));
        customer.setName(rs.getString("name"));

        customer.setAddress(rs.getString("address"));
        customer.setPhone(rs.getString("phone"));
        customer.setEmail(rs.getString("email"));
        customer.setBountPoints(rs.getInt("bonuspoint"));
        customer.setTotalsale(rs.getInt("totalsale"));

        customers.add(customer);


    }

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

You can't use Microsoft.Office.Interop.Excel without having ms office installed.

Just search in google for some libraries, which allows to modify xls or xlsx:

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

Get The Current Domain Name With Javascript (Not the path, etc.)

You can get it from location object in Javascript easily:

For example URL of this page is:

http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc

Then we can get the exact domain with following properties of location object:

location.host = "www.stackoverflow.com"
location.protocol= "http:"

you can make the full domain with:

location.protocol + "//" + location.host

Which in this example returns http://www.stackoverflow.com

I addition of this we can get full URL and also the path with other properties of location object:

location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"    
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"

How to hide output of subprocess in Python 2.7

Redirect the output to DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null")

Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL, 
    stderr=subprocess.STDOUT)

Bootstrap Carousel image doesn't align properly

With bootstrap 3, just add the responsive and center classes:

 <img class="img-responsive center-block" src="img/....jpg" alt="First slide">

This automatically does image resizing, and centers the picture.

Edit:

With bootstrap 4, just add the img-fluid class

<img class="img-fluid" src="img/....jpg">

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Should look like this:

UPDATE DHE.dbo.tblAccounts
   SET DHE.dbo.tblAccounts.ControllingSalesRep = 
       DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
  from DHE.dbo.tblAccounts 
     INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink 
        ON DHE.dbo.tblAccounts.AccountCode =
           DHE_Import.tblSalesRepsAccountsLink.AccountCode 

Update table is repeated in FROM clause.

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

Salt and hash a password in Python

EDIT: This answer is wrong. A single iteration of SHA512 is fast, which makes it inappropriate for use as a password hashing function. Use one of the other answers here instead.


Looks fine by me. However, I'm pretty sure you don't actually need base64. You could just do this:

import hashlib, uuid
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()

If it doesn't create difficulties, you can get slightly more efficient storage in your database by storing the salt and hashed password as raw bytes rather than hex strings. To do so, replace hex with bytes and hexdigest with digest.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Java, "Variable name" cannot be resolved to a variable

public void setHoursWorked(){
    hoursWorked = hours;
}

You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.

WCF named pipe minimal example

Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:

Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:

<configuration>
    <system.serviceModel>
        <services>
            <service name="com.aschneider.examples.wcf.services.EchoService">
                <host>
                    <baseAddresses>
                        <add baseAddress="net.pipe://localhost/EchoService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors></serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:

<configuration>
    <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IEchoService"/>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address              = "net.pipe://localhost/EchoService"
                      binding              = "netNamedPipeBinding"
                      bindingConfiguration = "NetNamedPipeBinding_IEchoService"
                      contract             = "EchoServiceReference.IEchoService"
                      name                 = "NetNamedPipeBinding_IEchoService"/>
        </client>
    </system.serviceModel>
</configuration>

The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).

Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...

ExecJS and could not find a JavaScript runtime

Add following gems in your gem file

gem 'therubyracer'
gem 'execjs'

and run

bundle install

you are done :)

How to go back to previous page if back button is pressed in WebView?

I use something like this in my activities with WebViews:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

Edit:

For this code to work, you need to add a field to the Activity containing the WebView:

private WebView mWebView;

Initialize it in the onCreate() method and you should be good to go.

mWebView = (WebView) findViewById(R.id.webView);

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.

Hope this helps.

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

System.Runtime.InteropServices.COMException (0x800A03EC)

I was seeing this same error when trying to save an excel file. The code worked fine when I was using MS Office 2003, but after upgrading to MS Office 2007 I started seeing this. It would happen anytime I tried to save an Excel file to a server or remote fie share.

My solution, though rudimentary, worked well. I just had the program save the file locally, like to the user's C:\ drive. Then use the "System.IO.File.Copy(File, Destination, Overwrite)" method to move the file to the server. Then you can delete the file on the C:\ drive.

Works great, and simple. But admittedly not the most elegant approach.

Hope this helps! I was having a ton of trouble finding any solutions on the web till this idea popped into my head.

Find (and kill) process locking port 3000 on Mac

Execute in command line on OS-X El Captain:

kill -kill `lsof -t -i tcp:3000`

Terse option of lsof returns just the PID.

Which Eclipse version should I use for an Android app?

You can use the Eclipse Indigo EE version for Android development. It is quite good, and I haven't faced any issues so far.

Reference — What does this symbol mean in PHP?

An overview of operators in PHP:


Logical Operators:

  • $a && $b : TRUE if both $a and $b are TRUE.
  • $a || $b : TRUE if either $a or $b is TRUE.
  • $a xor $b : TRUE if either $a or $b is TRUE, but not both.
  • ! $a : TRUE if $a is not TRUE.
  • $a and $b : TRUE if both $a and $b are TRUE.
  • $a or $b : TRUE if either $a or $b is TRUE.

Comparison operators:

  • $a == $b : TRUE if $a is equal to $b after type juggling.
  • $a === $b : TRUE if $a is equal to $b, and they are of the same type.
  • $a != $b : TRUE if $a is not equal to $b after type juggling.
  • $a <> $b : TRUE if $a is not equal to $b after type juggling.
  • $a !== $b : TRUE if $a is not equal to $b, or they are not of the same type.
  • $a < $b : TRUE if $a is strictly less than $b.
  • $a > $b : TRUE if $a is strictly greater than $b.
  • $a <= $b : TRUE if $a is less than or equal to $b.
  • $a >= $b : TRUE if $a is greater than or equal to $b.
  • $a <=> $b : An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.
  • $a ? $b : $c : if $a return $b else return $c (ternary operator)
  • $a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires PHP>=7)

Arithmetic Operators:

  • -$a : Opposite of $a.
  • $a + $b : Sum of $a and $b.
  • $a - $b : Difference of $a and $b.
  • $a * $b : Product of $a and $b.
  • $a / $b : Quotient of $a and $b.
  • $a % $b : Remainder of $a divided by $b.
  • $a ** $b : Result of raising $a to the $b'th power (introduced in PHP 5.6)

Incrementing/Decrementing Operators:

  • ++$a : Increments $a by one, then returns $a.
  • $a++ : Returns $a, then increments $a by one.
  • --$a : Decrements $a by one, then returns $a.
  • $a-- : Returns $a, then decrements $a by one.

Bitwise Operators:

  • $a & $b : Bits that are set in both $a and $b are set.
  • $a | $b : Bits that are set in either $a or $b are set.
  • $a ^ $b : Bits that are set in $a or $b but not both are set.
  • ~ $a : Bits that are set in $a are not set, and vice versa.
  • $a << $b : Shift the bits of $a $b steps to the left (each step means "multiply by two")
  • $a >> $b : Shift the bits of $a $b steps to the right (each step means "divide by two")

String Operators:

  • $a . $b : Concatenation of $a and $b.

Array Operators:

  • $a + $b : Union of $a and $b.
  • $a == $b : TRUE if $a and $b have the same key/value pairs.
  • $a === $b : TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
  • $a != $b : TRUE if $a is not equal to $b.
  • $a <> $b : TRUE if $a is not equal to $b.
  • $a !== $b : TRUE if $a is not identical to $b.

Assignment Operators:

  • $a = $b : The value of $b is assigned to $a
  • $a += $b : Same as $a = $a + $b
  • $a -= $b : Same as $a = $a - $b
  • *$a = $b : Same as $a = $a * $b
  • $a /= $b : Same as $a = $a / $b
  • $a %= $b : Same as $a = $a % $b
  • **$a = $b : Same as $a = $a ** $b
  • $a .= $b : Same as $a = $a . $b
  • $a &= $b : Same as $a = $a & $b
  • $a |= $b : Same as $a = $a | $b
  • $a ^= $b : Same as $a = $a ^ $b
  • $a <<= $b : Same as $a = $a << $b
  • $a >>= $b : Same as $a = $a >> $b
  • $a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)

Note

and operator and or operator have lower precedence than assignment operator =.

This means that $a = true and false; is equivalent to ($a = true) and false.

In most cases you will probably want to use && and ||, which behave in a way known from languages like C, Java or JavaScript.

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5xajQAAAABDnFqgAAAAAEOcWrRBnlHwQ5xax0MvOY9DnFraQ6AiZkOcWu5DquEAQ5xbAUNtwQNDnFsVQqVdQEOcWygAAAAAQ5xbPAAAAABDnFtPAAAAAEOcW2IAAAAAQ6Cg+AAAAABDoKEMAAAAAEOgoSEAAAAAQ6ChNQAAAABDoKFKQwi7a0OgoV5DOmAdQ6Chc0NSxE9DoKGHQy7KVUOgoZxCvXN4Q6ChsAAAAABDoKHFAAAAAEOgodkAAAAAQ6Ch7gAAAABDo3scAAAAAEOjezEAAAAAQ6N7RgAAAABDo3tcAAAAAEOje3FCY5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AAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXpC8AAAAAERekQsAAAAARF7MvgAAAABEXs0NAAAAAERezVwAAAAARF7NqgAAAABEXs35Q478yERezkhDw2IoRF7Ol0PtNthEXs7mQ+gZFERezzVDnL2ORF7PhAAAAABEXs/TAAAAAERe0CEAAAAARF7QcAAAAABEYs8hAAAAAERiz3MAAAAARGLPxQAAAABEYtAXAAAAAERi0GhCk7m4RGLQukOaFH5EYtEMQ8gFaERi0V1DoL7mRGLRr0MQ5L1EYtIBAAAAAERi0lMAAAAARGLSpAAAAABEYtL2AAAAAERjTncAAAAARGNOyQAAAABEY08bAAAAAERjT20AAAAARGNPv0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AAAAER1FRIAAAAARIFNGgAAAABEgU1PAAAAAESBTYQAAAAARIFNuQAAAABEgU3uQy178USBTiNDb4JRRIFOWEOhvR5EgU6NQ7dIFESBTsNDkg3MRIFO+ELaUAREgU8tAAAAAESBT2IAAAAARIFPlwAAAABEgU/MAAAAAESBpzIAAAAARIGnZwAAAABEgaecAAAAAESBp9IAAAAARIGoB0Jew0REgag9QzrtF0SBqHJDhC78RIGop0NtEDlEgajdQy4kQ0SBqRIAAAAARIGpSAAAAABEgal9AAAAAESBqbMAAAAARIHnXgAAAABEgeeUAAAAAESB58kAAAAARIHn/wAAAABEgeg1QwZ+g0SB6GpDhNUoRIHooEOId6xEgejWQvQoEkSB6QsAAAAARIHpQQAAAABEgel2AAAAAESB6awAAAAARIIHpwAAAABEggfdAAAAAESCCBMAAAAARIIISAAAAABEggh+Qv4nckSCCLRDWj6rRIII6kNbO+tEggkfQwvuw0SCCVUAAAAARIIJiwAAAABEggnBAAAAAESCCfYAAAAARIInlQAAAABEgifLAAAAAESCKAAAAAAARIIoNgAAAABEgihsQpgZsESCKKJDTqwDRIIo2ENlUilEgikOQwzsVUSCKUMAAAAARIIpeQAAAABEgimvAAAAAESCKeUAAAAARIJjZgAAAABEgmOcAAAAAESCY9IAAAAARIJkCAAAAABEgmQ+QxAFj0SCZHRDUubtRIJkq0NEJytEgmThQrRT7ESCZRcAAAAARIJlTQAAAABEgmWDAAAAAESCZbkAAAAARILgJgAAAABEguBcAAAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAAABEguZQQwBjuUSC5odDV6cNRILmvUM6wtdEgub0QqvdxESC5yoAAAAARILnYQAAAABEgueXAAAAAESC580AAAAARIQHrQAAAABEhAflAAAAAESECBwAAAAARIQIVAAAAABEhAiLQ6u3TESECMJDwF2mRIQI+kO6QMBEhAkxQ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En8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

How to make correct date format when writing data to Excel

Try this solution, in my softwarew work very well:

if (obj != null)
{
    if (obj is DateTime)
    {
        if (DateTime.MinValue == ((DateTime)obj))
        {

            xlWorkSheet.Cells[x,y] = String.Empty;

        }
        else
        {

            dynamic opp = ((DateTime)obj);
            xlWorkSheet.Cells[x,y] = (DateTime)opp;

        }
    }
}

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

Abstract variables in Java?

No, Java doesn't support abstract variables. It doesn't really make a lot of sense, either.

What specific change to the "implementation" of a variable to you expect a sub class to do?

When I have a abstract String variable in the base class, what should the sub class do to make it non-abstract?

Mocking Extension Methods with Moq

You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach. Here is the description of the tool:

Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.

Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

You can use Moles with any testing framework (it's independent about that).

Hibernate: How to set NULL query-parameter value with HQL?

I did not try this, but what happens when you use :status twice to check for NULL?

Query query = getSession().createQuery(
     "from CountryDTO c where ( c.status = :status OR ( c.status IS NULL AND :status IS NULL ) ) and c.type =:type"
)
.setParameter("status", status, Hibernate.STRING)
.setParameter("type", type, Hibernate.STRING);

Multiple submit buttons on HTML form – designate one button as default

The first button is always the default; it can't be changed. Whilst you can try to fix it up with JavaScript, the form will behave unexpectedly in a browser without scripting, and there are some usability/accessibility corner cases to think about. For example, the code linked to by Zoran will accidentally submit the form on Enter press in a <input type="button">, which wouldn't normally happen, and won't catch IE's behaviour of submitting the form for Enter press on other non-field content in the form. So if you click on some text in a <p> in the form with that script and press Enter, the wrong button will be submitted... especially dangerous if, as given in that example, the real default button is ‘Delete’!

My advice would be to forget about using scripting hacks to reassign defaultness. Go with the flow of the browser and just put the default button first. If you can't hack the layout to give you the on-screen order you want, then you can do it by having a dummy invisible button first in the source, with the same name/value as the button you want to be default:

<input type="submit" class="defaultsink" name="COMMAND" value="Save" />

.defaultsink {
    position: absolute; left: -100%;
}

(note: positioning is used to push the button off-screen because display: none and visibility: hidden have browser-variable side-effects on whether the button is taken as default and whether it's submitted.)

Java error: Only a type can be imported. XYZ resolves to a package

I got it resolved by adding the jars in tomcat lib directory.

How do I get the Session Object in Spring?

If all that you need is details of User, for Spring Version 4.x you can use @AuthenticationPrincipal and @EnableWebSecurity tag provided by Spring as shown below.

Security Configuration Class:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   ...
}

Controller method:

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal User user) {
    ...
}

C# Error "The type initializer for ... threw an exception

I got this error when trying to log to an NLog target that no longer existed.

WCF ServiceHost access rights

If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"

How to simplify a null-safe compareTo() implementation?

I always recommend using Apache commons since it will most likely be better than one you can write on your own. Plus you can then do 'real' work rather then reinventing.

The class you are interested in is the Null Comparator. It allows you to make nulls high or low. You also give it your own comparator to use when the two values are not null.

In your case you can have a static member variable that does the comparison and then your compareTo method just references that.

Somthing like

class Metadata implements Comparable<Metadata> {
private String name;
private String value;

static NullComparator nullAndCaseInsensitveComparator = new NullComparator(
        new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // inputs can't be null
                return o1.compareToIgnoreCase(o2);
            }

        });

@Override
public int compareTo(Metadata other) {
    if (other == null) {
        return 1;
    }
    int res = nullAndCaseInsensitveComparator.compare(name, other.name);
    if (res != 0)
        return res;

    return nullAndCaseInsensitveComparator.compare(value, other.value);
}

}

Even if you decide to roll your own, keep this class in mind since it is very useful when ordering lists thatcontain null elements.

Bat file to run a .exe at the command prompt

You can use:

start "windowTitle" fullPath/file.exe

Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:

start "" fullPath/file.exe

How do you run CMD.exe under the Local System Account?

I would recommend you work out the minimum permission set that your service really needs and use that, rather than the far too privileged Local System context. For example, Local Service.

Interactive services no longer work - or at least, no longer show UI - on Windows Vista and Windows Server 2008 due to session 0 isolation.

Unzip files programmatically in .net

You can do it all within .NET 3.5 using DeflateStream. The thing lacking in .NET 3.5 is the ability to process the file header sections that are used to organize the zipped files. PKWare has published this information, which you can use to process the zip file after you create the structures that are used. It is not particularly onerous, and it a good practice in tool building without using 3rd party code.

It isn't a one line answer, but it is completely doable if you are willing and able to take the time yourself. I wrote a class to do this in a couple of hours and what I got from that is the ability to zip and unzip files using .NET 3.5 only.

How to convert an int to a hex string?

As an alternative representation you could use

[in] '%s' % hex(15)
[out]'0xf'

Accessing localhost of PC from USB connected Android mobile device

Connecting android phone via USB cable and accessing http server on the Computer.

  1. Firewall - switch it off, once everything works you can add a rule under Inbound rules, enable Apache HTTP Server (UDP and TCP) (or whatever HTTP server you're using) Warning - if you switch off the firewall, your computer becomes vulnerable to internet attacks. So switch off internet and disconnect from network first. You don't need to be on the Internet for this to work, as you're connecting two devices on local network.

  2. Plug in the USB cable. If networking window pops up, select Home Network. If it doesn't pop up it's probably set to Public (which won't work), so go to: Control Panel\Network and Internet\Network and Sharing Center (in win7) and set it to Home Network there. It might give you a next screen after you press it to share Pictures, Music... just click cancel on it. On the main screen Home Network will still be active.

  3. You need the Computer's IP, localhost or other aliases don't work. To get the IP of your machine, start the Windows command line shell (press Windows Key + R and type cmd), the black command prompt window should pop up, type: "ipconfig" and hit enter. Now look for

IPv4 Address. . . . . . . . . . . : 192.168.###.### That's the IP that your phone assigned to your computer

  1. Now you should be done, in the phone's browser, try accessing a test html file from your computer's server it should display fine.

  2. Now that everything is working you'll probably want to enable the firewall and Internet access on your computer. Now try accessing your http server again. It probably won't work. Depending on your setup you might get a popup asking you to add a rule to allow it, but if you don't, just add it yourself. Start the windows firewall and go to Inbound Rules (because it's a server) and add New Rule. Select "Program". Locate the exe of your http server, and in the next screen make sure Allow is selected. Try connecting again, and now it should work. If not it's probably because you selected wrong exe. You can even go more advanced to restrict outside usage (because now everyone on the internet can access it if they have your Internet IP address) To restrict access you can right-click on the new rule you've just created, click Properties, and go to Scope tab and change things there accordingly.

    Note for Android developers, now in your android code, you have to use "http://", otherwise it won't work. For example: MyAsyncTask.execute("http://192.168.123.123/test.html")

Part II -- Setting IP to fixed/static.

Now that things work, every time you unplug the cable and plug it back in, your IP will change. And if you are using it somewhere like inside a code, you'll have to update it every time! Solution I've come up with is to set the IP to static.

  1. Having the phone connected and tethered, go back to Network and Sharing Center and click on the Local Area connection "Connections:"

screenshot

  1. On the next screen select Properties, then highlight IP 4 and press properties there and click "Use the following IP address"
  2. Put Default Gateway and Subnet Mask exactly as it was in the ipconfig, and for the IP Address, only change the last 3 digits to anything from 1 to 255

screenshot

That IP will be your new fixed/static IP and it will remain the same next time you plug the phone.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

How to query values from xml nodes?

SELECT  b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);

Demo: SQLFiddle

Shell script : How to cut part of a string

Use a regular expression to catch the id number and replace the whole line with the number. Something like this should do it (match everything up to "id=", then match any number of digits, then match the rest of the line):

sed -e 's/.*id=\([0-9]\+\).*/\1/g'

Do this for every line and you get the list of ids.

Dynamic button click event handler

@Debasish Sahu, your answer is an answer to another question, namely: how to know which button (or any other control) was clicked when there is a common handler for a couple of controls? So I'm giving an answer to this question how I usually do it, almost the same as yours, but note that also works without type conversion when it handles the same type of Controls:

Private Sub btn_done_clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim selectedBtn As Button = sender
    MsgBox("you have clicked button " & selectedBtn.Name)
End Sub

How to fix corrupted git repository?

If you are desperate you can try this:

git clone ssh://[email protected]/path/to/project destination --depth=1

It will get your data, but you'll lose the history. I went with trial and error on my repo and --depth=10 worked, but --depth=50 gave me failure.

Optimal number of threads per core

4000 threads at one time is pretty high.

The answer is yes and no. If you are doing a lot of blocking I/O in each thread, then yes, you could show significant speedups doing up to probably 3 or 4 threads per logical core.

If you are not doing a lot of blocking things however, then the extra overhead with threading will just make it slower. So use a profiler and see where the bottlenecks are in each possibly parallel piece. If you are doing heavy computations, then more than 1 thread per CPU won't help. If you are doing a lot of memory transfer, it won't help either. If you are doing a lot of I/O though such as for disk access or internet access, then yes multiple threads will help up to a certain extent, or at the least make the application more responsive.

cannot load such file -- bundler/setup (LoadError)

i had the same issue and tried all the answers without any luck.

steps i did to reproduce:

  1. rvm instal 2.1.10
  2. rvm gemset create my_gemset
  3. rvm use 2.1.10@my_gemset
  4. bundle install

however bundle install installed Rails, but i still got cannot load such file -- bundler/setup (LoadError)

finally running gem install rails -v 4.2 fixed it

How to remove a variable from a PHP session array

Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.

$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry

Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.

<form blah blah blah method="post">
  <input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
  <input type="submit" name="add" value="Add />
</form>

And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Remove:

httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');

... and add:

httpRequest.withCredentials = false;

What is 0x10 in decimal?

0xNNNN (not necessarily four digits) represents, in C at least, a hexadecimal (base-16 because 'hex' is 6 and 'dec' is 10 in Latin-derived languages) number, where N is one of the digits 0 through 9 or A through F (or their lower case equivalents, either representing 10 through 15), and there may be 1 or more of those digits in the number. The other way of representing it is NNNN16.

It's very useful in the computer world as a single hex digit represents four bits (binary digits). That's because four bits, each with two possible values, gives you a total of 2 x 2 x 2 x 2 or 16 (24) values. In other words:

  _____________________________________bits____________________________________
 /                                                                             \
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| bF | bE | bD | bC | bB | bA | b9 | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
 \_________________/ \_________________/ \_________________/ \_________________/ 
      Hex digit           Hex digit           Hex digit           Hex digit

A base-X number is a number where each position represents a multiple of a power of X.


In base 10, which we humans are used to, the digits used are 0 through 9, and the number 730410 is:

  • (7 x 103) = 700010 ; plus
  • (3 x 102) = 30010 ; plus
  • (0 x 101) = 010 ; plus
  • (4 x 100) = 410 ; equals 7304.

In octal, where the digits are 0 through 7. the number 7548 is:

  • (7 x 82) = 44810 ; plus
  • (5 x 81) = 4010 ; plus
  • (4 x 80) = 410 ; equals 49210.

Octal numbers in C are preceded by the character 0 so 0123 is not 123 but is instead (1 * 64) + (2 * 8) + 3, or 83.


In binary, where the digits are 0 and 1. the number 10112 is:

  • (1 x 23) = 810 ; plus
  • (0 x 22) = 010 ; plus
  • (1 x 21) = 210 ; plus
  • (1 x 20) = 110 ; equals 1110.

In hexadecimal, where the digits are 0 through 9 and A through F (which represent the "digits" 10 through 15). the number 7F2416 is:

  • (7 x 163) = 2867210 ; plus
  • (F x 162) = 384010 ; plus
  • (2 x 161) = 3210 ; plus
  • (4 x 160) = 410 ; equals 3254810.

Your relatively simple number 0x10, which is the way C represents 1016, is simply:

  • (1 x 161) = 1610 ; plus
  • (0 x 160) = 010 ; equals 1610.

As an aside, the different bases of numbers are used for many things.

  • base 10 is used, as previously mentioned, by we humans with 10 digits on our hands.
  • base 2 is used by computers due to the relative ease of representing the two binary states with electrical circuits.
  • base 8 is used almost exclusively in UNIX file permissions so that each octal digit represents a 3-tuple of binary permissions (read/write/execute). It's also used in C-based languages and UNIX utilities to inject binary characters into an otherwise printable-character-only data stream.
  • base 16 is a convenient way to represent four bits to a digit, especially as most architectures nowadays have a word size which is a multiple of four bits.
  • base 64 is used in encoding mail so that binary files may be sent using only printable characters. Each digit represents six binary digits so you can pack three eight-bit characters into four six-bit digits (25% increased file size but guaranteed to get through the mail gateways untouched).
  • as a semi-useful snippet, base 60 comes from some very old civilisation (Babylon, Sumeria, Mesopotamia or something like that) and is the source of 60 seconds/minutes in the minute/hour, 360 degrees in a circle, 60 minutes (of arc) in a degree and so on [not really related to the computer industry, but interesting nonetheless].
  • as an even less-useful snippet, the ultimate question and answer in The Hitchhikers Guide To The Galaxy was "What do you get when you multiply 6 by 9?" and "42". Whilst same say this is because the Earth computer was faulty, others see it as proof that the creator has 13 fingers :-)

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

Round integers to the nearest 10

This function will round either be order of magnitude (right to left) or by digits the same way that format treats floating point decimal places (left to right:

def intround(n, p):
    ''' rounds an intger. if "p"<0, p is a exponent of 10; if p>0, left to right digits '''
    if p==0: return n
    if p>0:  
        ln=len(str(n))  
        p=p-ln+1 if n<0 else p-ln
    return (n + 5 * 10**(-p-1)) // 10**-p * 10**-p

>>> tgt=5555555
>>> d=2
>>> print('\t{} rounded to {} places:\n\t{} right to left \n\t{} left to right'.format(
        tgt,d,intround(tgt,-d), intround(tgt,d))) 

Prints

5555555 rounded to 2 places:
5555600 right to left 
5600000 left to right

You can also use Decimal class:

import decimal
import sys

def ri(i, prec=6):
    ic=long if sys.version_info.major<3 else int
    with decimal.localcontext() as lct:
        if prec>0:
            lct.prec=prec
        else:
            lct.prec=len(str(decimal.Decimal(i)))+prec  
        n=ic(decimal.Decimal(i)+decimal.Decimal('0'))
    return n

On Python 3 you can reliably use round with negative places and get a rounded integer:

def intround2(n, p):
    ''' will fail with larger floating point numbers on Py2 and require a cast to an int '''
    if p>0:
        return round(n, p-len(str(n))+1)
    else:
        return round(n, p)    

On Python 2, round will fail to return a proper rounder integer on larger numbers because round always returns a float:

>>> round(2**34, -5)
17179900000.0                     # OK
>>> round(2**64, -5)
1.84467440737096e+19              # wrong 

The other 2 functions work on Python 2 and 3

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

Run a PostgreSQL .sql file using command line arguments

You should do it like this:

\i path_to_sql_file

See:

Enter image description here

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

"unrecognized import path" with go get

I encountered this issue when installing a different package, and it could be caused by the GOROOT and GOPATH configuration on your PATH. I tend not to set GOROOT because my OS X installation handled it (I believe) for me.

  1. Ensure the following in your .profile (or wherever you store profile configuration: .bash_profile, .zshrc, .bashrc, etc):

    export GOPATH=$HOME/go
    export PATH=$PATH:$GOROOT/bin
    
  2. Also, you likely want to unset GOROOT, as well, in case that path is also incorrect.

  3. Furthermore, be sure to clean your PATH, similarly to what I've done below, just before the GOPATH assignment, i.e.:

    export PATH=$HOME/bin:/usr/local/bin:$PATH
    export GOPATH=$HOME/go
    export PATH=$PATH:$GOROOT/bin
    
  4. Then, source <.profile> to activate

  5. retry go get

AttributeError: 'str' object has no attribute 'append'

This is simple program showing append('t') to the list.
n=['f','g','h','i','k']

for i in range(1):
    temp=[]
    temp.append(n[-2:])
    temp.append('t')
    print(temp)

Output: [['i', 'k'], 't']

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

How to select option in drop down using Capybara

If you take a look at the source of the select method, you can see that what it does when you pass a from key is essentially:

find(:select, from, options).find(:option, value, options).select_option

In other words, it finds the <select> you're interested in, then finds the <option> within that, then calls select_option on the <option> node.

You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option method on the end:

find('#organizationSelect').find(:xpath, 'option[2]').select_option

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

How to access the elements of a 2D array?

If you want do many calculation with 2d array, you should use NumPy array instead of nest list.

for your question, you can use:zip(*a) to transpose it:

In [55]: a=[[1,1],[2,1],[3,1]]
In [56]: zip(*a)
Out[56]: [(1, 2, 3), (1, 1, 1)]
In [57]: zip(*a)[0]
Out[57]: (1, 2, 3)

How to check if a socket is connected/disconnected in C#?

Following the advice from NibblyPig and zendar, I came up with the code below, which works on every test I made. I ended up needing both the ping, and the poll. The ping will let me know if the cable has been disconnected, or the physical layer otherwise disrupted (router powered off, etc). But sometimes after reconnect I get a RST, the ping is ok, but the tcp state is not.

#region CHECKS THE SOCKET'S HEALTH
    if (_tcpClient.Client.Connected)
    {
            //Do a ping test to see if the server is reachable
            try
            {
                Ping pingTest = new Ping()
                PingReply reply = pingTest.Send(ServeripAddress);
                if (reply.Status != IPStatus.Success) ConnectionState = false;
            } catch (PingException) { ConnectionState = false; }

            //See if the tcp state is ok
            if (_tcpClient.Client.Poll(5000, SelectMode.SelectRead) && (_tcpClient.Client.Available == 0))
            {
                ConnectionState = false;
            }
        }
    }
    else { ConnectionState = false; }
#endregion

Disabling Controls in Bootstrap

try

$('#xxx').attr('disabled', true);

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.

If you are using Eclipse: How to add dependent libraries in Eclipse

If you are using command line include the path to the driver jar using the -cp parameter of java.

java -cp C:\lib\* Main

Floating point vs integer calculations on modern hardware

For example (lesser numbers are faster),

64-bit Intel Xeon X5550 @ 2.67GHz, gcc 4.1.2 -O3

short add/sub: 1.005460 [0]
short mul/div: 3.926543 [0]
long add/sub: 0.000000 [0]
long mul/div: 7.378581 [0]
long long add/sub: 0.000000 [0]
long long mul/div: 7.378593 [0]
float add/sub: 0.993583 [0]
float mul/div: 1.821565 [0]
double add/sub: 0.993884 [0]
double mul/div: 1.988664 [0]

32-bit Dual Core AMD Opteron(tm) Processor 265 @ 1.81GHz, gcc 3.4.6 -O3

short add/sub: 0.553863 [0]
short mul/div: 12.509163 [0]
long add/sub: 0.556912 [0]
long mul/div: 12.748019 [0]
long long add/sub: 5.298999 [0]
long long mul/div: 20.461186 [0]
float add/sub: 2.688253 [0]
float mul/div: 4.683886 [0]
double add/sub: 2.700834 [0]
double mul/div: 4.646755 [0]

As Dan pointed out, even once you normalize for clock frequency (which can be misleading in itself in pipelined designs), results will vary wildly based on CPU architecture (individual ALU/FPU performance, as well as actual number of ALUs/FPUs available per core in superscalar designs which influences how many independent operations can execute in parallel -- the latter factor is not exercised by the code below as all operations below are sequentially dependent.)

Poor man's FPU/ALU operation benchmark:

#include <stdio.h>
#ifdef _WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif
#include <time.h>
#include <cstdlib>

double
mygettime(void) {
# ifdef _WIN32
  struct _timeb tb;
  _ftime(&tb);
  return (double)tb.time + (0.001 * (double)tb.millitm);
# else
  struct timeval tv;
  if(gettimeofday(&tv, 0) < 0) {
    perror("oops");
  }
  return (double)tv.tv_sec + (0.000001 * (double)tv.tv_usec);
# endif
}

template< typename Type >
void my_test(const char* name) {
  Type v  = 0;
  // Do not use constants or repeating values
  //  to avoid loop unroll optimizations.
  // All values >0 to avoid division by 0
  // Perform ten ops/iteration to reduce
  //  impact of ++i below on measurements
  Type v0 = (Type)(rand() % 256)/16 + 1;
  Type v1 = (Type)(rand() % 256)/16 + 1;
  Type v2 = (Type)(rand() % 256)/16 + 1;
  Type v3 = (Type)(rand() % 256)/16 + 1;
  Type v4 = (Type)(rand() % 256)/16 + 1;
  Type v5 = (Type)(rand() % 256)/16 + 1;
  Type v6 = (Type)(rand() % 256)/16 + 1;
  Type v7 = (Type)(rand() % 256)/16 + 1;
  Type v8 = (Type)(rand() % 256)/16 + 1;
  Type v9 = (Type)(rand() % 256)/16 + 1;

  double t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v += v0;
    v -= v1;
    v += v2;
    v -= v3;
    v += v4;
    v -= v5;
    v += v6;
    v -= v7;
    v += v8;
    v -= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s add/sub: %f [%d]\n", name, mygettime() - t1, (int)v&1);
  t1 = mygettime();
  for (size_t i = 0; i < 100000000; ++i) {
    v /= v0;
    v *= v1;
    v /= v2;
    v *= v3;
    v /= v4;
    v *= v5;
    v /= v6;
    v *= v7;
    v /= v8;
    v *= v9;
  }
  // Pretend we make use of v so compiler doesn't optimize out
  //  the loop completely
  printf("%s mul/div: %f [%d]\n", name, mygettime() - t1, (int)v&1);
}

int main() {
  my_test< short >("short");
  my_test< long >("long");
  my_test< long long >("long long");
  my_test< float >("float");
  my_test< double >("double");

  return 0;
}

MySQL - How to select data by string length

select * from table order by length(column);

Documentation on the length() function, as well as all the other string functions, is available here.

Get Absolute URL from Relative path (refactored method)

Here is my own version that handles many validations and relative pathing from user's current location option. Feel free to refactor from here :)

/// <summary>
/// Converts the provided app-relative path into an absolute Url containing 
/// the full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string GetAbsoluteUrl(string relativeUrl)
{
    //VALIDATE INPUT
    if (String.IsNullOrEmpty(relativeUrl))
        return String.Empty;
    //VALIDATE INPUT FOR ALREADY ABSOLUTE URL
    if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) 
    || relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
        return relativeUrl;
    //VALIDATE CONTEXT
    if (HttpContext.Current == null)
        return relativeUrl;
    //GET CONTEXT OF CURRENT USER
    HttpContext context = HttpContext.Current;
    //FIX ROOT PATH TO APP ROOT PATH
    if (relativeUrl.StartsWith("/"))
        relativeUrl = relativeUrl.Insert(0, "~");
    //GET RELATIVE PATH
    Page page = context.Handler as Page;
    if (page != null)
    {
        //USE PAGE IN CASE RELATIVE TO USER'S CURRENT LOCATION IS NEEDED
        relativeUrl = page.ResolveUrl(relativeUrl);
    }
    else //OTHERWISE ASSUME WE WANT ROOT PATH
   {
        //PREPARE TO USE IN VIRTUAL PATH UTILITY
        if (!relativeUrl.StartsWith("~/"))
            relativeUrl = relativeUrl.Insert(0, "~/");
        relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);
    }

    var url = context.Request.Url;
    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
    //BUILD AND RETURN ABSOLUTE URL
    return String.Format("{0}://{1}{2}{3}",
           url.Scheme, url.Host, port, relativeUrl);
}

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Usually the msb file not found problems are the result of an environment setting problem, but in your case I'm a little suspicious of the installation (I've never used the apt-get + configure method).

To check the sanity of the installation:

  • ORACLE_HOME should be set to a directory path one level above the bin directory where sqlplus executable is found.
  • There should some .msb files under $ORACLE_HOME/sqlplus/mesg
  • There should be hundreds (not sure of the number with XE) of .msb files under $ORACLE_HOME (try find $ORACLE_HOME -name "*.msb" -print to show them)
  • Your PATH should include $ORACLE_HOME/bin.
  • All files under ORACLE_HOME should be owned by user:oracle group:dba.

Array of Matrices in MATLAB

I was doing some volume rendering in octave (matlab clone) and building my 3D arrays (ie an array of 2d slices) using

buffer=zeros(1,512*512*512,"uint16");
vol=reshape(buffer,512,512,512);

Memory consumption seemed to be efficient. (can't say the same for the subsequent speed of computations :^)

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

iText - add content to existing PDF file

Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("E:/TextFieldForm.pdf"));
    document.open();

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;      

    // Code 2, add name TextField       
    table.addCell("Name"); 
    TextField nameField = new TextField(writer, 
        new Rectangle(0,0,200,10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);               
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 
        200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript(
        "var nameField = this.getField('nameField');" +
        "nameField.setAction('Keystroke'," +
        "'forceUpperCase()');" +
        "" +
        "function forceUpperCase(){" +
        "if(!event.willCommit)event.change = " +
        "event.change.toUpperCase();" +
        "}");


    // Code 3, add empty row
    table.addCell("");
    table.addCell("");


    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0,
         0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 
        30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript(
        "var ageField = this.getField('ageField');" +
        "ageField.setAction('Validate','checkAge()');" +
        "function checkAge(){" +
        "if(event.value < 12){" +
        "app.alert('Warning! Applicant\\'s age can not" +
        " be younger than 12.');" +
        "event.value = 12;" +
        "}}");      



    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, 
        new Rectangle(0, 0,200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 
        200, writer));
    table.addCell(cell);


    // check comment characters length javascript
    writer.addJavaScript(
        "var commentField = " +
        "this.getField('commentField');" +
        "commentField" +
        ".setAction('Keystroke','checkLength()');" +
        "function checkLength(){" +
        "if(!event.willCommit && " +
        "event.value.length > 100){" +
        "app.alert('Warning! Comment can not " +
        "be more than 100 characters.');" +
        "event.change = '';" +
        "}}");          

    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 6, add submit button    
    PushbuttonField submitBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15),"submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.
        setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.
        VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction
    .createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));

    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);



    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(
        PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn
    .setOptions(
        PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);        

    document.add(table);
    document.close();
}


class FieldCell implements PdfPCellEvent{

    PdfFormField formField;
    PdfWriter writer;
    int width;

    public FieldCell(PdfFormField formField, int width, 
        PdfWriter writer){
        this.formField = formField;
        this.width = width;
        this.writer = writer;
    }

    public void cellLayout(PdfPCell cell, Rectangle rect, 
        PdfContentByte[] canvas){
        try{
            // delete cell border
            PdfContentByte cb = canvas[PdfPTable
                .LINECANVAS];
            cb.reset();

            formField.setWidget(
                new Rectangle(rect.left(), 
                    rect.bottom(), 
                    rect.left()+width, 
                    rect.top()), 
                    PdfAnnotation
                    .HIGHLIGHT_NONE);

            writer.addAnnotation(formField);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

For me the following approach solved the issue (Python 3.5.2; mysqlclient 1.3.9):

  1. Dowload latest MySQL C Connector http://dev.mysql.com/downloads/connector/c/ (for me was Windows (x86, 64-bit), MSI Installer)
  2. Copy c:\Program Files\MySQL\MySQL Connector C 6.0.2\ directory to c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\
  3. Run pip install mysqlclient
  4. [optional] delete c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\

The issue here is only for x64 bit installation owners, since build script is trying to locate C connector includes in x86 program files directory.

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).


Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/

If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here


Update: See this SO post -- https://stackoverflow.com/a/9567402/413254

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

How do I get the day of week given a date?

If you're not solely reliant on the datetime module, calendar might be a better alternative. This, for example, will provide you with the day codes:

calendar.weekday(2017,12,22);

And this will give you the day itself:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

Or in the style of python, as a one liner:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

Javascript - remove an array item by value

If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.

Array.prototype.unset = function(value) {
    if(this.indexOf(value) != -1) { // Make sure the value exists
        this.splice(this.indexOf(value), 1);
    }   
}

tag_story.unset(56)

Arrays in unix shell?

An array can be loaded in twoways.

set -A TEST_ARRAY alpha beta gamma

or

X=0 # Initialize counter to zero.

-- Load the array with the strings alpha, beta, and gamma

for ELEMENT in alpha gamma beta
do
    TEST_ARRAY[$X]=$ELEMENT
    ((X = X + 1))
done

Also, I think below information may help:

The shell supports one-dimensional arrays. The maximum number of array elements is 1,024. When an array is defined, it is automatically dimensioned to 1,024 elements. A one-dimensional array contains a sequence of array elements, which are like the boxcars connected together on a train track.

In case you want to access the array:

echo ${MY_ARRAY[2] # Show the third array element
 gamma 


echo ${MY_ARRAY[*] # Show all array elements
-   alpha beta gamma


echo ${MY_ARRAY[@] # Show all array elements
 -  alpha beta gamma


echo ${#MY_ARRAY[*]} # Show the total number of array elements
-   3


echo ${#MY_ARRAY[@]} # Show the total number of array elements
-   3

echo ${MY_ARRAY} # Show array element 0 (the first element)
-  alpha

How to load image files with webpack file-loader

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

How to create PDF files in Python

I suggest pyPdf. It works really nice. I also wrote a blog post some while ago, you can find it here.

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.

What is the preferred Bash shebang?

You should use #!/usr/bin/env bash for portability: different *nixes put bash in different places, and using /usr/bin/env is a workaround to run the first bash found on the PATH. And sh is not bash.

IE and Edge fix for object-fit: cover;

Here is the only CSS solution to fix this. Use the below css.

.row-fluid {
  display: table;
}

.row-fluid .span6 {
  display: table-cell;
  vertical-align: top;
}

.vc_single_image-wrapper {
  position: relative;
}

.vc_single_image-wrapper .image-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
}

HTML from the OP:

<div class="vc_single_image-wrapper   vc_box_border_grey">
  <div class="image-wrapper" style="background-image: url(http://i0.wp.com/www.homedecor.nl/wp-content/uploads/2016/03/Gordijnen-Home-Decor-2.jpg?fit=952%2C480;"></div>
</div>

try this, it should work. also remove float from .row-fluid .span6

If else in stored procedure sql server

If there are no matching row/s then @ParLngId will be NULL not zero, so you need IF @ParLngId IS NULL.

You should also use SCOPE_IDENTITY() rather than @@IDENTITY.

How to detect if a stored procedure already exists

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[xxx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
CREATE PROCEDURE dbo.xxx

where xxx is the proc name

Set folder browser dialog start location

Found on dotnet-snippets.de

With reflection this works and sets the real RootFolder!

using System;
using System.Reflection;
using System.Windows.Forms;

namespace YourNamespace
{
    public class RootFolderBrowserDialog
    {

        #region Public Properties

        /// <summary>
        ///   The description of the dialog.
        /// </summary>
        public string Description { get; set; } = "Chose folder...";

        /// <summary>
        ///   The ROOT path!
        /// </summary>
        public string RootPath { get; set; } = "";

        /// <summary>
        ///   The SelectedPath. Here is no initialization possible.
        /// </summary>
        public string SelectedPath { get; private set; } = "";

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        ///   Shows the dialog...
        /// </summary>
        /// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
        public DialogResult ShowDialog()
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var folder = shellType.InvokeMember(
                             "BrowseForFolder", BindingFlags.InvokeMethod, null,
                             shell, new object[] { 0, Description, 0, RootPath, });
            if (folder is null)
            {
                return DialogResult.Cancel;
            }
            else
            {
                var folderSelf = folder.GetType().InvokeMember(
                                     "Self", BindingFlags.GetProperty, null,
                                     folder, null);
                SelectedPath = folderSelf.GetType().InvokeMember(
                                   "Path", BindingFlags.GetProperty, null,
                                   folderSelf, null) as string;
                // maybe ensure that SelectedPath is set
                return DialogResult.OK;
            }
        }

        #endregion Public Methods

    }
}

VBA error 1004 - select method of range class failed

You have to select the sheet before you can select the range.

I've simplified the example to isolate the problem. Try this:

Option Explicit


Sub RangeError()

    Dim sourceBook As Workbook
    Dim sourceSheet As Worksheet
    Dim sourceSheetSum As Worksheet

    Set sourceBook = ActiveWorkbook
    Set sourceSheet = sourceBook.Sheets("Sheet1")
    Set sourceSheetSum = sourceBook.Sheets("Sheet2")

    sourceSheetSum.Select

    sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

End Sub

Replace Sheet1 and Sheet2 with your sheet names.

IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

How to change facet labels?

I feel like I should add my answer to this because it took me quite long to make this work:

This answer is for you if:

  • you do not want to edit your original data
  • if you need expressions (bquote) in your labels and
  • if you want the flexibility of a separate labelling name-vector

I basically put the labels in a named vector so labels would not get confused or switched. The labeller expression could probably be simpler, but this at least works (improvements are very welcome). Note the ` (back quotes) to protect the facet-factor.

n <- 10
x <- seq(0, 300, length.out = n)

# I have my data in a "long" format
my_data <- data.frame(
  Type = as.factor(c(rep('dl/l', n), rep('alpha', n))),
  T = c(x, x),
  Value = c(x*0.1, sqrt(x))
)

# the label names as a named vector
type_names <- c(
  `nonsense` = "this is just here because it looks good",
  `dl/l` = Linear~Expansion~~Delta*L/L[Ref]~"="~"[%]", # bquote expression
  `alpha` = Linear~Expansion~Coefficient~~alpha~"="~"[1/K]"
  )


ggplot() + 
  geom_point(data = my_data, mapping = aes(T, Value)) + 
  facet_wrap(. ~ Type, scales="free_y", 
             labeller = label_bquote(.(as.expression(
               eval(parse(text = paste0('type_names', '$`', Type, '`')))
               )))) +
  labs(x="Temperature [K]", y="", colour = "") +
  theme(legend.position = 'none')

enter image description here

Github: Can I see the number of downloads for a repo?

As mentioned, GitHub API returns downloads count of binary file releases. I developed a little script to easly get downloads count by command line.

POST string to ASP.NET Web Api application - returns null

You seem to have used some [Authorize] attribute on your Web API controller action and I don't see how this is relevant to your question.

So, let's get into practice. Here's a how a trivial Web API controller might look like:

public class TestController : ApiController
{
    public string Post([FromBody] string value)
    {
        return value;
    }
}

and a consumer for that matter:

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var data = "=Short test...";
            var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
            Console.WriteLine(result);
        }
    }
}

You will undoubtedly notice the [FromBody] decoration of the Web API controller attribute as well as the = prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.

As far as the [Authorize] attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post that I wrote on this topic interesting to get you started.

And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.

Open new popup window without address bars in firefox & IE

Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:

window.open('/pageaddress.html','winname',"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350");

Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

Determine whether a key is present in a dictionary

In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.

>>> dis.dis(indict)
  2           0 LOAD_GLOBAL              0 (name)
              3 LOAD_GLOBAL              1 (d)
              6 COMPARE_OP               6 (in)
              9 POP_TOP             


>>> dis.dis(haskey)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_ATTR                1 (haskey)
              6 LOAD_GLOBAL              2 (name)
              9 CALL_FUNCTION            1
             12 POP_TOP             

My feelings are that in is much more readable and is to be preferred in every case that I can think of.

In terms of performance, the timing reflects the opcode

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
 10000000 loops, best of 3: 0.11 usec per loop

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
  1000000 loops, best of 3: 0.205 usec per loop

in is almost twice as fast.

Determining the size of an Android view at runtime

I was also lost around getMeasuredWidth() and getMeasuredHeight() getHeight() and getWidth() for a long time.......... later i found that getting the view's width and height in onSizeChanged() is the best way to do this........ you can dynamically get your CURRENT width and CURRENT height of your view by overriding the onSizeChanged() method.

might wanna take a look at this which has an elaborate code snippet. New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

A generic solution like so

public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
        Function<Y, Z> function) {
    return input
            .entrySet()
            .stream()
            .collect(
                    Collectors.toMap((entry) -> entry.getKey(),
                            (entry) -> function.apply(entry.getValue())));
}

Example

Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<String, Integer> output = transform(input,
            (val) -> Integer.parseInt(val));

How to replace all spaces in a string

    $('#title').keyup(function () {
        var replaceSpace = $(this).val();

        var result = replaceSpace.replace(/\s/g, ";");

        $("#keyword").val(result);

    });

Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

How to go back last page

Another solution

window.history.back();

Why do we have to override the equals() method in Java?

Object.equals() method checks only reference of object not primitive data type or Object value (Wrapper class object of primitive data, simple primitive data type (byte, short, int, long etc.)). So that we must override equals() method when we compare object based on primitive data type.

Clear and refresh jQuery Chosen dropdown list

Using .trigger("chosen:updated"); you can update the options list after appending.

Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

Your code:

$("#refreshgallery").click(function(){
        $('#picturegallery').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#picturegallery').append(newOption);
        $('#picturegallery').trigger("chosen:updated");
    });

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

.NET unique object identifier

You would have to assign such an identifier yourself, manually - either inside the instance, or externally.

For records related to a database, the primary key may be useful (but you can still get duplicates). Alternatively, either use a Guid, or keep your own counter, allocating using Interlocked.Increment (and make it large enough that it isn't likely to overflow).

How to add a class to a given element?

find your target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space

you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

If you are in same network then add the destination server to the MS Server management studio using connect option and then try exporting from source to destination. The most easiest way :)

TSQL Pivot without aggregate function

SELECT
main.CustomerID,
f.Data AS FirstName,
m.Data AS MiddleName,
l.Data AS LastName,
d.Data AS Date
FROM table main
INNER JOIN table f on f.CustomerID = main.CustomerID
INNER JOIN table m on m.CustomerID = main.CustomerID
INNER JOIN table l on l.CustomerID = main.CustomerID
INNER JOIN table d on d.CustomerID = main.CustomerID
WHERE f.DBColumnName = 'FirstName' 
AND m.DBColumnName = 'MiddleName' 
AND l.DBColumnName = 'LastName' 
AND d.DBColumnName = 'Date' 

Edit: I have written this without an editor & have not run the SQL. I hope, you get the idea.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

This could also happen when your app doesn't actually compile, yet it's still launched in Tomcat. When I saw this happen, it wasn't compiling because the project had a "project specific" JDK specified, and the code was checked out on a machine that didn't have that specific JDK. Eclipse defaulted to a JRE instead, not a JDK, and then the app wasn't compiled.

To fix it in our specific case, we just turned off "Project Specific Settings" here:

"Project | Properties | Java Compiler"

Here's more detailed info on how to do this: https://stackoverflow.com/a/2540730/26510

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

How do I change the title of the "back" button on a Navigation Bar

For Swift:

    // Rename back button
    let backButton = UIBarButtonItem(
        title: "Back",
        style: UIBarButtonItemStyle.Plain, // Note: .Bordered is deprecated
        target: nil,
        action: nil
    )
    self.navigationController!.navigationBar.topItem!.backBarButtonItem = backButton

Enterprise app deployment doesn't work on iOS 7.1

Open up terminal and run the command: curl -i https:// (.ipa file path not plist)

This will tell you whether or not the installer can see the IPA file. If you run the curl command with the '-i' you'll see the full response and it's probably not the IPA file. This is the response the installer sees, so if it's not returning HTTP 200 and an IPA you'll need to return it on your end.

The ITMS installer doesn't save any context from Safari. If you authenticated into a secure portal in Safari, the authentication cookies aren't pass to the the installer. i.e. The installer needs to be able to see the app without authentication and this could be the reason you are getting 'Cannot connect to server'.

Android - Start service on boot

I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission 
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".UIBootReceiver" android:enabled="true" 
    android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
     <service android:name=".class_Service" />
</application>

UIBootReceiver

public class UIBootReceiver extends BroadcastReceiver {

private static final String TAG = "UIBootReceiver";
@Override

    public void onReceive(Context context, Intent arg1)
    {
        Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context,class_Service.class);
        context.startService(intent);
    }
  }

This is asking permission to not need to manage battery saving for this app so you can run in the background stably.

Declare this code in onCreate () of MainActivity class:

   Intent myIntent = new Intent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        myIntent.setData(Uri.parse("package:" + 
   DeviceMovingSpeed.this.getPackageName()));
    }
    startActivity(myIntent);

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

How to get only time from date-time C#

if you are using gridview then you can show only the time with DataFormatString="{0:t}" example:

    By bind the value:-
<asp:Label ID="lblreg" runat="server" Text='<%#Eval("Registration_Time ", "{0:t}") %>'></asp:Label>

By bound filed:-
<asp:BoundField DataField=" Registration_Time" HeaderText="Brithday" SortExpression=" Registration Time " DataFormatString="{0:t}"/>

List file using ls command in Linux with full path

The ls command will only print the name of the file in the directory. Why not do something like

print("/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/" + i)

This will print out the directory with the filename.

Redirect with CodeIgniter

If you want to redirect previous location or last request then you have to include user_agent library:

$this->load->library('user_agent');

and then use at last in a function that you are using:

redirect($this->agent->referrer());

its working for me.

Sending commands and strings to Terminal.app with Applescript

Kinda related, you might want to look at Shuttle (http://fitztrev.github.io/shuttle/), it's a SSH shortcut menu for OSX.

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

What are callee and caller saved registers?

I'm not really sure if this adds anything but,

Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).

Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.

The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax, ecx and edx are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx may be used to return a 64 bit value. I'm not sure why ecx is also caller saved if needed, but it is.

Regular expression to match characters at beginning of line only

(?i)^[ \r\n]*CTR

(?i) -- case insensitive -- Remove if case sensitive.
[ \r\n]  -- ignore space and new lines
* -- 0 or more times the same
CTR - your starts with string.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Have you tried?

var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

// "2013-10-10T22:10:00"
 dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); 

// "2013-10-10 22:10:00Z"    
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)

Also try using parameters when you store the c# datetime value in the mySql database, this might help.

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

Git - How to use .netrc file on Windows to save user and password

I am posting a way to use _netrc to download materials from the site www.course.com.

If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n instead of -U <username> -P <password> for convenience. He/she can do it like this:

  1. Check the home path on Windows OS: setx HOME %USERPROFILE%(refer to VonC's answer). It will save the HOME environment variable as C:\Users\"username".

  2. Locate into the directory C:\Users\"username" and create a file name _netrc.NOTE: there is NOT any suffix. the content is like: machine coursera-dl login <user> password <pass>

  3. Use a command like coursera-dl -n --path PATH <course name> to download the class materials. More coursera-dl options details for this page.

Spring 3 MVC accessing HttpRequest from controller

@RequestMapping(value="/") public String home(HttpServletRequest request){
    System.out.println("My Attribute :: "+request.getAttribute("YourAttributeName"));
    return "home"; 
}

Difference between Spring MVC and Struts MVC

Spring provides a very clean division between controllers, JavaBean models, and views.

iOS Launching Settings -> Restrictions URL Scheme

As of iOS10 you can use

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root")!) 

to open general settings.

also you can add known urls(you can see them in the most upvoted answer) to it to open specific settings. For example the below one opens touchID and passcode.

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=TOUCHID_PASSCODE")!)

Invalid argument supplied for foreach()

Use is_array function, when you will pass array to foreach loop.

if (is_array($your_variable)) {
  foreach ($your_variable as $item) {
   //your code
}
}

How are POST and GET variables handled in Python?

Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.

In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.

Get User Selected Range

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

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

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Is there an ignore command for git like there is for svn?

I hope it's not too late.

If you are on Windows you can just do the following to create a .gitignore file

echo name_of_the_file_you_want_to_ignore.extension > .gitignore

In order to edit .gitignore you can run

notepad .gitignore

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.

What is the difference between x86 and x64

x86 is for a 32-bit OS, and x64 is for a 64-bit OS

Pyinstaller setting icons don't change

The below command can set the icon on an executable file.

Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py

For example:

If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

Then the command should be as below. The final executable file will be generated inside the dist folder

pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

Include of non-modular header inside framework module

try @import FrameworkName instead of #import "FrameworkName.h"

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

Open a PDF using VBA in Excel

WOW... In appreciation, I add a bit of code that I use to find the path to ADOBE

Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
    (ByVal lpFile As String, _
     ByVal lpDirectory As String, _
     ByVal lpResult As String) As Long

and call this to find the applicable program name

Public Function GetFileAssociation(ByVal sFilepath As String) As String
Dim i               As Long
Dim E               As String
    GetFileAssociation = "File not found!"
    If Dir(sFilepath) = vbNullString Or sFilepath = vbNullString Then Exit Function
    GetFileAssociation = "No association found!"
    E = String(260, Chr(0))
    i = FindExecutable(sFilepath, vbNullString, E)
    If i > 32 Then GetFileAssociation = Left(E, InStr(E, Chr(0)) - 1)
End Function

Thank you for your code, which isn't EXACTLY what I wanted, but can be adapted for me.

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

how to prevent css inherit

If the inner object is inheriting properties you don't want, you can always set them to what you do want (ie - the properties are cascading, and so you can overwrite them at the lower level).

e.g.

.li-a {
    font-weight: bold;
    color: red;
}

.li-b {
    color: blue;
}

In this case, "li-b" will still be bold even though you don't want it to be. To make it not bold you can do:

.li-b {
    font-weight: normal;
    color: blue;
}

Xampp MySQL not starting - "Attempting to start MySQL service..."

I have the same problem. Finally found the solution:

The Relocate XAMPP option in the setup tool didn't correctly relocate the paths and corrupted them, but I've manually change the directories inside my.ini (base dir, data dir , ...). After that mysql started successfully.

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

How do I print to the debug output window in a Win32 app?

Consider using the VC++ runtime Macros for Reporting _RPTN() and _RPTFN()

You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.

Example...

if (someVar > MAX_SOMEVAR) {
    _RPTF2(_CRT_WARN, "In NameOfThisFunc( )," 
         " someVar= %d, otherVar= %d\n", someVar, otherVar );
}

Or you can use the VC++ runtime functions _CrtDbgReport, _CrtDbgReportW directly.

_CrtDbgReport and _CrtDbgReportW can send the debug report to three different destinations: a debug report file, a debug monitor (the Visual Studio debugger), or a debug message window.

_CrtDbgReport and _CrtDbgReportW create the user message for the debug report by substituting the argument[n] arguments into the format string, using the same rules defined by the printf or wprintf functions. These functions then generate the debug report and determine the destination or destinations, based on the current report modes and file defined for reportType. When the report is sent to a debug message window, the filename, lineNumber, and moduleName are included in the information displayed in the window.

git clone: Authentication failed for <URL>

I had the same issue when Cloning the repository via Bash/VS Code with "fatal:Authentication failed". I used SSH Key authentication instead to connect my repository following the article: [https://docs.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops&tabs=current-page][1] I didn't get any errors after with any bash commands!

rotating axis labels in R

Use par(las=1).

See ?par:

las
numeric in {0,1,2,3}; the style of axis labels.
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.

Using NOT operator in IF conditions

In general, ! is a perfectly good and readable boolean logic operator. No reason not to use it unless you're simplifying by removing double negatives or applying Morgan's law.

!(!A) = A

or

!(!A | !B) = A & B

As a rule of thumb, keep the signature of your boolean return methods mnemonic and in line with convention. The problem with the scenario that @hvgotcodes proposes is that of course a.b and c.d.e are not very friendly examples to begin with. Suppose you have a Flight and a Seat class for a flight booking application. Then the condition for booking a flight could perfectly be something like

if(flight.isActive() && !seat.isTaken())
{
    //book the seat
}

This perfectly readable and understandable code. You could re-define your boolean logic for the Seat class and rephrase the condition to this, though.

if(flight.isActive() && seat.isVacant())
{
    //book the seat
}

Thus removing the ! operator if it really bothers you, but you'll see that it all depends on what your boolean methods mean.

How to detect when an @Input() value changes in Angular?

Actually, there are two ways of detecting and acting upon when an input changes in the child component in angular2+ :

  1. You can use the ngOnChanges() lifecycle method as also mentioned in older answers:
    @Input() categoryId: string;
        
    ngOnChanges(changes: SimpleChanges) {
        
        this.doSomething(changes.categoryId.currentValue);
        // You can also use categoryId.previousValue and 
        // categoryId.firstChange for comparing old and new values
        
    }
    

Documentation Links: ngOnChanges, SimpleChanges, SimpleChange
Demo Example: Look at this plunker

  1. Alternately, you can also use an input property setter as follows:
    private _categoryId: string;
    
    @Input() set categoryId(value: string) {
    
       this._categoryId = value;
       this.doSomething(this._categoryId);
    
    }
    
    get categoryId(): string {
    
        return this._categoryId;
    
    }

Documentation Link: Look here.

Demo Example: Look at this plunker.

WHICH APPROACH SHOULD YOU USE?

If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.

However, if you want to do something when only a particular single input changes (and you don't care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).

EDIT 2017-07-25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES

Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, provided that the data is a JS primitive datatype(string, number, boolean). However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.

  1. If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look here.

  2. If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to this.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

Why does javascript map function return undefined?

You only return a value if the current element is a string. Perhaps assigning an empty string otherwise will suffice:

var arr = ['a','b',1];
var results = arr.map(function(item){
    return (typeof item ==='string') ? item : '';  
});

Of course, if you want to filter any non-string elements, you shouldn't use map(). Rather, you should look into using the filter() function.

DNS problem, nslookup works, ping doesn't

It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup wouldn't do that.

To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping command.


OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).

Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

Convert an image to grayscale in HTML/CSS

support for native CSS filters in webkit has been added from the current version 19.0.1084.46

so -webkit-filter: grayscale(1) will work and which is easier than SVG approach for webkit...

What is the equivalent of "none" in django templates?

You can also use another built-in template default_if_none

{{ profile.user.first_name|default_if_none:"--" }}

how to create Socket connection in Android?

Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.

You have to create two application to test below code.

In both application's manifest file, add below permission

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

1st App code: Client Socket

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableRow
        android:id="@+id/tr_send_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="11dp">

        <EditText
            android:id="@+id/edt_send_message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:hint="Enter message"
            android:inputType="text" />

        <Button
            android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Send" />
    </TableRow>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tr_send_message"
        android:layout_marginTop="25dp"
        android:id="@+id/scrollView2">

        <TextView
            android:id="@+id/tv_reply_from_server"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>
</RelativeLayout>

MainActivity.java

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Girish Bhalerao on 5/4/2017.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mTextViewReplyFromServer;
    private EditText mEditTextSendMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonSend = (Button) findViewById(R.id.btn_send);

        mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
        mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);

        buttonSend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_send:
                sendMessage(mEditTextSendMessage.getText().toString());
                break;
        }
    }

    private void sendMessage(final String msg) {

        final Handler handler = new Handler();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    //Replace below IP with the IP of that device in which server socket open.
                    //If you change port then change the port number in the server side code also.
                    Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);

                    OutputStream out = s.getOutputStream();

                    PrintWriter output = new PrintWriter(out);

                    output.println(msg);
                    output.flush();
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    final String st = input.readLine();

                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            String s = mTextViewReplyFromServer.getText().toString();
                            if (st.trim().length() != 0)
                                mTextViewReplyFromServer.setText(s + "\nFrom Server : " + st);
                        }
                    });

                    output.close();
                    out.close();
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }
}

2nd App Code - Server Socket

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_stop_receiving"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="STOP Receiving data"
        android:layout_alignParentTop="true"
        android:enabled="false"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btn_stop_receiving"
        android:layout_marginTop="35dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:id="@+id/tv_data_from_client"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:id="@+id/btn_start_receiving"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="START Receiving data"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp" />
</RelativeLayout>

MainActivity.java

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Girish Bhalerao on 5/4/2017.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    final Handler handler = new Handler();

    private Button buttonStartReceiving;
    private Button buttonStopReceiving;
    private TextView textViewDataFromClient;
    private boolean end = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
        buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
        textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);

        buttonStartReceiving.setOnClickListener(this);
        buttonStopReceiving.setOnClickListener(this);

    }

    private void startServerSocket() {

        Thread thread = new Thread(new Runnable() {

            private String stringData = null;

            @Override
            public void run() {

                try {

                    ServerSocket ss = new ServerSocket(9002);

                    while (!end) {
                        //Server is waiting for client here, if needed
                        Socket s = ss.accept();
                        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        PrintWriter output = new PrintWriter(s.getOutputStream());

                        stringData = input.readLine();
                        output.println("FROM SERVER - " + stringData.toUpperCase());
                        output.flush();

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        updateUI(stringData);
                        if (stringData.equalsIgnoreCase("STOP")) {
                            end = true;
                            output.close();
                            s.close();
                            break;
                        }

                        output.close();
                        s.close();
                    }
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
        thread.start();
    }

    private void updateUI(final String stringData) {

        handler.post(new Runnable() {
            @Override
            public void run() {

                String s = textViewDataFromClient.getText().toString();
                if (stringData.trim().length() != 0)
                    textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_start_receiving:

                startServerSocket();
                buttonStartReceiving.setEnabled(false);
                buttonStopReceiving.setEnabled(true);
                break;

            case R.id.btn_stop_receiving:

                //stopping server socket logic you can add yourself
                buttonStartReceiving.setEnabled(true);
                buttonStopReceiving.setEnabled(false);
                break;
        }
    }
}

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

Combining border-top,border-right,border-left,border-bottom in CSS

I can relate to the problem, there should be a shorthand like...

border: 1px solid red top bottom left;

Of course that doesn't work! Kobi's answer gave me an idea. Let's say you want to do top, bottom and left, but not right. Instead of doing border-top: border-left: border-bottom: (three statements) you could do two like this, the zero cancels out the right side.

border: 1px dashed yellow;
border-width:1px 0 1px 1px;

Two statements instead of three, small improvement :-D

Filter array to have unique values

This is for es2015 and above as far as I know. There are 'cleaner' options with ES6 but this a great way to do it (with TypeScript).

let values: any[] = [];
const distinct = (value: any, index: any, self: any) => {
    return self.indexOf(value) === index;
};
values = values.filter(distinct);

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

image has a shape of (64,64,3).

Your input placeholder _x have a shape of (?, 64,64,3).

The problem is that you're feeding the placeholder with a value of a different shape.

You have to feed it with a value of (1, 64, 64, 3) = a batch of 1 image.

Just reshape your image value to a batch with size one.

image = array(img).reshape(1, 64,64,3)

P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel. You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)

How to replace a character from a String in SQL?

UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'

The transaction manager has disabled its support for remote/network transactions

I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.

The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction

The partner transaction manager has disabled its support for remote/network transactions*

Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.

EF model generated method based attempt:

db.SomeStoredProcedure();

ExecuteSqlCommand based attempt:

db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");

With:

var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);    
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";

connection.Open();
var result = cmd.ExecuteNonQuery();

That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.

I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.

The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.

How to read existing text files without defining path

You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.

So it could relate to the current directory (get it from Directory.GetCurrentDirectory()) or to the application executable path (eg. Application.ExecutablePath comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath() with one element of the Environment.SpecialFolder enumeration).

Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!

In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

WAMP 403 Forbidden message on Windows 7

I have tried all the stuff except clearing the mess in .htaccess file.

Go to www/ directory and make a copy of .htaccess file in another folder. Then clear all the lines in .htaccess original file. And add this line,

RewriteEngine On

Then restart the server. This has solved my problem and got access to all my localhost sites. Hope it would solve yours too.

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

Convert date field into text in Excel

You can use TEXT like this as part of a concatenation

=TEXT(A1,"dd-mmm-yy") & " other string"

enter image description here

What is the simplest SQL Query to find the second largest value?

Use this query.

SELECT MAX( colname ) 
FROM Tablename 
where colname < (
    SELECT MAX( colname ) 
    FROM Tablename)

Android Webview - Webpage should fit the device screen

I had video in html string, and width of web view was larger that screen width and this is working for me.

Add these lines to HTML string.

<head>
<meta name="viewport" content="width=device-width">
</head>

Result after adding above code to HTML string:

<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width">
</head>


</html>

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

i have tried upgrading node-gyp:

sudo npm install -g node-gyp

It worked for me.

I find the solution here, I hope it can help.

How can I get current location from user in iOS

The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.

Header

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

MainFile

In the init method

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

Callback function

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

iOS 6

In iOS 6 the delegate function was deprecated. The new delegate is

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

Therefore to get the new position use

[locations lastObject]

iOS 8

In iOS 8 the permission should be explicitly asked before starting to update location

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

You also have to add a string for the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys to the app's Info.plist. Otherwise calls to startUpdatingLocation will be ignored and your delegate will not receive any callback.

And at the end when you are done reading location call stopUpdating location at suitable place.

[locationManager stopUpdatingLocation];

Cannot overwrite model once compiled Mongoose

To Solve this check if the model exists before to do the creation:

if (!mongoose.models[entityDBName]) {
  return mongoose.model(entityDBName, entitySchema);
}
else {
  return mongoose.models[entityDBName];
}

How to normalize a NumPy array to within a certain range?

If the array contains both positive and negative data, I'd go with:

import numpy as np

a = np.random.rand(3,2)

# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)

# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)        

# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1

If the array contains nan, one solution could be to just remove them as:

def nan_ptp(a):
    return np.ptp(a[np.isfinite(a)])

b = (a - np.nanmin(a))/nan_ptp(a)

However, depending on the context you might want to treat nan differently. E.g. interpolate the value, replacing in with e.g. 0, or raise an error.

Finally, worth mentioning even if it's not OP's question, standardization:

e = (a - np.mean(a)) / np.std(a)

How to write text on a image in windows using python opencv2

Here's the code with parameter labels

def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
    if x is not None and y is not None:
        cv2.putText(
            frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)

For font name please see another answer in this thread.

Excerpt from answer by @Roeffus

This is indeed a bit of an annoying problem. For python 2.x.x you use:

cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:

cv2.FONT_HERSHEY_SIMPLEX

For more see this http://www.programcreek.com/python/example/83399/cv2.putText

jquery multiple checkboxes array

This way will let you add or remove values when you check or uncheck any checkbox named as options[]:

var checkedValues = [];
$("input[name='options[]']").change(function() {
    const intValue = parseInt($(this).val());
    if ($(this).is(':checked')) {
        checkedValues.push(value);
    } else {
        const index = checkedValues.indexOf(value);
        if (index > -1) {
           checkedValues.splice(index, 1);
        }
    }
 });

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports sorting by object key:

yourApp.filter('orderObjectBy', function () {
    return function (items, field, reverse) {
        // Build array
        var filtered = [];
        for (var key in items) {
            if (field === 'key')
                filtered.push(key);
            else
                filtered.push(items[key]);
        }
        // Sort array
        filtered.sort(function (a, b) {
            if (field === 'key')
                return (a > b ? 1 : -1);
            else
                return (a[field] > b[field] ? 1 : -1);
        });
        // Reverse array
        if (reverse)
            filtered.reverse();
        return filtered;
    };
});

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

What exactly is LLVM?

A good summary of LLVM is this:

enter image description here

At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.

At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

As per the docs:

You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).

So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false to your RoomDatabase, as follows.

@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
   //...
}

If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :). Basically you will get a .json file in your ../app/schemas/ folder. And it looks something like this:

{
  "formatVersion": 1,
  "database": {
    "version": 1,
    "identityHash": "53db508c5248423325bd5393a1c88c03",
    "entities": [
      {
        "tableName": "sms_table",
        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
        "fields": [
          {
            "fieldPath": "id",
            "columnName": "id",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "message",
            "columnName": "message",
            "affinity": "TEXT"
          },
          {
            "fieldPath": "date",
            "columnName": "date",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "clientId",
            "columnName": "client_id",
            "affinity": "INTEGER"
          }
        ],
        "primaryKey": {
          "columnNames": [
            "id"
          ],
          "autoGenerate": true
        },
        "indices": [],
        "foreignKeys": []
      }
    ],
    "setupQueries": [
      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
    ]
  }
}

If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.

MySQL, create a simple function

MySQL function example:

Open the mysql terminal:

el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>

Drop the function if it already exists

mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Create the function

mysql> create function hello(id INT)
    -> returns CHAR(50)
    -> return 'foobar';
Query OK, 0 rows affected (0.01 sec)

Create a simple table to test it out with

mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)

Insert three values into the table yar

mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

Select all the values from yar, run our function hello each time:

mysql> select id, hello(5) from yar;
+------+----------+
| id   | hello(5) |
+------+----------+
|    5 | foobar   |
|    7 | foobar   |
|    9 | foobar   |
+------+----------+
3 rows in set (0.01 sec)

Verbalize and internalize what just happened:

You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50) containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5) for each row returned by yar.

How do I create an abstract base class in JavaScript?

JavaScript Classes and Inheritance (ES6)

According to ES6, you can use JavaScript classes and inheritance to accomplish what you need.

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

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

First of all, we define our abstract class. This class can't be instantiated, but can be extended. We can also define functions that must be implemented in all classes that extends this one.

/**
 * Abstract Class Animal.
 *
 * @class Animal
 */
class Animal {

  constructor() {
    if (this.constructor == Animal) {
      throw new Error("Abstract classes can't be instantiated.");
    }
  }

  say() {
    throw new Error("Method 'say()' must be implemented.");
  }

  eat() {
    console.log("eating");
  }
}

After that, we can create our concrete Classes. These classes will inherit all functions and behaviour from abstract class.

/**
 * Dog.
 *
 * @class Dog
 * @extends {Animal}
 */
class Dog extends Animal {
  say() {
    console.log("bark");
  }
}

/**
 * Cat.
 *
 * @class Cat
 * @extends {Animal}
 */
class Cat extends Animal {
  say() {
    console.log("meow");
  }
}

/**
 * Horse.
 *
 * @class Horse
 * @extends {Animal}
 */
class Horse extends Animal {}

And the results...

// RESULTS

new Dog().eat(); // eating
new Cat().eat(); // eating
new Horse().eat(); // eating

new Dog().say(); // bark
new Cat().say(); // meow
new Horse().say(); // Error: Method say() must be implemented.

new Animal(); // Error: Abstract classes can't be instantiated.

Convert and format a Date in JSP

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Locale"%>

<html>
<head>
<title>Date Format</title>
</head>
<body>
<%
String stringDate = "Fri May 13 2011 19:59:09 GMT 0530";
Date stringDate1 = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH).parse(stringDate);
String stringDate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stringDate1);

out.println(stringDate2);
%>
</body>
</html>

How to define an optional field in protobuf 3

To expand on @cybersnoopy 's suggestion here

if you had a .proto file with a message like so:

message Request {
    oneof option {
        int64 option_value = 1;
    }
}

You can make use of the case options provided (java generated code):

So we can now write some code as follows:

Request.OptionCase optionCase = request.getOptionCase();
OptionCase optionNotSet = OPTION_NOT_SET;

if (optionNotSet.equals(optionCase)){
    // value not set
} else {
    // value set
}

Sending images using Http Post

I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.

Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.

You will need to add the following imports to your class.

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:

public void post(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for(int index=0; index < nameValuePairs.size(); index++) {
            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
                // If the key equals to "image", we use FileBody to transfer the data
                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, localContext);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I hope this helps you a bit in the right direction.

How do I debug Node.js applications?

If you are using the Atom IDE, you can install the node-debugger package.

Check if object exists in JavaScript

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.

As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.

Vuex - Computed property "name" was assigned to but it has no setter

It should be like this.

In your Component

computed: {
        ...mapGetters({
                nameFromStore: 'name'
            }),
        name: {
           get(){
             return this.nameFromStore
           },
           set(newName){
             return newName
           } 
        }
    }

In your store

export const store = new Vuex.Store({
         state:{
             name : "Stackoverflow"
         },
         getters: {
                 name: (state) => {
                     return state.name;
                 }
         }
}

How to replace all special character into a string using C#

Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):

string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,

You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]

How do I disable a href link in JavaScript?

Try this when you dont want user to redirect on click

<a href="javascript: void(0)">I am a useless link</a>

How to redirect from one URL to another URL?

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

Converting stream of int's to char's in java

If you want to simply convert int 5 to char '5': (Only for integers 0 - 9)

int i = 5;
char c = (char) ('0' + i); // c is now '5';

Force file download with php using header()

Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.

// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );

How to display div after click the button in Javascript?

HTML Code:

<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />

Javascript:

function showDiv() {
   document.getElementById('welcomeDiv').style.display = "block";
}

See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

SOLVED

  1. Just run CMD as an administrator.
  2. Make sure your using the correct truststore password

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

C# string reference type?

I believe your code is analogous to the following, and you should not have expected the value to have changed for the same reason it wouldn't here:

 public static void Main()
 {
     StringWrapper testVariable = new StringWrapper("before passing");
     Console.WriteLine(testVariable);
     TestI(testVariable);
     Console.WriteLine(testVariable);
 }

 public static void TestI(StringWrapper testParameter)
 {
     testParameter = new StringWrapper("after passing");

     // this will change the object that testParameter is pointing/referring
     // to but it doesn't change testVariable unless you use a reference
     // parameter as indicated in other answers
 }

How to select top n rows from a datatable/dataview in ASP.NET

You could modify the query. If you are using SQL Server at the back, you can use Select top n query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.

Error: Cannot find module html

I am assuming that test.html is a static file.To render static files use the static middleware like so.

app.use(express.static(path.join(__dirname, 'public')));

This tells express to look for static files in the public directory of the application.

Once you have specified this simply point your browser to the location of the file and it should display.

If however you want to render the views then you have to use the appropriate renderer for it.The list of renderes is defined in consolidate.Once you have decided which library to use just install it.I use mustache so here is a snippet of my config file

var engines = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

What this does is tell express to

  • look for files to render in views directory

  • Render the files using mustache

  • The extension of the file is .html(you can use .mustache too)

How to access a value defined in the application.properties file in Spring Boot

@Value Spring annotation is used for injecting values into fields in Spring-manged beans, and it can be applied to the field or constructor/method parameter level.

Examples

  1. String value from the annotation to the field
    @Value("string value identifire in property file")
    private String stringValue;
  1. We can also use the @Value annotation to inject a Map property.

    First, we'll need to define the property in the {key: ‘value' } form in our properties file:

   valuesMap={key1: '1', key2: '2', key3: '3'}

Not that the values in the Map must be in single quotes.

Now inject this value from the property file as a Map:

   @Value("#{${valuesMap}}")
   private Map<String, Integer> valuesMap;

To get the value of a specific key

   @Value("#{${valuesMap}.key1}")
   private Integer valuesMapKey1;
  1. We can also use the @Value annotation to inject a List property.
   @Value("#{'${listOfValues}'.split(',')}")
   private List<String> valuesList;

How to get evaluated attributes inside a custom directive

For the same solution I was looking for Angularjs directive with ng-Model.
Here is the code that resolve the problem.

    myApp.directive('zipcodeformatter', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(attrs.ngModel, function (v) {
                if (v) {
                    console.log('value changed, new value is: ' + v + ' ' + v.length);
                    if (v.length > 5) {
                        var newzip = v.replace("-", '');
                        var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
                        element.val(str);

                    } else {
                        element.val(v);
                    }

                }

            });

        }
    };
});


HTML DOM

<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">


My Result is:

92108-2223

C++ Redefinition Header Files (winsock2.h)

In VS 2015, the following will work:

#define _WINSOCKAPI_

While the following won't:

#define WIN32_LEAN_AND_MEAN

ImportError: No module named matplotlib.pyplot

First check the version of Python

For python2:

sudo apt-get install python-matplotlib

For python3:

sudo apt-get install python3-matplotlib

If you mismatch the Matplotlib installation and the Python version you will get the no-module-error because no module for that version exits.

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Convert a List<T> into an ObservableCollection<T>

ObervableCollection have constructor in which you can pass your list. Quoting MSDN:

 public ObservableCollection(
      List<T> list
 )

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Because switching to HTTPS can be painful or impossible depending on your architecture, I found a workaround solution: you can use the Google Maps Geolocation API. Although it has usage limits, it does the job. You will need an browser API key, so don't forget to limit it's usage to your page hostname.

I use it as a fallback method to the getCurrentPosition() method if it fails. It allows me to make it work until I switch to HTTPS.

Here's the JSFiddles:

  • HTTP: getCurrentPosition() will fail and fall back to the API
  • HTTPS: getCurrentPosition() will succeed

How do I fix 'ImportError: cannot import name IncompleteRead'?

This should work for you. Follow these simple steps.

First, let's remove the pip which is already installed so it won't cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.

Method-1

Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

or

Method-2

Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name get-pip.py .

Step: 3 use: cd to go to the same directory as your get-pip.py file

Step: 4 use: sudo python get-pip.py

It will install pip latest version.

or

Method-3

Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Make sure you have closed your MSAccess file before running the java program.

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

How do I configure Notepad++ to use spaces instead of tabs?

I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default] ? Replace by space:

NotePad++ Preferences

NotePad++ Tab Settings

ImportError: No module named PIL

if you use anaconda:

conda install pillow

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

How to insert spaces/tabs in text using HTML/CSS

This worked for me:

In my CSS I have:

tab0  { position:absolute;left:25px;  }
tab1  { position:absolute;left:50px;  }
tab2  { position:absolute;left:75px;  }
tab3  { position:absolute;left:100px; }
tab4  { position:absolute;left:125px; }
tab5  { position:absolute;left:150px; }
tab6  { position:absolute;left:175px; }
tab7  { position:absolute;left:200px; }
tab8  { position:absolute;left:225px; }
tab9  { position:absolute;left:250px; }
tab10 { position:absolute;left:275px; }

Then in the HTML I just use my tabs:

Dog Food <tab3> :$30
Milk <tab3> :$3
Pizza Kit <tab3> :$5
Mt Dew <tab3> :$1.75

Bootstrap Modal Backdrop Remaining

So if you don't want to remove fade or tinker with the dom objects, all you have to do is make sure you wait for the show to finish:

$('#load-modal').on('shown.bs.modal', function () {
    console.log('Shown Modal Backdrop');
    $('#load-modal').addClass('shown');
});

function HideLoader() {
    var loadmodalhidetimer = setInterval(function () {
        if ($('#load-modal').is('.shown')) {                
            $('#load-modal').removeClass('shown').modal('hide');
            clearInterval(loadmodalhidetimer);
            console.log('HideLoader');
        }
        else { //this is just for show.
            console.log('Waiting to Hide');
        }
    }, 200);
}

IMO Bootstrap should already be doing this. Well perhaps a little more, if there is a chance that you could be calling hide without having done show you may want to add a little on show.bs.modal add the class 'showing' and make sure that the timer checks that showing is intended before getting into the loop. Make sure you clear 'showing' at the point it's shown.

jQuery How do you get an image to fade in on load?

Like Sohne mentions, but I would add this:

$("img").hide();

$("img").bind("load", function () { $(this).fadeIn(); });

or:

$("img").bind("load", function () {
 $(this).css({opacity: 0, visibility: "visible"}).animate({opacity: 1}, "slow"); 
});

Perform commands over ssh with Python

Works Perfectly...

import paramiko
import time

ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')

time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")

def execute():
       stdin.write('xcommand SystemUnit Boot Action: Restart\n')
       print('success')

execute()

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

How to use .htaccess in WAMP Server?

RewriteEngine on
RewriteBase /basic_test/

RewriteRule ^index.php$ test.php

How to get dictionary values as a generic list

Another variant:

    List<MyType> items = new List<MyType>();
    items.AddRange(myDico.values);

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Difference between "git add -A" and "git add ."

Both git add . and git add -A will stage all new, modified and deleted files in the newer versions of Git.

The difference is that git add -A stages files in "higher, current and subdirectories" that belong to your working Git repository. But doing a git add . only stages files in the current directory and subdirectories following it (not the files lying outside, i.e., higher directories).

Here's an example:

/my-repo
  .git/
  subfolder/
    nested-file.txt
  rootfile.txt

If your current working directory is /my-repo, and you do rm rootfile.txt, then cd subfolder, followed by git add ., then it will not stage the deleted file. But doing git add -A will certainly stage this change no matter where you perform the command from.

How to get Real IP from Visitor?

This is the most common technique I've seen:

function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.

How to save traceback / sys.exc_info() values in a variable?

sys.exc_info() returns a tuple with three values (type, value, traceback).

  1. Here type gets the exception type of the Exception being handled
  2. value is the arguments that are being passed to constructor of exception class
  3. traceback contains the stack information like where the exception occurred etc.

For Example, In the following program

try:

    a = 1/0

except Exception,e:

    exc_tuple = sys.exc_info()

Now If we print the tuple the values will be this.

  1. exc_tuple[0] value will be "ZeroDivisionError"
  2. exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
  3. exc_tuple[2] value will be "trackback object at (some memory address)"

The above details can also be fetched by simply printing the exception in string format.

print str(e)

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

How to create User/Database in script for Docker Postgres

You can now put .sql files inside the init directory:

From the docs

If you would like to do additional initialization in an image derived from this one, add one or more *.sql or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

So copying your .sql file in will work.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

Came accross the same problem just now.

I have a class named HelloWorld, and I created a test class for it named HelloWorldTests, then I got the output Skipping JaCoCo execution due to missing execution data file.

I then tried to change my pom.xml to make it work, but the attempt failed.

Finally, I simply rename HelloWorldTests to HelloWorldTest, and it worked!

So I guess that, by default, jacoco only recognizes test class named like XxxTest, which indicates that it's the test class for Xxx. So simply rename your test classes to this format should work!

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Remove all subviews?

For ios6 using autolayout I had to add a little bit of code to remove the constraints too.

NSMutableArray * constraints_to_remove = [ @[] mutableCopy] ;
for( NSLayoutConstraint * constraint in tagview.constraints) {
    if( [tagview.subviews containsObject:constraint.firstItem] ||
       [tagview.subviews containsObject:constraint.secondItem] ) {
        [constraints_to_remove addObject:constraint];
    }
}
[tagview removeConstraints:constraints_to_remove];

[ [tagview subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

I'm sure theres a neater way to do this, but it worked for me. In my case I could not use a direct [tagview removeConstraints:tagview.constraints] as there were constraints set in XCode that were getting cleared.

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

Is it possible to put CSS @media rules inline?

You can use image-set()

<div style="
  background-image: url(icon1x.png);
  background-image: -webkit-image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);  
  background-image: image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);">