Programs & Examples On #Windows 2003 webserver

IIS: Idle Timeout vs Recycle

Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory

Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health

The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"

The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.

java: ArrayList - how can I check if an index exists?

Quick and dirty test for whether an index exists or not. in your implementation replace list With your list you are testing.

public boolean hasIndex(int index){
    if(index < list.size())
        return true;
    return false;
}

or for 2Dimensional ArrayLists...

public boolean hasRow(int row){
    if(row < _matrix.size())
        return true;
    return false;
}

application/x-www-form-urlencoded or multipart/form-data?

READ AT LEAST THE FIRST PARA HERE!

I know this is 3 years too late, but Matt's (accepted) answer is incomplete and will eventually get you into trouble. The key here is that, if you choose to use multipart/form-data, the boundary must not appear in the file data that the server eventually receives.

This is not a problem for application/x-www-form-urlencoded, because there is no boundary. x-www-form-urlencoded can also always handle binary data, by the simple expedient of turning one arbitrary byte into three 7BIT bytes. Inefficient, but it works (and note that the comment about not being able to send filenames as well as binary data is incorrect; you just send it as another key/value pair).

The problem with multipart/form-data is that the boundary separator must not be present in the file data (see RFC 2388; section 5.2 also includes a rather lame excuse for not having a proper aggregate MIME type that avoids this problem).

So, at first sight, multipart/form-data is of no value whatsoever in any file upload, binary or otherwise. If you don't choose your boundary correctly, then you will eventually have a problem, whether you're sending plain text or raw binary - the server will find a boundary in the wrong place, and your file will be truncated, or the POST will fail.

The key is to choose an encoding and a boundary such that your selected boundary characters cannot appear in the encoded output. One simple solution is to use base64 (do not use raw binary). In base64 3 arbitrary bytes are encoded into four 7-bit characters, where the output character set is [A-Za-z0-9+/=] (i.e. alphanumerics, '+', '/' or '='). = is a special case, and may only appear at the end of the encoded output, as a single = or a double ==. Now, choose your boundary as a 7-bit ASCII string which cannot appear in base64 output. Many choices you see on the net fail this test - the MDN forms docs, for example, use "blob" as a boundary when sending binary data - not good. However, something like "!blob!" will never appear in base64 output.

YYYY-MM-DD format date in shell script

In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).

As such:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal

In bash (<4.2):

# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date

How to force remounting on React components?

I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};

Some React Hooks in there

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Tab space instead of multiple non-breaking spaces ("nbsp")?

Well, if one needs a long whitespace in the beginning of one line only out of the whole paragraph, then this may be a solution:

<span style='display:inline-block;height:1em;width:4em;'>&nbsp;</span>

If that is too much to write or one needs such tabs in many places, then you can do this

<span class='tab'>&nbsp;</span>

Then include this into CSS:

span.tab {display:inline-block;height:1em;width:4em;}

What are the benefits of using C# vs F# or F# vs C#?

It's like asking what's the benefit of a hammer over a screwdriver. At an extremely high level, both do essentially the same thing, but at the implementation level it's important to select the optimal tool for what you're trying to accomplish. There are tasks that are difficult and time-consuming in c# but easy in f# - like trying to pound a nail with a screwdriver. You can do it, for sure - it's just not ideal.

Data manipulation is one example I can personally point to where f# really shines and c# can potentially be unwieldy. On the flip side, I'd say (generally speaking) complex stateful UI is easier in OO (c#) than functional (f#). (There would probably be some people who disagree with this since it's "cool" right now to "prove" how easy it is to do anything in F#, but I stand by it). There are countless others.

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

How to pass arguments from command line to gradle

As of Gradle 4.9 Application plugin understands --args option, so passing the arguments is as simple as:

build.gradle

plugins {
    id 'application'
}

mainClassName = "my.App"

src/main/java/my/App.java

public class App {
    public static void main(String[] args) {
        System.out.println(args);
    }
}

bash

./gradlew run --args='This string will be passed into my.App#main arguments'

or in Windows, use double quotes:

gradlew run --args="This string will be passed into my.App#main arguments"

Catch paste input

OK, just bumped into the same issue.. I went around the long way

$('input').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});

Just a small timeout till .val() func can get populated.

E.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

jQuery function to get all unique elements from an array?

function array_unique(array) {
    var unique = [];
    for ( var i = 0 ; i < array.length ; ++i ) {
        if ( unique.indexOf(array[i]) == -1 )
            unique.push(array[i]);
    }
    return unique;
}

Java stack overflow error - how to increase the stack size in Eclipse?

i also have the same problem while parsing schema definition files(XSD) using XSOM library,

i was able to increase Stack memory upto 208Mb then it showed heap_out_of_memory_error for which i was able to increase only upto 320mb.

the final configuration was -Xmx320m -Xss208m but then again it ran for some time and failed.

My function prints recursively the entire tree of the schema definition,amazingly the output file crossed 820Mb for a definition file of 4 Mb(Aixm library) which in turn uses 50 Mb of schema definition library(ISO gml).

with that I am convinced I have to avoid Recursion and then start iteration and some other way of representing the output, but I am having little trouble converting all that recursion to iteration.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

I have found this page

http://schemas.xmlsoap.org/wsdl/soap12/soap12WSDL.htm

which says that Soap 1.2 uses the new namespace http://schemas.xmlsoap.org/wsdl/soap12/

It is in the 'WSDL 1.1 Binding extension for SOAP 1.1'.

Angular2 dynamic change CSS property

Angular 6 + Alyle UI

With Alyle UI you can change the styles dynamically

Here a demo stackblitz

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AlyleUIModule.forRoot(
      {
        name: 'myTheme',
        primary: {
          default: '#00bcd4'
        },
        accent: {
          default: '#ff4081'
        },
        scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
        lightGreen: '#8bc34a',
        colorSchemes: {
          light: {
            myColor: 'teal',
          },
          dark: {
            myColor: '#FF923D'
          },
          myCustomScheme: {
            background: {
              primary: '#dde4e6',
            },
            text: {
              default: '#fff'
            },
            myColor: '#C362FF'
          }
        }
      }
    ),
    LyCommonModule, // for bg, color, raised and others
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Html

<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>

For change Style

import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';

@Component({ ... })
export class AppComponent  {
  classes = {
    card: this.theme.setStyle(
      'card', // key
      () => (
        // style
        `background-color: ${this.theme.palette.myColor};` +
        `position: relative;` +
        `margin: 1em;` +
        `text-align: center;`
         ...
      )
    )
  }
  constructor(
    public theme: LyTheme
  ) { }

  changeScheme() {
    const scheme = this.theme.palette.scheme === 'light' ?
    'dark' : this.theme.palette.scheme === 'dark' ?
    'myCustomScheme' : 'light';
    this.theme.setScheme(scheme);
  }
}

Github Repository

How do you add an in-app purchase to an iOS application?

Just translate Jojodmo code to Swift:

class InAppPurchaseManager: NSObject , SKProductsRequestDelegate, SKPaymentTransactionObserver{





//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product

let kRemoveAdsProductIdentifier = "put your product id (the one that we just made in iTunesConnect) in here"

@IBAction func tapsRemoveAds() {

    NSLog("User requests to remove ads")

    if SKPaymentQueue.canMakePayments() {
        NSLog("User can make payments")

        //If you have more than one in-app purchase, and would like
        //to have the user purchase a different product, simply define
        //another function and replace kRemoveAdsProductIdentifier with
        //the identifier for the other product
        let set : Set<String> = [kRemoveAdsProductIdentifier]
        let productsRequest = SKProductsRequest(productIdentifiers: set)
        productsRequest.delegate = self
        productsRequest.start()

    }
    else {
        NSLog("User cannot make payments due to parental controls")
        //this is called the user cannot make payments, most likely due to parental controls
    }
}


func purchase(product : SKProduct) {

    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().addPayment(payment)
}

func restore() {
    //this is called when the user restores purchases, you should hook this up to a button
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}


func doRemoveAds() {
    //TODO: implement
}

/////////////////////////////////////////////////
//////////////// store delegate /////////////////
/////////////////////////////////////////////////
// MARK: - store delegate -


func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {

    if let validProduct = response.products.first {
        NSLog("Products Available!")
        self.purchase(validProduct)
    }
    else {
        NSLog("No products available")
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {


    NSLog("received restored transactions: \(queue.transactions.count)")
    for transaction in queue.transactions {
        if transaction.transactionState == .Restored {
            //called when the user successfully restores a purchase
            NSLog("Transaction state -> Restored")

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            self.doRemoveAds()
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            break;
        }
    }
}


func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {

    for transaction in transactions {
        switch transaction.transactionState {
        case .Purchasing: NSLog("Transaction state -> Purchasing")
            //called when the user is in the process of purchasing, do not add any of your own code here.
        case .Purchased:
            //this is called when the user has successfully purchased the package (Cha-Ching!)
            self.doRemoveAds() //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            NSLog("Transaction state -> Purchased")
        case .Restored:
            NSLog("Transaction state -> Restored")
            //add the same code as you did from SKPaymentTransactionStatePurchased here
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Failed:
            //called when the transaction does not finish
            if transaction.error?.code == SKErrorPaymentCancelled {
                NSLog("Transaction state -> Cancelled")
                //the user cancelled the payment ;(
            }
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Deferred:
            // The transaction is in the queue, but its final status is pending external action.
            NSLog("Transaction state -> Deferred")

        }


    }
}
} 

Get the week start date and week end date from week number

I just encounter a similar case with this one, but the solution here seems not helping me. So I try to figure it out by myself. I work out the week start date only, week end date should be of similar logic.

Select 
      Sum(NumberOfBrides) As [Wedding Count], 
      DATEPART( wk, WeddingDate) as [Week Number],
      DATEPART( year, WeddingDate) as [Year],
      DATEADD(DAY, 1 - DATEPART(WEEKDAY, dateadd(wk, DATEPART( wk, WeddingDate)-1,  DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))), dateadd(wk, DATEPART( wk, WeddingDate)-1, DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))) as [Week Start]

FROM  MemberWeddingDates
Group By DATEPART( year, WeddingDate), DATEPART( wk, WeddingDate)
Order By Sum(NumberOfBrides) Desc

How to set HTML5 required attribute in Javascript?

try out this..

document.getElementById("edName").required = true;

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

Iterating through array - java

You should definitely encapsulate this logic into a method.

There is no benefit to repeating identical code multiple times.

Also, if you place the logic in a method and it changes, you only need to modify your code in one place.

Whether or not you want to use a 3rd party library is an entirely different decision.

PyLint "Unable to import" error - how to set PYTHONPATH?

In case anybody is looking for a way to run pylint as an external tool in PyCharm and have it work with their virtual environments (why I came to this question), here's how I solved it:

  1. In PyCharm > Preferences > Tools > External Tools, Add or Edit an item for pylint.
  2. In the Tool Settings of the Edit Tool dialog, set Program to use pylint from the python interpreter directory: $PyInterpreterDirectory$/pylint
  3. Set your other parameters in the Parameters field, like: --rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
  4. Set your working directory to $FileDir$

Now using pylint as an external tool will run pylint on whatever directory you have selected using a common config file and use whatever interpreter is configured for your project (which presumably is your virtualenv interpreter).

How to plot a function curve in R

Lattice solution with additional settings which I needed:

library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
  1. If you need your range of values for x plotted in increments different from 1, e.g. 0.00001 you can use:

X<-seq(0,10,0.00001)

  1. You can change the colour of your line by defining a rgb value:

col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)

  1. You can change the width of the plotted line by setting:

lwd = 2

  1. You can change the size of the labels by scaling them:

cex.lab = 3.5, cex.axis = 3.5

Example plot

How can I turn a DataTable to a CSV?

A new extension function based on Paul Grimshaw's answer. I cleaned it up and added the ability to handle unexpected data. (Empty Data, Embedded Quotes, and comma's in the headings...)

It also returns a string which is more flexible. It returns Null if the table object does not contain any structure.

    public static string ToCsv(this DataTable dataTable) {
        StringBuilder sbData = new StringBuilder();

        // Only return Null if there is no structure.
        if (dataTable.Columns.Count == 0)
            return null;

        foreach (var col in dataTable.Columns) {
            if (col == null)
                sbData.Append(",");
            else
                sbData.Append("\"" + col.ToString().Replace("\"", "\"\"") + "\",");
        }

        sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) {
            foreach (var column in dr.ItemArray) {
                if (column == null)
                    sbData.Append(",");
                else
                    sbData.Append("\"" + column.ToString().Replace("\"", "\"\"") + "\",");
            }
            sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
        }

        return sbData.ToString();
    }

You call it as follows:

var csvData = dataTableOject.ToCsv();

How can I apply styles to multiple classes at once?

If you use as following, your code can be more effective than you wrote. You should add another feature.

.abc, .xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a.abc, a.xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a {
margin-left:20px;
width: 100px;
height: 100px;
} 

how to convert object into string in php

There is an object serialization module, with the serialize function you can serialize any object.

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

Does a favicon have to be 32x32 or 16x16?

Update for 2020: Sticking to the original question of 16x16 versus 32x32 icons: the current recommendation should be to provide a 32x32 icon, skipping 16x16 entirely. All current browsers and devices support 32x32 icons. The icon will routinely be upscaled to as much as 192x192 depending on the environment (assuming there are no larger sizes available or the system didn't recognize them). Upscaling from ultra low resolution has a noticeable effect so better stick to 32x32 as the smallest baseline.


For IE, Microsoft recommends 16x16, 32x32 and 48x48 packed in the favicon.ico file.

For iOS, Apple recommends specific file names and resolutions, at most 180x180 for latest devices running iOS 8.

Android Chrome primarily uses a manifest and also relies on the Apple touch icon.

IE 10 on Windows 8.0 requires PNG pictures and a background color and IE 11 on Windows 8.1 and 10 accepts several PNG pictures declared in a dedicated XML file called browserconfig.xml.

Safari for Mac OS X El Capitan introduces an SVG icon for pinned tabs.

Some other platforms look for PNG files with various resolutions, like the 96x96 picture for Google TV or the 228x228 picture for Opera Coast.

Look at this favicon pictures list for a complete reference.

TLDR: This favicon generator can generate all these files at once. The generator can also be implemented as a WordPress plugin. Full disclosure: I am the author of this site.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

Why isn't my Pandas 'apply' function referencing multiple columns working?

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

How do you beta test an iphone app?

Using testflight :

1) create the ipa file by development certificate

2) upload the ipa file on testflight

3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.

4) Now email the ipa file to the testers.

5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...

How to remove empty cells in UITableView?

override func viewWillAppear(animated: Bool) {
    self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

/// OR 

    self.tableView.tableFooterView = UIView()
}

Making a DateTime field in a database automatic?

You need to set the "default value" for the date field to getdate(). Any records inserted into the table will automatically have the insertion date as their value for this field.

The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

How to program a fractal?

Programming the Mandelbrot is easy.
My quick-n-dirty code is below (not guaranteed to be bug-free, but a good outline).

Here's the outline: The Mandelbrot-set lies in the Complex-grid completely within a circle with radius 2.

So, start by scanning every point in that rectangular area. Each point represents a Complex number (x + yi). Iterate that complex number:

[new value] = [old-value]^2 + [original-value] while keeping track of two things:

1.) the number of iterations

2.) the distance of [new-value] from the origin.

If you reach the Maximum number of iterations, you're done. If the distance from the origin is greater than 2, you're done.

When done, color the original pixel depending on the number of iterations you've done. Then move on to the next pixel.

public void MBrot()
{
    float epsilon = 0.0001; // The step size across the X and Y axis
    float x;
    float y;
    int maxIterations = 10; // increasing this will give you a more detailed fractal
    int maxColors = 256; // Change as appropriate for your display.

    Complex Z;
    Complex C;
    int iterations;
    for(x=-2; x<=2; x+= epsilon)
    {
        for(y=-2; y<=2; y+= epsilon)
        {
            iterations = 0;
            C = new Complex(x, y);
            Z = new Complex(0,0);
            while(Complex.Abs(Z) < 2 && iterations < maxIterations)
            {
                Z = Z*Z + C;
                iterations++;
            }
            Screen.Plot(x,y, iterations % maxColors); //depending on the number of iterations, color a pixel.
        }
    }
}

Some details left out are:

1.) Learn exactly what the Square of a Complex number is and how to calculate it.

2.) Figure out how to translate the (-2,2) rectangular region to screen coordinates.

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

How to merge remote changes at GitHub?

This problem can also occur when you have conflicting tags. If your local version and remote version use same tag name for different commits, you can end up here.

You can solve it my deleting the local tag:

$ git tag --delete foo_tag

How can I kill all sessions connecting to my oracle database?

As SYS:

startup force;

Brutal, yet elegant.

Java Web Service client basic authentication

Some context additional about basic authentication, it consists in a header which contains the key/value pair:

Authorization: Basic Z2VybWFuOmdlcm1hbg==

where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot

String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

Difference between dict.clear() and assigning {} in Python

d = {} will create a new instance for d but all other references will still point to the old contents. d.clear() will reset the contents, but all references to the same instance will still be correct.

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Google Chrome: This setting is enforced by your administrator

On Linux, you can get rid of "Managed by your organization" Chrome policies, by removing these directories (as sudo probably):

/etc/opt/chrome/policies
/etc/opt/chrome/policies/managed
/etc/opt/chrome/policies/recommended

Why is there no Constant feature in Java?

Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.

Wikipedia offers the following information on the subject:

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Should I use 'border: none' or 'border: 0'?

Using

border: none;

doesn't work in some versions of IE. IE9 is fine but in previous versions it displays the border even when the style is "none". I experienced this when using a print stylesheet where I didn't want borders on the input boxes.

border: 0;

seems to work fine in all browsers.

(WAMP/XAMP) send Mail using SMTP localhost

If any one of you are getting error like following after following answer given by Afwe Wef

 Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:

 550 The address is not valid. in c:\wamp\www\email.php

Go to php.ini

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]

Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .

your problem will be solved.

Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8

If you are also getting following error

"APPLICATION"   6364    "2014-03-24 13:13:33.979"   "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION"   6364    "2014-03-24 13:13:34.415"   "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION"   6364    "2014-03-24 13:13:34.430"   "SMTPDeliverer - Message 2: Message delivery thread completed."

You might have forgot to change the port from 25 to 465

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

How can I display the users profile pic using the facebook graph api?

I was having a problem fetching profile photos while using CURL. I thought for a while there was something wrong my implementation of the Facebook API, but I need to add a bit to my CURL called:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

How to find the array index with a value?

Use jQuery's function jQuery.inArray

jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )

No == operator found while comparing structs in C++

In C++, structs do not have a comparison operator generated by default. You need to write your own:

bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return /* your comparison code goes here */
}

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

Editing hosts file to redirect url?

Apply this trick.

First you need IP address of url you want to redirect to. Lets say you want to redirect to stackoverflow.com To find it, use the ping command in a Command Prompt. Type in:

ping stackoverflow.com

into the command prompt window and you’ll see stackoverflow's numerical IP address. Now use that IP into your host file

104.16.36.249 google.com

yay now google is serving stackoverflow :)

Button that refreshes the page on click

If you are looking for a form reset:

<input type="reset" value="Reset Form Values"/>

or to reset other aspects of the form not handled by the browser

<input type="reset" onclick="doFormReset();" value="Reset Form Values"/>

Using jQuery

function doFormReset(){
    $(".invalid").removeClass("invalid");
}

How can I connect to MySQL on a WAMP server?

Try opening Port 3306, and using that in the connection string not 8080.

Check if a property exists in a class

Your method looks like this:

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

This adds an extension onto object - the base class of everything. When you call this extension you're passing it a Type:

var res = typeof(MyClass).HasProperty("Label");

Your method expects an instance of a class, not a Type. Otherwise you're essentially doing

typeof(MyClass) - this gives an instanceof `System.Type`. 

Then

type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`

As @PeterRitchie correctly points out, at this point your code is looking for property Label on System.Type. That property does not exist.

The solution is either

a) Provide an instance of MyClass to the extension:

var myInstance = new MyClass()
myInstance.HasProperty("Label")

b) Put the extension on System.Type

public static bool HasProperty(this Type obj, string propertyName)
{
    return obj.GetProperty(propertyName) != null;
}

and

typeof(MyClass).HasProperty("Label");

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

Dynamically updating css in Angular 2

All the above answers are great. But if you were trying to find a solution that won't change the html files below is helpful

 ngAfterViewChecked(){
    this.renderer.setElementStyle(targetItem.nativeElement, 'height', textHeight+"px");
}

You can import renderer from import {Renderer} from '@angular/core';

android.os.NetworkOnMainThreadException with android 4.2

This is the correct way:

public class JSONParser extends AsyncTask <String, Void, String>{

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}
@Override
protected String doInBackground(String... params) {


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

        //HttpResponse httpResponse = httpClient.execute(httpPost);
        //HttpEntity httpEntity = httpResponse.getEntity();
        is = getResponseEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

To call it (from main):

mJSONParser = new JSONParser();
mJSONParser.execute();

Weird PHP error: 'Can't use function return value in write context'

I also had a similar problem like yours. The problem is that you are using an old php version. I have upgraded to PHP 5.6 and the problem no longer exist.

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

Can I use multiple versions of jQuery on the same page?

You can have as many different jQuery versions on your page as you want.

Use jQuery.noConflict():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
    var $i = jQuery.noConflict();
    alert($i.fn.jquery);
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    alert($j.fn.jquery);
</script> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var $k = jQuery.noConflict();
    alert($k.fn.jquery);
</script> 

DEMO | Source

Insert null/empty value in sql datetime column by default

Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()

-Just a side thought. seems you have things working.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

If you want the editor to work with git operations, setting the $EDITOR environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:

git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.

If you want Sublime to work correctly with git, you should configure it using:

git config --global core.editor "sublime -n -w"

I came here looking for this and found the solution in this gist on github.

git clone: Authentication failed for <URL>

I'm facing exactly same error when I'm trying to clone a repository on a brand new machine. I'm using Git bash as my Git client. When I ran Git's command to clone a repository it was not prompting me for user id and password which will be used for authentication. It was a fresh machine where not a single credential was cached by Windows credential manager.

As a last resort, I manually added my credentials in credentials manager.

Go to > Control Panel\User Accounts\Credential Manager > Windows Credentials

Click Add a Windows credential link and then Supply the details as shown in the form below and you're done:

enter image description here

I had put the details as below:

Internet or network address: <gitRepoServerNameOrIPAddress>
User Name: MyCompanysDomainName\MyUserName
Password: MyPassword

Next time you run any Git command targeting a repository set up on above address this manually created credential will be used.

It is also important if you have a git command line you close it and reopen it for changes to be applied.

What is Turing Complete?

In practical language terms familiar to most programmers, the usual way to detect Turing completeness is if the language allows or allows the simulation of nested unbounded while statements (as opposed to Pascal-style for statements, with fixed upper bounds).

Android ADB devices unauthorized

All you need is to authorize debug mode.
1. make sure your Device is connected to your PC.
2. Allow authorized for debug mode via Android-Studio by going to
Run -> Attach debugger to Android process
than you will see the pop up window for allow debug mode in your Device,
press OK. done.
i hope it help to someone.

best way to get the key of a key/value javascript object

The easiest way is to just use Underscore.js:

keys

_.keys(object) Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]

Yes, you need an extra library, but it's so easy!

Facebook OAuth "The domain of this URL isn't included in the app's domain"

I had the same problem,

I just added the link of my local adress http://localhost/Facebook%20Login%20Test.html to Site URL in my application setting https://developers.facebook.com/apps.

Now it works fine :) I hope this was useful ;)

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

Explaining Python's '__enter__' and '__exit__'

If you know what context managers are then you need nothing more to understand __enter__ and __exit__ magic methods. Lets see a very simple example.

In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.

fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
    for line in fp:
        print(line)
finally:
    fp.close()

Now I am opening same file with with statement:

with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
    for line in fp:
        print(line) 

If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed) attribute -- which returns True.

This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__ and __exit__. It is also known as context manager. __enter__ method is called at the start of with block and __exit__ method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__ and __exit__ methods. A class which implement both methods is known as context manager class.

Now lets define our own context manager class.

 class Log:
    def __init__(self,filename):
        self.filename=filename
        self.fp=None    
    def logging(self,text):
        self.fp.write(text+'\n')
    def __enter__(self):
        print("__enter__")
        self.fp=open(self.filename,"a+")
        return self    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.fp.close()

with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
    print("Main")
    logfile.logging("Test1")
    logfile.logging("Test2")

I hope now you have basic understanding of both __enter__ and __exit__ magic methods.

How to solve SyntaxError on autogenerated manage.py?

I had this issue (Mac) and followed the instructions on the below page to install and activate the virtual environment

https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

$ cd [ top-level-django-project-dir ]

$ python3 -m pip install --user virtualenv

$ python3 -m venv env

$ source env/bin/activate

Once I had installed and activated the virtual env I checked it

$ which python

Then I installed django into the virtual env

$ pip install django

And then I could run my app

$ python3 manage.py runserver

When I got to the next part of the tutorial

$ python manage.py startapp polls

I encountered another error:

     File "manage.py", line 16

   ) from exc
            ^

   SyntaxError: invalid syntax

I removed

from exc

and it then created the polls directory

React: "this" is undefined inside a component function

In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

From this (onClick doesn't have access to the equivalent of 'this')

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

To this (it works)

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()

  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])

  return targetRef
}

const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)

  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Two values from one input in python?

All input will be through a string. It's up to you to process that string after you've received it. Unless that is, you use the eval(input()) method, but that isn't recommended for most situations anyway.

input_string = raw_input("Enter 2 numbers here: ")
a, b = split_string_into_numbers(input_string)
do_stuff(a, b)

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

How to convert a string to number in TypeScript?

Here is a modified version of the StrToNumber function. As before,

  1. It allows an optional sign to appear in front or behind the numeric value.
  2. It performs a check to verify there is only one sign at the head or tail of the string.
  3. If an error occurs, a "passed" default value is returned.

This response is a possible solution that is better suited to the initial question than my previous post.

_x000D_
_x000D_
   static StrToNumber(val: string, defaultVal:number = 0): number_x000D_
   {        _x000D_
      let result:number = defaultVal;      _x000D_
      if(val == null) _x000D_
         return result;            _x000D_
      if(val.length == 0) _x000D_
         return result;      _x000D_
      val = val.trim();_x000D_
      if(val.length == 0) _x000D_
         return(result);_x000D_
      let sign:number = 1;     _x000D_
      //_x000D_
      // . obtain sign from string, and place result in "sign" local variable. The Sign naturally defaults to positive_x000D_
      //     1 for positive, -1 for negative._x000D_
      // . remove sign character from val. _x000D_
      //      Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign._x000D_
      // . error check for multiple sign characters_x000D_
      // . error check to make sure sign character is at the head or tail of the string_x000D_
      //              _x000D_
      {  _x000D_
         let positiveSignIndex = val.indexOf('+');_x000D_
         let negativeSignIndex = val.indexOf('-');_x000D_
         let nTailIndex = val.length-1;_x000D_
         //_x000D_
         // make sure both negative and positive signs are not in the string_x000D_
         //_x000D_
         if( (positiveSignIndex != -1) && (negativeSignIndex != -1) ) _x000D_
             return result;_x000D_
         //_x000D_
         // handle postive sign_x000D_
         //_x000D_
         if (positiveSignIndex != -1)_x000D_
         {_x000D_
            //_x000D_
            // make sure there is only one sign character_x000D_
            //_x000D_
            if( (positiveSignIndex != val.lastIndexOf('+')) )_x000D_
             return result;     _x000D_
             //_x000D_
             // make sure the sign is at the head or tail_x000D_
             //_x000D_
             if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             //_x000D_
             // remove sign from string_x000D_
             //_x000D_
             val = val.replace("+","").trim();                 _x000D_
         }    _x000D_
         //_x000D_
         // handle negative sign_x000D_
         //_x000D_
         if (negativeSignIndex != -1)_x000D_
         {_x000D_
            //_x000D_
            // make sure there is only one sign character_x000D_
            //_x000D_
            if( (negativeSignIndex != val.lastIndexOf('-')) )_x000D_
             return result;     _x000D_
             //_x000D_
             // make sure the sign is at the head or tail_x000D_
             //_x000D_
             if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             //_x000D_
             // remove sign from string_x000D_
             //_x000D_
             val = val.replace("-","").trim();  _x000D_
             sign = -1;                 _x000D_
         }               _x000D_
         //_x000D_
         // make sure text length is greater than 0_x000D_
         //       _x000D_
         if(val.length == 0) _x000D_
            return result;                             _x000D_
      }   _x000D_
      //_x000D_
      // convert string to a number_x000D_
      //_x000D_
      var r = +(<any>val);_x000D_
      if( (r != null) && (!isNaN(r)) )_x000D_
      {          _x000D_
         result = r*sign;         _x000D_
      }_x000D_
      return(result);    _x000D_
   }
_x000D_
_x000D_
_x000D_

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

PHP Try and Catch for SQL Insert

Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.

$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
     //handle the error here
}
//page continues loading

How do I POST a x-www-form-urlencoded request using Fetch?

Just set the body as the following

var reqBody = "username="+username+"&password="+password+"&grant_type=password";

then

fetch('url', {
      method: 'POST',
      headers: {
          //'Authorization': 'Bearer token',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: reqBody
  }).then((response) => response.json())
      .then((responseData) => {
          console.log(JSON.stringify(responseData));
      }).catch(err=>{console.log(err)})

How to insert TIMESTAMP into my MySQL table?

The DEFAULT value of a column in MySql is used only if it isn't provided a value for that column. So if you

INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', '', '$comments')

You are not using the DEFAULT value for the column date, but you are providing an empty string, so you get an error, because you can't store an empty string in a DATETIME column. The same thing apply if you use NULL, because again NULL is a value. However, if you remove the column from the list of the column you are inserting, MySql will use the DEFAULT value specified for that column (or the data type default one)

How to set conditional breakpoints in Visual Studio?

Create a breakpoint as you normally would, right click the red dot and select "condition".

Is it possible to set a number to NaN or infinity?

Cast from string using float():

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False

How to use MD5 in javascript to transmit a password

if you're using php jquery, this might help:

   $.ajax({
        url:'phpmd5file.php',
        data:{'mypassword',mypassword},
        dataType:"json",
        method:"POST",
        success:function(mymd5password){
            alert(mymd5password);
        }
    });

on your phpmd5.php file:

echo json_encode($_POST["mypassword"]);

no jsplugins needed. just use ajax and let php md5() do the job.

Custom Card Shape Flutter SDK

An Alternative Solution to the above

Card(
  shape: RoundedRectangleBorder(
     borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
  color: Colors.white,
  child: ...
)

You can use BorderRadius.only() to customize the corners you wish to manage.

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

I had a similar problem and solved it by checking the threads that are running. To see the running threads use the following command in mysql command line interface:

SHOW PROCESSLIST;

It can also be sent from phpMyAdmin if you don't have access to mysql command line interface.
This will display a list of threads with corresponding ids and execution time, so you can KILL the threads that are taking too much time to execute. In phpMyAdmin you will have a button for stopping threads by using KILL, if you are using command line interface just use the KILL command followed by the thread id, like in the following example:

KILL 115;

This will terminate the connection for the corresponding thread.

CSS force new line

Use <br /> OR <br> -

<li>Post by<br /><a>Author</a></li>

OR

<li>Post by<br><a>Author</a></li>

or

make the a element display:block;

<li>Post by <a style="display:block;">Author</a></li>

Try

How to set background color of an Activity to white programmatically?

Add this single line in your activity, after setContentView() call

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

What are all the differences between src and data-src attributes?

The first <img /> is invalid - src is a required attribute. data-src is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

SVN: Is there a way to mark a file as "do not commit"?

I came to this thread looking for a way to make an "atomic" commit of just some files and instead of ignoring some files on commit I went the other way and only commited the files I wanted:

svn ci filename1 filename2

Maybe, it will help someone.

How to instantiate a javascript class in another js file?

You can export your methods to access from other files like this:

file1.js

var name = "Jhon";
exports.getName = function() {
  return name;
}

file2.js

var instance = require('./file1.js');
var name = instance.getName();

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

ActionDone is use when click in next button in the keyboard that time keyboard is hide.Use in Edit Text or AppcompatEdit

XML

1.1 If you use AppCompatEdittext

    <android.support.v7.widget.AppCompatEditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionDone"/>

1.2 If you use Edittext

    <EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionDone"/>

JAVA

EditText edittext= (EditText) findViewById(R.id.edittext);
edittext.setImeOptions(EditorInfo.IME_ACTION_DONE);

Count number of rows per group and add result to original data frame

You were just one step away from incorporating the row count into the base dataset.

Using the tidy() function from the broom package, convert the frequency table into a data frame and inner join with df:

df <- data.frame(name=c('black','black','black','red','red'),
                         type=c('chair','chair','sofa','sofa','plate'),
                         num=c(4,5,12,4,3))
library(broom)
df <- merge(df, tidy(table(df[ , c("name","type")])), by=c("name","type"))
df
   name  type num Freq
1 black chair   4    2
2 black chair   5    2
3 black  sofa  12    1
4   red plate   3    1
5   red  sofa   4    1

How do I check if a number is positive or negative in C#?

bool isNegative(int n) {
  int i;
  for (i = 0; i <= Int32.MaxValue; i++) {
    if (n == i) 
      return false;
  }
  return true;
}

How can I measure the actual memory usage of an application or process?

In recent versions of Linux, use the smaps subsystem. For example, for a process with a PID of 1234:

cat /proc/1234/smaps

It will tell you exactly how much memory it is using at that time. More importantly, it will divide the memory into private and shared, so you can tell how much memory your instance of the program is using, without including memory shared between multiple instances of the program.

ERROR in ./node_modules/css-loader?

I am also facing the same problem, but I resolve.

npm install node-sass  

Above command work for me. As per your synario you can use the blow command.

Try 1

 npm install node-sass

Try 2

remove node_modules folder and run npm install

Try 3

npm rebuild node-sass

Try 4

npm install --save node-sass

For your ref you can go through this github link

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

How to maintain page scroll position after a jquery event is carried out?

For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:

<a  
href='javascript:void(0)'  
onclick='javascript:whatever causing the page to scroll to the top'  
></a>

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

Checking host availability by using ping in bash scripts

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

Write a formula in an Excel Cell using VBA

The correct character to use in this case is a full colon (:), not a semicolon (;).

How to send email to multiple recipients using python smtplib?

You need to understand the difference between the visible address of an email, and the delivery.

msg["To"] is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.

The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.

There are various reasons for this. For example forwarding. The To: header field doesn't change on forwarding, however the email is dropped into a different mailbox.

The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.

In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.

For the header, it can also contain for example the name, e.g. To: First Last <[email protected]>, Other User <[email protected]>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!

How to build splash screen in windows forms application?

simple and easy solution to create splash screen

  1. open new form use name "SPLASH"
  2. change background image whatever you want
  3. select progress bar
  4. select timer

now set timer tick in timer:

private void timer1_Tick(object sender, EventArgs e)
{
    progressBar1.Increment(1);
    if (progressBar1.Value == 100) timer1.Stop();        
}

add new form use name "FORM-1"and use following command in FORM 1.

note: Splash form works before opening your form1

  1. add this library

    using System.Threading;
    
  2. create function

    public void splash()
    {     
        Application.Run(new splash());
    }
    
  3. use following command in initialization like below.

    public partial class login : Form
    {     
        public login()
        {
            Thread t = new Thread(new ThreadStart(splash));
            t.Start();
            Thread.Sleep(15625);
    
            InitializeComponent();
    
            enter code here
    
            t.Abort();
        }
    }
    

http://solutions.musanitech.com/c-create-splash-screen/

Postgresql: Scripting psql execution with password

It can be done simply using PGPASSWORD. I am using psql 9.5.10. In your case the solution would be

PGPASSWORD=password psql -U myuser < myscript.sql

How to auto-indent code in the Atom editor?

This works for me:

'atom-workspace atom-text-editor':
    'ctrl-alt-a': 'editor:auto-indent'

You have to select all with ctrl-a first.

Get month name from date in Oracle

Try this,

select to_char(sysdate,'dd') from dual; -> 08 (date)
select to_char(sysdate,'mm') from dual; -> 02 (month in number)
select to_char(sysdate,'yyyy') from dual; -> 2013 (Full year)

Check if a row exists, otherwise insert

i'm writing my solution. my method doesn't stand 'if' or 'merge'. my method is easy.

INSERT INTO TableName (col1,col2)
SELECT @par1, @par2
   WHERE NOT EXISTS (SELECT col1,col2 FROM TableName
                     WHERE col1=@par1 AND col2=@par2)

For Example:

INSERT INTO Members (username)
SELECT 'Cem'
   WHERE NOT EXISTS (SELECT username FROM Members
                     WHERE username='Cem')

Explanation:

(1) SELECT col1,col2 FROM TableName WHERE col1=@par1 AND col2=@par2 It selects from TableName searched values

(2) SELECT @par1, @par2 WHERE NOT EXISTS It takes if not exists from (1) subquery

(3) Inserts into TableName (2) step values

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']
]);

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']
]);

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation


Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

    public function getShow($id)
    {
        // get request to 'users/show/{id}'
    }

    public function postStore()
    {
        // POST request to 'users/store'
    }

}

Implicit Controller documentation


It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

How to use \n new line in VB msgbox() ...?

The message box must end with a text and not with a variable

How to enable PHP short tags?

I'v Changed the short_open_tag Off to On on my aws centos 7 instance and php7(PHP 7.0.33 (cli) (built: Dec 6 2018 22:30:44) ( NTS )), but its not reflecting the php info page and the code. So I refer may docs and find a solution on my case. Add an extra line after the short_open_tag as asp_tags = On after that restart Apache It works on the code and I go the output correctly

php.ini file

engine = On

; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It is
; generally recommended that <?php and ?> should be used and that this feature
; should be disabled, as enabling it may result in issues when generating XML
; documents, however this remains supported for backward compatibility reasons.
; Note that this directive does not control the <?= shorthand tag, which can be
; used regardless of this directive. 
; Default Value: On   
; Development Value: Off     
; Production Value: Off  
; http://php.net/short-open-tag

short_open_tag = On

; Allow ASP-style <% %> tags   
; http://php.net/asp-tags
asp_tags = On

How to write a caption under an image?

<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>

Style as desired.

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

Right HTTP status code to wrong input

According to the below scenario ,

Let's say that someone makes a request to your server with data that is in the correct format, but is simply not "good" data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using "password" as their password). then the status code could be either 400 or 422 ?

Until now, I would have returned a "400 Bad Request", which, according to the w3.org, means:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

This description doesn't quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it's probably your best bet.

Recently, however, Someone from my Dev team pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code "422 Unprocessable Entity" as defined in the HTTP extension for WebDAV. HTTP status code 422 states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

SQL Client for Mac OS X that works with MS SQL Server

This will be the second question in a row I've answered with this, so I think it's worth pointing out that I have no affiliation with this product, but I use it and love it and think it's the right answer to this question too: DbVisualizer.

How to get multiline input from user

Use the input() built-in function to get a input line from the user.

You can read the help here.

You can use the following code to get several line at once (finishing by an empty one):

while input() != '':
    do_thing

Show constraints on tables command

Try doing:

SHOW TABLE STATUS FROM credentialing1;

The foreign key constraints are listed in the Comment column of the output.

Simple linked list in C++

You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.

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

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

Merge (Concat) Multiple JSONObjects in Java

An improved version of merge on Gson's JsonObjects - can go any level of nested structure
 /**
 * Merge "source" into "target". 
 * 
 * <pre>
 *     An improved version of merge on Gson's JsonObjects - can go any level of nested structure:
 *             1. merge root & nested attributes.
 *             2. replace list of strings. For. eg.
 *              source -> "listOfStrings": ["A!"]
 *              dest -> "listOfStrings": ["A", "B"]
 *              merged -> "listOfStrings": ["A!", "B"]
 *             3. can merge nested objects inside list. For. eg.
 *              source -> "listOfObjects": [{"key2": "B"}]
 *              dest -> "listOfObjects": [{"key1": "A"}]
 *              merged -> "listOfObjects": [{"key1": "A"}, {"key2": "B"}]
 * </pre>
 * @return the merged object (target).
 */
public static JsonObject deepMerge(JsonObject source, JsonObject target) {
    for (String key: source.keySet()) {
        JsonElement srcValue = source.get(key);
        if (!target.has(key)) {
            target.add(key, srcValue);
        } else {
            if (srcValue instanceof JsonArray) {
                JsonArray srcArray = (JsonArray)srcValue;
                JsonArray destArray = target.getAsJsonArray(key);
                if (destArray == null || destArray.size() == 0) {
                    target.add(key, srcArray);
                    continue;
                } else {
                    IntStream.range(0, srcArray.size()).forEach(index -> {
                        JsonElement srcElem = srcArray.get(index);
                        JsonElement destElem = null;
                        if (index < destArray.size()) {
                            destElem = destArray.get(index);
                        }
                        if (srcElem instanceof JsonObject) {
                            if (destElem == null) {
                                destElem = new JsonObject();
                            }
                            deepMerge((JsonObject) srcElem, (JsonObject) destElem);
                        } else {
                            destArray.set(index, srcElem);
                        }
                    });
                }
            } else if (srcValue instanceof JsonObject) {
                JsonObject valueJson = (JsonObject)srcValue;
                deepMerge(valueJson, target.getAsJsonObject(key));
            } else {
                target.add(key, srcValue);
            }
        }
    }
    return target;
}

How to pass password to scp?

  1. Make sure password authentication is enabled on the target server. If it runs Ubuntu, then open /etc/ssh/sshd_config on the server, find lines PasswordAuthentication=no and comment all them out (put # at the start of the line), save the file and run sudo systemctl restart ssh to apply the configuration. If there is no such line then you're done.
  2. Add -o PreferredAuthentications="password" to your scp command, e.g.:
    scp -o PreferredAuthentications="password" /path/to/file user@server:/destination/directory
    

Why does Git treat this text file as a binary file?

I had an instance where .gitignore contained a double \r (carriage return) sequence by purpose.

That file was identified as binary by git. Adding a .gitattributes file helped.

# .gitattributes file
.gitignore diff

How to remove duplicate values from an array in PHP

sometimes array_unique() is not the way, if you want get unique AND duplicated items...

$unique=array("","A1","","A2","","A1","");
$duplicated=array();

foreach($unique as $k=>$v) {

if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
 { unset($unique[$kt]);  $duplicated[]=$v; }

}

sort($unique); // optional
sort($duplicated); // optional

results on

array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */

array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */

How do I set hostname in docker-compose?

As of docker-compose version 3 and later, you can just use the hostname key:

version: '3'
services:
  dns:
    hostname: 'your-name'

Remove border radius from Select tag in bootstrap 3

You can use -webkit-border-radius: 0;. Like this:-

-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;

This will give square corners as well as dropdown arrows. Using -webkit-appearance: none; is not recommended as it will turn off all the styling done by Chrome.

How can I get input radio elements to horizontally align?

In your case, you just need to remove the line breaks (<br> tags) between the elements - input elements are inline-block by default (in Chrome at least). (updated example).

<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change

I'd suggest using <label> elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>'s for attribute with the <input>'s id: (example)

<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>

<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>

<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>

..or wrap the <label> elements around the <input> elements directly: (example)

<label>
    <input type="radio" name="editList" value="always"/>Always
</label>
<label>
    <input type="radio" name="editList" value="never"/>Never
</label>
<label>
    <input type="radio" name="editList" value="costChange"/>Cost Change
</label>

You can also get fancy and use the :checked pseudo class.

How should I do integer division in Perl?

int(x+.5) will round positive values toward the nearest integer. Rounding up is harder.

To round toward zero:

int($x)

For the solutions below, include the following statement:

use POSIX;

To round down: POSIX::floor($x)

To round up: POSIX::ceil($x)

To round away from zero: POSIX::floor($x) - int($x) + POSIX::ceil($x)

To round off to the nearest integer: POSIX::floor($x+.5)

Note that int($x+.5) fails badly for negative values. int(-2.1+.5) is int(-1.6), which is -1.

MySQL Workbench - Connect to a Localhost

if you are using localhost database, try port 3306

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

How to get the Development/Staging/production Hosting Environment in ConfigureServices

In Dotnet Core 2.0 the Startup-constructor only expects a IConfiguration-parameter.

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

How to read hosting environment there? I store it in Program-class during ConfigureAppConfiguration (use full BuildWebHost instead of WebHost.CreateDefaultBuilder):

public class Program
{
    public static IHostingEnvironment HostingEnvironment { get; set; }

    public static void Main(string[] args)
    {
        // Build web host
        var host = BuildWebHost(args);

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args)
    {
        return new WebHostBuilder()
            .UseConfiguration(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("hosting.json", optional: true)
                .Build()
            )
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                // Assigning the environment for use in ConfigureServices
                HostingEnvironment = env; // <---

                config
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                builder.AddConsole();
                builder.AddDebug();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();
    }

Ant then reads it in ConfigureServices like this:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var isDevelopment = Program.HostingEnvironment.IsDevelopment();
}

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

What should I set JAVA_HOME environment variable on macOS X 10.6?

Also, it`s interesting to set your PATH to reflect the JDK. After adding JAVA_HOME (which can be done with the example cited by 'mipadi'):

export JAVA_HOME=$(/usr/libexec/java_home)

Add also in ~/.profile:

export PATH=${JAVA_HOME}/bin:$PATH

P.S.: For OSX, I generally use .profile in the HOME dir instead of .bashrc

How to count TRUE values in a logical vector

There's also a package called bit that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.

z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)

system.time({
  sum(z) # 0.170s
})

system.time({
  bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

solution that worked for me is to change user under which Application Pool is started (ApplicationPoolIdentity obviously has not enough rights to access COM object).

Good luck!

How do I check for equality using Spark Dataframe without SQL Query?

There is another simple sql like option. With Spark 1.6 below also should work.

df.filter("state = 'TX'")

This is a new way of specifying sql like filters. For a full list of supported operators, check out this class.

What is the difference between '/' and '//' when used for division?

  • // is floor division, it will always give you the floor value of the result.
  • And the other one / is the floating-point division.

Followings are the difference between / and //; I have run these arithmetic operations in Python 3.7.2

>>> print (11 / 3)
3.6666666666666665

>>> print (11 // 3)
3

>>> print (11.3 / 3)
3.7666666666666667

>>> print (11.3 // 3)
3.0

Get Hours and Minutes (HH:MM) from date

If you want to display 24 hours format use:

SELECT FORMAT(GETDATE(),'HH:mm')

and to display 12 hours format use:

SELECT FORMAT(GETDATE(),'hh:mm')

How to get a value inside an ArrayList java

You haven't shown your Car type, but assuming you'd want the price of the first car, you could use:

public static void processCars(ArrayList<Car> cars) {
    Car car = cars.get(0);
    System.out.println(car.getPrice());
}

Note that I've changed the name of the list from car to cars - this is a list of cars, not a single car. (I've changed the method name in a similar way.)

If you only want the method to process a single car, you should change the parameter to be of type Car:

public static void processCar(Car car)

and then call it like this:

// In the main method
processCar(cars.get(0));

If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car> - it's unlikely that you'll really require that it's an ArrayList<Car>.

Exit Shell Script Based on Process Exit Code

For Bash:

# This will trap any errors or commands with non-zero exit status
# by calling function catch_errors()
trap catch_errors ERR;

#
# ... the rest of the script goes here
#

function catch_errors() {
   # Do whatever on errors
   #
   #
   echo "script aborted, because of errors";
   exit 0;
}

How to create strings containing double quotes in Excel formulas?

Use chr(34) Code:

    Joe = "Hi there, " & Chr(34) & "Joe" & Chr(34)
    ActiveCell.Value = Joe

Result:

    Hi there, "joe"

How can I pass command-line arguments to a Perl program?

my $output_file;

if((scalar (@ARGV) == 2) && ($ARGV[0] eq "-i"))

{

$output_file= chomp($ARGV[1]) ;


}

Split Div Into 2 Columns Using CSS

Best way to divide a div vertically --

#parent {
    margin: 0;
    width: 100%;
}
.left {
    float: left;
    width: 60%;
}
.right {
    overflow: hidden;
    width: 40%;
}

Increasing (or decreasing) the memory available to R processes

Use memory.limit(). You can increase the default using this command, memory.limit(size=2500), where the size is in MB. You need to be using 64-bit in order to take real advantage of this.

One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.

Non-alphanumeric list order from os.listdir()

You can use the builtin sorted function to sort the strings however you want. Based on what you describe,

sorted(os.listdir(whatever_directory))

Alternatively, you can use the .sort method of a list:

lst = os.listdir(whatever_directory)
lst.sort()

I think should do the trick.

Note that the order that os.listdir gets the filenames is probably completely dependent on your filesystem.

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

How to check if an element is visible with WebDriver

I have the following 2 suggested ways:

  1. You can use isDisplayed() as below:

    driver.findElement(By.id("idOfElement")).isDisplayed();
    
  2. You can define a method as shown below and call it:

    public boolean isElementPresent(By by) {
      try {
        driver.findElement(by);
        return true;
      }
    catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
      }
    }
    

Now, you can do assertion as below to check either the element is present or not:

assertTrue(isElementPresent(By.id("idOfElement")));

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

Calculating frames per second in a game

Good answers here. Just how you implement it is dependent on what you need it for. I prefer the running average one myself "time = time * 0.9 + last_frame * 0.1" by the guy above.

however I personally like to weight my average more heavily towards newer data because in a game it is SPIKES that are the hardest to squash and thus of most interest to me. So I would use something more like a .7 \ .3 split will make a spike show up much faster (though it's effect will drop off-screen faster as well.. see below)

If your focus is on RENDERING time, then the .9.1 split works pretty nicely b/c it tend to be more smooth. THough for gameplay/AI/physics spikes are much more of a concern as THAT will usually what makes your game look choppy (which is often worse than a low frame rate assuming we're not dipping below 20 fps)

So, what I would do is also add something like this:

#define ONE_OVER_FPS (1.0f/60.0f)
static float g_SpikeGuardBreakpoint = 3.0f * ONE_OVER_FPS;
if(time > g_SpikeGuardBreakpoint)
    DoInternalBreakpoint()

(fill in 3.0f with whatever magnitude you find to be an unacceptable spike) This will let you find and thus solve FPS issues the end of the frame they happen.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Try:

Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator).

https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-configuration

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

@Scope("prototype") bean scope not creating new bean

Your controller also need the @Scope("prototype") defined

like this:

@Controller
@Scope("prototype")
public class HomeController { 
 .....
 .....
 .....

}

How to import load a .sql or .csv file into SQLite?

This is how you can insert into an identity column:

CREATE TABLE my_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name COLLATE NOCASE);
CREATE TABLE temp_table (name COLLATE NOCASE);

.import predefined/myfile.txt temp_table 
insert into my_table (name) select name from temp_table;

myfile.txt is a file in C:\code\db\predefined\

data.db is in C:\code\db\

myfile.txt contains strings separated by newline character.

If you want to add more columns, it's easier to separate them using the pipe character, which is the default.

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

ContractFilter mismatch at the EndpointDispatcher exception

I had the same error on a WCF service deployed, the problem was related to another service deployed with another contract with the same port.

Solution

I used different ports in the web.config and the issue disappeared.

Service 1

contract="Service.WCF.Contracts.IBusiness1" 
baseAddress="net.tcp://local:5244/ServiceBusiness" 

Service 2

contract="Service.WCF.Contracts.IBusiness2"
baseAddress="net.tcp://local:5243/ServiceBusiness"

Also, I ran into this situation by using diferent port for the same address between the service and the consumer.

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

Distinct by property of class with LINQ

You can implement an IEqualityComparer and use that in your Distinct extension.

class CarEqualityComparer : IEqualityComparer<Car>
{
    #region IEqualityComparer<Car> Members

    public bool Equals(Car x, Car y)
    {
        return x.CarCode.Equals(y.CarCode);
    }

    public int GetHashCode(Car obj)
    {
        return obj.CarCode.GetHashCode();
    }

    #endregion
}

And then

var uniqueCars = cars.Distinct(new CarEqualityComparer());

getting "No column was specified for column 2 of 'd'" in sql server cte?

[edit]

I tried to rewrite your query, but even yours will work once you associate aliases to the aggregate columns in the query that defines 'd'.


I think you are looking for the following:

First one:

select 
    c.duration, 
    c.totalbookings, 
    d.bkdqty 
from
    (select 
               month(bookingdate) as duration, 
               count(*) as totalbookings 
           from 
               entbookings
           group by month(bookingdate)
    ) AS c 
    inner join 
    (SELECT 
               duration, 
               sum(totalitems) 'bkdqty'
           FROM 
               [DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
           group by duration
    ) AS d 
    on c.duration = d.duration

Second one:

select 
    c.duration, 
    c.totalbookings, 
    d.bkdqty 
from
    (select 
               month(bookingdate) as duration, 
               count(*) as totalbookings 
           from 
               entbookings
           group by month(bookingdate)
    ) AS c 
    inner join 
    (select 
               month(clothdeliverydate) 'clothdeliverydatemonth', 
               SUM(CONVERT(INT, deliveredqty)) 'bkdqty'
           FROM 
               barcodetable
           where 
               month(clothdeliverydate) is not null
               group by month(clothdeliverydate)
    ) AS d 
    on c.duration = d.duration

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

Swift Open Link in Safari

In Swift 1.2:

@IBAction func openLink {    
    let pth = "http://www.google.com"
    if let url = NSURL(string: pth){
        UIApplication.sharedApplication().openURL(url)
}

Can't ignore UserInterfaceState.xcuserstate

Had a friend show me this amazing site https://www.gitignore.io/. Enter the IDE of your choice or other options and it will automatically generate a gitignore file consisting of useful ignores, one of which is the xcuserstate. You can preview the gitignore file before downloading.

download file using an ajax request

there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.

First you need to separate the page processing from the results download.

1) Only the page calculations are made in the ajax call.

$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" },

       function(data, status) 
       {
            if (status == "success") 
            {
                /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */
                window.location.href = DownloadPage.php+"?ID="+29;
            }               
       }
);

// For example: in the CalculusPage.php

    if ( !empty($_POST["calculusFunction"]) ) 
    {
        $ID = $_POST["ID"];

        $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;
        ...
    }

// For example: in the DownloadPage.php

    $ID = $_GET["ID"];

    $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID;
    ...

    $filename="Export_Data.xls";
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: inline; filename=$filename");

    ...

I hope this solution can be useful for many, as it was for me.

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

Java 8

map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);

How to sign in kubernetes dashboard?

All the previous answers are good to me. But a straight forward answer on my side would come from https://github.com/kubernetes/dashboard/wiki/Creating-sample-user#bearer-token. Just use kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}'). You will have many values for some keys (Name, Namespace, Labels, ..., token). The most important is the token that corresponds to your name. copy that token and paste it in the token box. Hope this helps.

Ruby: How to iterate over a range, but in set increments?

You can use Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

Is it possible to override / remove background: none!important with jQuery?

div { background: none !important }
div { background: red; }

Is transparent.

div { background: none !important }
div { background: red !important; }

Is red.

An !important can override another !important.

If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

Pass multiple values with onClick in HTML link

 $Name= "'".$row['Name']."'";
  $Val1= "'".$row['Val1']."'";
  $Year= "'".$row['Year']."'";
  $Month="'".$row['Month']."'";

 echo '<button type="button"   onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');"  >submit</button>'; 

How do I manage conflicts with git submodules?

Well, its not technically managing conflicts with submodules (ie: keep this but not that), but I found a way to continue working...and all I had to do was pay attention to my git status output and reset the submodules:

git reset HEAD subby
git commit

That would reset the submodule to the pre-pull commit. Which in this case is exactly what I wanted. And in other cases where I need the changes applied to the submodule, I'll handle those with the standard submodule workflows (checkout master, pull down the desired tag, etc).

How to rename array keys in PHP?

It is from duplicated question

$json = '[   
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},    
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';

$array = json_decode($json, true);

$out = array_map(function ($product) {
  return array_merge([
    'price'    => $product['product_price'],
    'quantity' => $product['product_quantity'],
  ], array_flip(array_filter(array_flip($product), function ($value) {
    return $value != 'product_price' && $value != 'product_quantity';
  })));
}, $array);

var_dump($out);

https://repl.it/@Piterden/Replace-keys-in-array

Assign variable in if condition statement, good practice or not?

You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

The code:

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException 
{
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

How to center a View inside of an Android Layout?

If you want to center one view, use this one. In this case TextView must be the lowermost view in your XML because it's layout_height is match_parent.

<TextView 
    android:id="@+id/tv_to_be_centered"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:gravity="center"
    android:text="Some text"
/>

Programmatically change UITextField Keyboard type

    textFieldView.keyboardType = UIKeyboardType.PhonePad

This is for swift. Also in order for this to function properly it must be set after the textFieldView.delegate = self

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

How unique is UUID?

I concur with the other answers. UUIDs are safe enough for nearly all practical purposes1, and certainly for yours.

But suppose (hypothetically) that they aren't.

Is there a better system or a pattern of some type to alleviate this issue?

Here are a couple of approaches:

  1. Use a bigger UUID. For instance, instead of a 128 random bits, use 256 or 512 or ... Each bit you add to a type-4 style UUID will reduce the probability of a collision by a half, assuming that you have a reliable source of entropy2.

  2. Build a centralized or distributed service that generates UUIDs and records each and every one it has ever issued. Each time it generates a new one, it checks that the UUID has never been issued before. Such a service would be technically straight-forward to implement (I think) if we assumed that the people running the service were absolutely trustworthy, incorruptible, etcetera. Unfortunately, they aren't ... especially when there is the possibility of governments' security organizations interfering. So, this approach is probably impractical, and may be3 impossible in the real world.


1 - If uniqueness of UUIDs determined whether nuclear missiles got launched at your country's capital city, a lot of your fellow citizens would not be convinced by "the probability is extremely low". Hence my "nearly all" qualification.

2 - And here's a philosophical question for you. Is anything ever truly random? How would we know if it wasn't? Is the universe as we know it a simulation? Is there a God who might conceivably "tweak" the laws of physics to alter an outcome?

3 - If anyone knows of any research papers on this problem, please comment.

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

How to run only one task in ansible playbook?

are you familiar with handlers? I think it's what you are looking for. Move the restart from hadoop_master.yml to roles/hadoop_primary/handlers/main.yml:

- name: start hadoop jobtracker services
  service: name=hadoop-0.20-mapreduce-jobtracker state=started

and now call use notify in hadoop_master.yml:

- name: Install the namenode and jobtracker packages
  apt: name={{item}} force=yes state=latest
  with_items: 
   - hadoop-0.20-mapreduce-jobtracker
   - hadoop-hdfs-namenode
   - hadoop-doc
   - hue-plugins
  notify: start hadoop jobtracker services

How should I call 3 functions in order to execute them one after the other?

In Javascript, there are synchronous and asynchronous functions.

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.

Asynchronous Functions

Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.

But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.

Callbacks

Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.

Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.

If we create the functions like this

function some_3secs_function(value, callback){
  //do stuff
  callback();
}

then you can call then in order, like this:

some_3secs_function(some_value, function() {
  some_5secs_function(other_value, function() {
    some_8secs_function(third_value, function() {
      //All three functions have completed, in order.
    });
  });
});

Timeouts

In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.

function executeAsynchronously(functions, timeout) {
  for(var i = 0; i < functions.length; i++) {
    setTimeout(functions[i], timeout);
  }
}

This can be called like so:

executeAsynchronously(
    [doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.

Writing to a TextBox from another thread?

Have a look at Control.BeginInvoke method. The point is to never update UI controls from another thread. BeginInvoke will dispatch the call to the UI thread of the control (in your case, the Form).

To grab the form, remove the static modifier from the sample function and use this.BeginInvoke() as shown in the examples from MSDN.

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

How to set a ripple effect on textview or imageview on Android?

In addition to @Bikesh M Annur's answer, be sure to update your support libraries. Previously I was using 23.1.1 and nothing happened. Updating it to 23.3.0 did the trick.

Hide particular div onload and then show div after click

You are missing # hash character before id selectors, this should work:

$(document).ready(function() {
    $("#div2").hide();

    $("#preview").click(function() {
      $("#div1").hide();
      $("#div2").show();
    });

});

Learn More about jQuery ID Selectors

Does it make sense to use Require.js with Angular.js?

As @ganaraj mentioned AngularJS has dependency injection at its core. When building toy seed applications with and without RequireJS, I personally found RequireJS was probably overkill for most use cases.

That doesn't mean RequireJS is not useful for it's script loading capabilities and keeping your codebase clean during development. Combining the r.js optimizer (https://github.com/jrburke/r.js) with almond (https://github.com/jrburke/almond) can create a very slim script loading story. However since its dependency management features are not as important with angular at the core of your application, you can also evaluate other client side (HeadJS, LABjs, ...) or even server side (MVC4 Bundler, ...) script loading solutions for your particular application.

When saving, how can you check if a field has changed?

improving @josh answer for all fields:

class Person(models.Model):
  name = models.CharField()

def __init__(self, *args, **kwargs):
    super(Person, self).__init__(*args, **kwargs)
    self._original_fields = dict([(field.attname, getattr(self, field.attname))
        for field in self._meta.local_fields if not isinstance(field, models.ForeignKey)])

def save(self, *args, **kwargs):
  if self.id:
    for field in self._meta.local_fields:
      if not isinstance(field, models.ForeignKey) and\
        self._original_fields[field.name] != getattr(self, field.name):
        # Do Something    
  super(Person, self).save(*args, **kwargs)

just to clarify, the getattr works to get fields like person.name with strings (i.e. getattr(person, "name")