Programs & Examples On #Data connections

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

How to get SQL from Hibernate Criteria API (*not* for logging)

If you are using Hibernate 3.6 you can use the code in the accepted answer (provided by Brian Deterling) with slight modification:

  CriteriaImpl c = (CriteriaImpl) criteria;
  SessionImpl s = (SessionImpl) c.getSession();
  SessionFactoryImplementor factory = (SessionFactoryImplementor) s.getSessionFactory();
  String[] implementors = factory.getImplementors(c.getEntityOrClassName());
  LoadQueryInfluencers lqis = new LoadQueryInfluencers();
  CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable) factory.getEntityPersister(implementors[0]), factory, c, implementors[0], lqis);
  Field f = OuterJoinLoader.class.getDeclaredField("sql");
  f.setAccessible(true);
  String sql = (String) f.get(loader);

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

How to enable local network users to access my WAMP sites?

What finally worked for me is what I found here:

http://www.codeproject.com/Tips/395286/How-to-Access-WAMP-Server-in-LAN-or-WAN

To summarize:

  • set Listen in httpd.conf:

    Listen 192.168.1.154:8081

  • Add Allow from all to this section:

    <Directory "cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory>

  • Set an inbound port rule. I think the was the crucial missing part for me:

Great! The next step is to open port (8081) of the server such that everyone can access your server. This depends on which OS you are using. Like if you are using Windows Vista, then follow the below steps.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “8081” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Now you are done with PORT opening as well.

Next is “Restart All Services” of WAMP and access your machine in LAN or WAN.

NullInjectorError: No provider for AngularFirestore

For AngularFire2 Latest version

Install AngularFire2

$ npm install --save firebase @angular/fire

Then update app.module.ts file

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppComponent } from './app.component';
    import { FormsModule } from '@angular/forms';


    import { AngularFireModule } from '@angular/fire';
    import { AngularFireDatabaseModule } from '@angular/fire/database';
    import { environment } from '../environments/environment';
    import { AngularFirestoreModule } from '@angular/fire/firestore';


    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,

        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule,
        AngularFireDatabaseModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

Check FireStore CRUD operation tutorial here

enter image description here

What REST PUT/POST/DELETE calls should return by a convention?

Creating a resource is generally mapped to POST, and that should return the location of the new resource; for example, in a Rails scaffold a CREATE will redirect to the SHOW for the newly created resource. The same approach might make sense for updating (PUT), but that's less of a convention; an update need only indicate success. A delete probably only needs to indicate success as well; if you wanted to redirect, returning the LIST of resources probably makes the most sense.

Success can be indicated by HTTP_OK, yes.

The only hard-and-fast rule in what I've said above is that a CREATE should return the location of the new resource. That seems like a no-brainer to me; it makes perfect sense that the client will need to be able to access the new item.

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

Node.js getaddrinfo ENOTFOUND

I was getting the same error and used below below link to get help:

https://nodejs.org/api/http.html#http_http_request_options_callback

I was not having in my code:

req.end();

(NodeJs V: 5.4.0) once added above req.end(); line, I was able to get rid of the error and worked fine for me.

How can I change or remove HTML5 form validation default error messages?

I Found a way Accidentally Now: you can need use this: data-error:""

<input type="username" class="form-control" name="username" value=""
placeholder="the least 4 character"
data-minlength="4" data-minlength-error="the least 4 character"
data-error="This is a custom Errot Text fot patern and fill blank"
max-length="15" pattern="[A-Za-z0-9]{4,}"
title="4~15 character" required/>

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Show create table in classic asp (handles constraints, primary keys, copying the table structure and/or data ...)

Sql server Show create table Mysql-style "Show create table" and "show create database" commands from Microsoft sql server. The script is written is Microsoft asp-language and is quite easy to port to another language.*

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I think this problem occurs when you try to access your web driver object after

1) a window has closed and you haven't yet switched to the parent

2) you switched to a window that wasn't quite ready and has been updated since you switched

waiting for the windowhandles.count to be what you're expecting doesn't take into account the page content nor does document.ready. I'm still searching for a solution to this problem

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

YYYY-MM-DD format date in shell script

I use $(date +"%Y-%m-%d") or $(date +"%Y-%m-%d %T") with time and hours.

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

Why isn't .ico file defined when setting window's icon?

No way what is suggested here works - the error "bitmap xxx not defined" is ever present. And yes, I set the correct path to it.

What it did work is this:

imgicon = PhotoImage(file=os.path.join(sp,'myicon.gif'))
root.tk.call('wm', 'iconphoto', root._w, imgicon)  

where sp is the script path, and root the Tk root window.

It's hard to understand how it does work (I shamelessly copied it from fedoraforums) but it works

Cannot create PoolableConnectionFactory

I had the same problem with localhost in the source URL. I resolved with 127.0.0.1 instead of localhost.

SQL Server PRINT SELECT (Print a select query result)?

set @n = (select sum(Amount) from Expense)
print 'n=' + @n

How can I insert a line break into a <Text> component in React Native?

Use:

<Text>{`Hi,\nCurtis!`}</Text>

Result:

Hi,

Curtis!

Jenkins pipeline how to change to another folder

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}

VB.net Need Text Box to Only Accept Numbers

every text box has a validating and validated event you can use then as follows :-

Private Sub PriceTxt_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles PriceTxt.Validating
                If Not IsNumeric(PriceTxt.Text) Then
                 PriceTxt.BackColor = Color.Red
                 MsgBox("The Price Should Be Numeric Only , Enter Again", vbCritical)
                 PriceTxt.Text = ""
                 PriceTxt.BackColor = Color.White
                End If
End Sub

WCF Service, the type provided as the service attribute values…could not be found

In my case I did a "Convert to application" to the wrong folder on iis. My application was set in a subfolder of where it should have been.

Google Chrome display JSON AJAX response as tree and not as a plain text

There was an issue with a build of Google Chrome Dev build 24.0.1312.5 that caused the preview panel to no longer display a json object tree but rather flat text. It should be fixed in the next dev

See more here: http://code.google.com/p/chromium/issues/detail?id=160733

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

enter image description here

Do we need to execute Commit statement after Update in SQL Server

Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.

Best way to get identity of inserted row?

Even though this is an older thread, there is a newer way to do this which avoids some of the pitfalls of the IDENTITY column in older versions of SQL Server, like gaps in the identity values after server reboots. Sequences are available in SQL Server 2016 and forward which is the newer way is to create a SEQUENCE object using TSQL. This allows you create your own numeric sequence object in SQL Server and control how it increments.

Here is an example:

CREATE SEQUENCE CountBy1  
    START WITH 1  
    INCREMENT BY 1 ;  
GO  

Then in TSQL you would do the following to get the next sequence ID:

SELECT NEXT VALUE FOR CountBy1 AS SequenceID
GO

Here are the links to CREATE SEQUENCE and NEXT VALUE FOR

How to add line breaks to an HTML textarea?

here is the thing i did for the same trouble i had.

when I'm passing the text to the next page in jsp, i'm reading it as a textarea instead of reading something like

so the output came as you wanted. and for other properties, you can use as below.

<textarea style="background-color: white; border: none; width:660px;font-family: Arial, Helvetica, sans-serif; font-size:1.0em; resize:none;" name="text" cols="75" rows="15" readonly="readonly" ><s:property value="%{text}"/></textarea>

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

How do you load custom UITableViewCells from Xib files?

The correct way to do it is to create a UITableViewCell subclass implementation, header, and XIB. In the XIB remove any views and just add a table cell. Set the class as the name of the UITableViewCell subclass. For file owner, make it the UITableViewController subclass class name. Connect the file owner to the cell using the tableViewCell outlet.

In the header file:

UITableViewCell *_tableViewCell;
@property (assign) IBOutlet UITableViewCell *tableViewCell;

In the implementation file:

@synthesize tableViewCell = _tableViewCell;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellIdentifier = @"reusableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:kCellIdentifier owner:self options:nil];
        cell = _tableViewCell;
        self.tableViewCell = nil;
    }

    return cell;
}

How to change the JDK for a Jenkins job?

Using latest Jenkins version 2.7.4 which is also having a bug for existing jobs.

  1. Add new JDKs through Manage Jenkins -> Global Tool Configuration -> JDK ** If you edit current job then JDK dropdown is not showing (bug)

  2. Hit http://your_jenkin_server:8080/restart and restart the server

  3. Re-configure job

Now, you should see JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

Is there a float input type in HTML5?

<input type="number" step="any">

This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.

How to calculate the number of days between two dates?

From my little date difference calculator:

var startDate = new Date(2000, 1-1, 1);  // 2000-01-01
var endDate =   new Date();              // Today

// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
  var ndays;
  var tv1 = d1.valueOf();  // msec since 1970
  var tv2 = d2.valueOf();

  ndays = (tv2 - tv1) / 1000 / 86400;
  ndays = Math.round(ndays - 0.5);
  return ndays;
}

So you would call:

var nDays = diffDays(startDate, endDate);

(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)

Addendum

The code can be improved by changing these lines:

  var tv1 = d1.getTime();  // msec since 1970
  var tv2 = d2.getTime();

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

How to sum a list of integers with java streams?

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:

integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();

Eclipse Java error: This selection cannot be launched and there are no recent launches

click on the project that you want to run on the left side in package explorer and then click the Run button.

Update query using Subquery in Sql Server

Here is a nice explanation of update operation with some examples. Although it is Postgres site, but the SQL queries are valid for the other DBs, too. The following examples are intuitive to understand.

-- Update contact names in an accounts table to match the currently assigned salesmen:

UPDATE accounts SET (contact_first_name, contact_last_name) =
    (SELECT first_name, last_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);

-- A similar result could be accomplished with a join:

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM salesmen WHERE salesmen.id = accounts.sales_id;

However, the second query may give unexpected results if salesmen.id is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple id matches. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all.

Hence for the given example, the most reliable query is like the following.

UPDATE tempDataView SET (marks) =
    (SELECT marks FROM tempData
     WHERE tempDataView.Name = tempData.Name);

Get size of all tables in database

If you are using SQL Server Management Studio (SSMS), instead of running a query (which in my case returned duplicate rows) you can run a standard report

  1. Right click on the database
  2. Navigate to Reports > Standard Reports > Disk Usage By Table

Note: The database compatibility level must be set to 90 or above for this to work correctly. See http://msdn.microsoft.com/en-gb/library/bb510680.aspx

window.open with target "_blank" in Chrome

It's a setting in chrome. You can't control how the browser interprets the target _blank.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

This problem took me about one day, on one of mine ASP.NET MVC project fortunately i had the problem on my machine and not in production environment, so comparing web.config i see and removing that the error disappeared... a true challenge connect the SQL Server error 26 to this problem

How to rollback a specific migration?

You can rollback your migration by using rake db:rollback with different options. The syntax will be different according to your requirements.

If you want to rollback just the last migration, then you can use either

rake db:rollback

or

rake db:rollback STEP=1

If you want rollback number of migrations at once, then you simply pass an argument:

rake db:rollback STEP=n

where n is number of migrations to rollback, counting from latest migration.

If you want to rollback to a specific migration, then you should pass the version of the migration in the following:

rake db:migrate:down VERSION=xxxxx

where xxxxx is the version number of the migration.

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

twitter bootstrap 3.0 typeahead ajax example

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>

How to match hyphens with Regular Expression?

Escape the hyphen.

[a-zA-Z0-9!$* \t\r\n\-]

UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had to uninstall then re-install the xunit.runner.visualstudio nuget package. I tried this after trying all the above suggestions, so may be it was a mixture of things.

AngularJs $http.post() does not send data

To send data via Post methode with $http of angularjs you need to change

data: "message=" + message, with data: $.param({message:message})

iPhone - Get Position of UIView within entire UIWindow

That's an easy one:

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  1. don't change when rotating the device.
  2. always have their origin in the top left corner of the unrotated screen.
  3. are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

Resource leak: 'in' is never closed

// An InputStream which is typically connected to keyboard input of console programs

Scanner in= new Scanner(System.in);

above line will invoke Constructor of Scanner class with argument System.in, and will return a reference to newly constructed object.

It is connected to a Input Stream that is connected to Keyboard, so now at run-time you can take user input to do required operation.

//Write piece of code 

To remove the memory leak -

in.close();//write at end of code.

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

Installing packages in Sublime Text 2

With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:

  1. Always look up a package in the wbond community. There you'll be able to see how many people have installed that package (the more popular, the better) as well as the documentation on the package (if any).
  2. Menu Items under Prefs > Package Control. Here you can install, remove or see a list of all installed packages.
  3. Prefs > Package Settings. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.
  4. CTRL+SHIFT+P. This will bring up a menu where you can look up a lot of the functions your installed packages can do. Just start typing and it will start filtering.

How to download a Nuget package without nuget.exe or Visual Studio extension?

To obtain the current stable version of the NuGet package use:

https://www.nuget.org/api/v2/package/{packageID}

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

you can use Android Asset in android studio , and android Asset will give you image in this size as a drawable and the application will automatically use the size based on screen of device or emulate

Make an Installation program for C# applications and include .NET Framework installer into the setup

Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.

Editing the git commit message in GitHub

I was facing the same problem.

See in your github for a particular branch and you will come to know the commit id of the very first commit in that branch. do a rebase to that:

git rebase -i

editor will open up. Do a track of your commits from github UI and opened editor and change the messages.

How do I use a regular expression to match any string, but at least 3 characters?

Try this .{3,} this will match any characher except new line (\n)

Letsencrypt add domain to existing certificate

You can replace the certificate by just running the certbot again with ./certbot-auto certonly

You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:

-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)

It contains these names: <domain>

You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.

Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------

Just chose Expand and replace it.

Fill formula down till last row in column

It's a one liner actually. No need to use .Autofill

Range("M3:M" & LastRow).Formula = "=G3&"",""&L3"

Android Studio: /dev/kvm device permission denied

In order to make a virtual device in Linux - I have to follow this three command and it helps me to avoid trouble for building avd devices - the process are -

sudo apt install qemu-kvm
sudo adduser $USER kvm
sudo chown $USER /dev/kvm 

so, now you are good to go, restart android studio and start building application with emulator.

How do I perform a Perl substitution on a string while keeping the original?

Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)

As his approach uses map, it also works well for arrays, but requires cascading map to produce a temporary array (otherwise the original would be modified):

my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified

Typescript Type 'string' is not assignable to type

I was facing the same issue, I made below changes and the issue got resolved.

Open watchQueryOptions.d.ts file

\apollo-client\core\watchQueryOptions.d.ts

Change the query type any instead of DocumentNode, Same for mutation

Before:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **DocumentNode**;

After:

export interface QueryBaseOptions<TVariables = OperationVariables> {
    query: **any**;

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

jQuery Validate Plugin - How to create a simple custom rule?

You can create a simple rule by doing something like this:

jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");

And then applying this like so:

$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});

Just change the contents of the 'addMethod' to validate your checkboxes.

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

Eclipse - Unable to install breakpoint due to missing line number attributes

This is explained in detail here:

https://github.com/spring-projects/spring-ide/issues/78

Just for future reference, this is the relevant part of the answer (ignore the fact that refers to a Spring Boot application, behavior is the same for lot of other cases):

Whenever you set a breakpoint in Eclipse/STS, the IDE tries to set the breakpoint in the VM if you launch an app. That is what happens in your case when you run the boot app in debug mode.

For each class that gets loaded into the JVM, the IDE checks whether it needs to set a breakpoint or not. If it decides to set the breakpoint, the tries to do so (using the information from the breakpoint definition in the IDE, including its line number, since you usually set line breakpoints on a source file at a given line).

This decision (whether to set the breakpoint on a given loaded class or not) checks the types that you set the breakpoint on, enclosing types, and inner classes. This makes sure that breakpoints for inner classes (even anonymous inner classes) are set to the JVM (and are not ignored).

Spring Boot generates an inner class for your controller at runtime (this is the CGLIB generated inner class that appears in the error message). When the JVM loads that class, it tries to set the line number breakpoint of the enclosing type (for this inner class). Since the generated inner class doesn't have any line number information (it doesn't need to have line number information), setting the breakpoint fails for this inner class with the mentioned error message.

When the IDE loads the enclosing type (your controller class itself), it also tries to set the line breakpoint and succeeds with that. This is visualized with the check marker on the breakpoint marker.

Therefore you can safely ignore the error message that shows up. To avoid this error message to show up, you can go to the preferences (Java -> Debug) and disable "Warn when unable to install breakpoint due to missing line number attributes".

No 'Access-Control-Allow-Origin' header is present on the requested resource error

I believe this might likely be that Chrome does not support localhost to go through the Access-Control-Allow-Origin -- see Chrome issue

To have Chrome send Access-Control-Allow-Origin in the header, just alias your localhost in your /etc/hosts file to some other domain, like:

127.0.0.1   localhost yourdomain.com

Then if you'd access your script using yourdomain.com instead of localhost, the call should succeed.

Remove title in Toolbar in appcompat-v7

The correct way to hide title/label of ToolBar the following codes:

  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);

Display MessageBox in ASP

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
    alert("Hello!");
}
</script>

</body>
</html>

Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.

Inner text shadow with CSS

Here's a great solution for TRUE inset text shadow using the background-clip CSS3 property:

.insetText {
    background-color: #666666;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    color: transparent;
    text-shadow: rgba(255,255,255,0.5) 0px 3px 3px;
}

Android SQLite Example

The following Links my help you

1. Android Sqlite Database

2. Tutorial 1

Database Helper Class:

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.

This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.

You need more refer this link Sqlite Helper

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

I faced this issue as well but in my case, I was in wrong directory. Check the directory you are working

getResourceAsStream() vs FileInputStream

The java.io.File and consorts acts on the local disk file system. The root cause of your problem is that relative paths in java.io are dependent on the current working directory. I.e. the directory from which the JVM (in your case: the webserver's one) is started. This may for example be C:\Tomcat\bin or something entirely different, but thus not C:\Tomcat\webapps\contextname or whatever you'd expect it to be. In a normal Eclipse project, that would be C:\Eclipse\workspace\projectname. You can learn about the current working directory the following way:

System.out.println(new File(".").getAbsolutePath());

However, the working directory is in no way programmatically controllable. You should really prefer using absolute paths in the File API instead of relative paths. E.g. C:\full\path\to\file.ext.

You don't want to hardcode or guess the absolute path in Java (web)applications. That's only portability trouble (i.e. it runs in system X, but not in system Y). The normal practice is to place those kind of resources in the classpath, or to add its full path to the classpath (in an IDE like Eclipse that's the src folder and the "build path" respectively). This way you can grab them with help of the ClassLoader by ClassLoader#getResource() or ClassLoader#getResourceAsStream(). It is able to locate files relative to the "root" of the classpath, as you by coincidence figured out. In webapplications (or any other application which uses multiple classloaders) it's recommend to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this so you can look "outside" the webapp context as well.

Another alternative in webapps is the ServletContext#getResource() and its counterpart ServletContext#getResourceAsStream(). It is able to access files located in the public web folder of the webapp project, including the /WEB-INF folder. The ServletContext is available in servlets by the inherited getServletContext() method, you can call it as-is.

See also:

How to use youtube-dl from a python program?

Here is a way.

We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']. Then, invoke youtube_dl.main(opts). In this way, we write our custom .py module, import youtube_dl and then invoke the main() function.

Use formula in custom calculated field in Pivot Table

Pivot table Excel2007- average to exclude zeros

=sum(XX:XX)/count if(XX:XX, ">0")

Invoice USD

Qty Rate(count) Value (sum) 300 0.000 000.000 1000 0.385 385.000

Average Rate Count should Exclude 0.000 rate

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

This worked for me after struggling a bit

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
 </dependency>

 <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
 </dependency>

 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
 </dependency>

OS specific instructions in CMAKE: How to?

In General

You can detect and specify variables for several operating systems like that:

Detect Microsoft Windows

if(WIN32)
    # for Windows operating system in general
endif()

Or:

if(MSVC OR MSYS OR MINGW)
    # for detecting Windows compilers
endif()

Detect Apple MacOS

if(APPLE)
    # for MacOS X or iOS, watchOS, tvOS (since 3.10.3)
endif()

Detect Unix and Linux

if(UNIX AND NOT APPLE)
    # for Linux, BSD, Solaris, Minix
endif()

Your specific linker issue

To solve your issue with the Windows-specific wsock32 library, just remove it from other systems, like that:

if(WIN32)
    target_link_libraries(${PROJECT_NAME} bioutils wsock32)
else
    target_link_libraries(${PROJECT_NAME} bioutils)
endif()

Adding three months to a date in PHP

Following should work

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

Catch a thread's exception in the caller thread in Python

A simple way of catching thread's exception and communicating back to the caller method could be by passing dictionary or a list to worker method.

Example (passing dictionary to worker method):

import threading

def my_method(throw_me):
    raise Exception(throw_me)

def worker(shared_obj, *args, **kwargs):
    try:
        shared_obj['target'](*args, **kwargs)
    except Exception as err:
        shared_obj['err'] = err

shared_obj = {'err':'', 'target': my_method}
throw_me = "Test"

th = threading.Thread(target=worker, args=(shared_obj, throw_me), kwargs={})
th.start()
th.join()

if shared_obj['err']:
    print(">>%s" % shared_obj['err'])

setContentView(R.layout.main); error

Step 1 : import android.*;

Step 2 : clean your project

Step 3 : Enjoy !!!

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

I also wondered that long time ago. I searched a bit in my history and I think that this post: http://lists.mysql.com/internals/34919 represents the semi-official position of MySQL (before Oracle's intervention ;))

In short:

this limitation stems only from the way in which this feature is currently implemented in the server and there are no other reasons for its existence.

So their explanation is "because it is implemented like this". Doesn't sound very scientific. I guess it all comes from some old code. This is suggested in the thread above: "carry-over from when only the first timestamp field was auto-set/update".

Cheers!

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Windows 7 environment variable not working in path

Things like having %PATH% or spaces between items in your path will break it. Be warned.

Yes, windows paths that include spaces will cause errors. For example an application added this to the front of the system %PATH% variable definition:

C:\Program Files (x86)\WebEx\Productivity Tools;C:\Sybase\IQ-16_0\Bin64;

which caused all of the paths in %PATH% to not be set in the cmd window.

My solution is to demarcate the extended path variable in double quotes where needed:

"C:\Program Files (x86)\WebEx\Productivity Tools";C:\Sybase\IQ-16_0\Bin64;

The spaces are therefore ignored and the full path variable is parsed properly.

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

Delete statement in SQL is very slow

It's possible that other tables have FK constraint to your [table]. So the DB needs to check these tables to maintain the referential integrity. Even if you have all needed indexes corresponding these FKs, check their amount.

I had the situation when NHibernate incorrectly created duplicated FKs on the same columns, but with different names (which is allowed by SQL Server). It has drastically slowed down running of the DELETE statement.

mysql: see all open connections to a given database?

That should do the trick for the newest MySQL versions:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE DB = "elstream_development";

How to test if a DataSet is empty?

This should work

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);

if(ds.Tables.Count > 0)
{
  // enter code here
}

How to insert an object in an ArrayList at a specific position

Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);

      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

$javac com/tutorialspoint/ArrayListDemo.java

$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    at java.util.ArrayList.add(ArrayList.java:473)
    at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

What is private bytes, virtual bytes, working set?

You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.

A previous reply to this question has given a great explanation of what the various types are.

You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.

http://www.softwareverify.com/cpp/memory/index.html

Disclaimer: I designed Memory Validator.

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

Node.js check if file exists

Modern async/await way ( Node 12.8.x )

const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));

const main = async () => {
    console.log(await fileExists('/path/myfile.txt'));
}

main();

We need to use fs.stat() or fs.access() because fs.exists(path, callback) now is deprecated

Another good way is fs-extra

When do I need to use AtomicBoolean in Java?

Excerpt from the package description

Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]

The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]

Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]

The memory effects for accesses and updates of atomics generally follow the rules for volatiles:

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
  • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

Simply you can use:

on server side:

Registry <objectName1> =LocateRegisty.createRegistry(1099);
Registry <objectName2> =LocateRegisty.getRegistry();

on Client Side:

Registry <object name you want> =LocateRegisty.getRegistry();

SQL Server: Error converting data type nvarchar to numeric

In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.

SELECT ISNUMERIC('2.81104e+006') 

returns 1.

SELECT convert(decimal(15,2), '2.81104e+006') 

returns

error: Error converting data type varchar to numeric.

And

SELECT try_convert(decimal(15,2), '2.81104e+006') 

returns NULL.

SELECT convert(float, '2.81104e+006') 

returns the correct value 2811040.

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

What are the best use cases for Akka framework

An example of how we use it would be on a priority queue of debit/credit card transactions. We have millions of these and the effort of the work depends on the input string type. If the transaction is of type CHECK we have very little processing but if it is a point of sale then there is lots to do such as merge with meta data (category, label, tags, etc) and provide services (email/sms alerts, fraud detection, low funds balance, etc). Based on the input type we compose classes of various traits (called mixins) necessary to handle the job and then perform the work. All of these jobs come into the same queue in realtime mode from different financial institutions. Once the data is cleansed it is sent to different data stores for persistence, analytics, or pushed to a socket connection, or to Lift comet actor. Working actors are constantly self load balancing the work so that we can process the data as fast as possible. We can also snap in additional services, persistence models, and for critical decision points.

The Erlang OTP style message passing on the JVM makes a great system for developing realtime systems on the shoulders of existing libraries and application servers.

Akka allows you to do message passing like you would in a traditional but with speed! It also gives you tools in the framework to manage the vast amount of actor pools, remote nodes, and fault tolerance that you need for your solution.

MySQL combine two columns into one column

For the MySQL fans out there, I like the IFNULL() function. Other answers here suggest similar functionality with the ISNULL() function in some implementations. In my situation, I have a column of descriptions which is NOT NULL, and a column of serial numbers which may be NULL This is how I combined them into one column:

SELECT CONCAT(description,IFNULL(' SN: ', serial_number),'')) FROM my_table;

My results suggest that the results of concatenating a string with NULL results in a NULL. I have been getting the alternative value in those cases.

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

FFmpeg: How to split video efficiently?

The ffmpeg wiki links back to this page in reference to "How to split video efficiently". I'm not convinced this page answers that question, so I did as @AlcubierreDrive suggested…

echo "Two commands" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 -sn test1.mkv
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test2.mkv
echo "One command" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 \
  -sn test3.mkv -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test4.mkv

Which outputs...

Two commands
real    0m16.201s
user    0m1.830s
sys 0m1.301s

real    0m43.621s
user    0m4.943s
sys 0m2.908s

One command
real    0m59.410s
user    0m5.577s
sys 0m3.939s

I tested a SD & HD file, after a few runs & a little maths.

Two commands SD 0m53.94 #2 wins  
One command  SD 0m49.63  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.60 #2 wins  
One command  SD 0m58.61 

Two commands SD 0m54.60  
One command  SD 0m50.51 #1 wins 

Two commands SD 0m53.94  
One command  SD 0m49.63 #1 wins  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.71  
One command  SD 0m58.61 #1 wins

Two commands SD 0m54.63  
One command  SD 0m50.51 #1 wins  

Two commands SD 1m6.67s #2 wins  
One command  SD 1m20.18  

Two commands SD 1m7.67  
One command  SD 1m6.72 #1 wins

Two commands SD 1m4.92  
One command  SD 1m2.24 #1 wins

Two commands SD 1m1.73  
One command  SD 0m59.72 #1 wins

Two commands HD 4m23.20  
One command  HD 3m40.02 #1 wins

Two commands SD 1m1.30  
One command  SD 0m59.59 #1 wins  

Two commands HD 3m47.89  
One command  HD 3m29.59 #1 wins  

Two commands SD 0m59.82  
One command  SD 0m59.41 #1 wins  

Two commands HD 3m51.18  
One command  HD 3m30.79 #1 wins  

SD file = 1.35GB DVB transport stream
HD file = 3.14GB DVB transport stream

Conclusion

The single command is better if you are handling HD, it agrees with the manuals comments on using -ss after the input file to do a 'slow seek'. SD files have a negligible difference.

The two command version should be quicker by adding another -ss before the input file for the a 'fast seek' followed by the more accurate slow seek.

The point of test %eax %eax

test is a non-destructive and, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz conditional jump.

If list index exists, do X

I need to code such that if a certain list index exists, then run a function.

This is the perfect use for a try block:

ar=[1,2,3]

try:
    t=ar[5]
except IndexError:
    print('sorry, no 5')   

# Note: this only is a valid test in this context 
# with absolute (ie, positive) index
# a relative index is only showing you that a value can be returned
# from that relative index from the end of the list...

However, by definition, all items in a Python list between 0 and len(the_list)-1 exist (i.e., there is no need for a try block if you know 0 <= index < len(the_list)).

You can use enumerate if you want the indexes between 0 and the last element:

names=['barney','fred','dino']

for i, name in enumerate(names):
    print(i + ' ' + name)
    if i in (3,4):
        # do your thing with the index 'i' or value 'name' for each item...

If you are looking for some defined 'index' thought, I think you are asking the wrong question. Perhaps you should consider using a mapping container (such as a dict) versus a sequence container (such as a list). You could rewrite your code like this:

def do_something(name):
    print('some thing 1 done with ' + name)
        
def do_something_else(name):
    print('something 2 done with ' + name)        
    
def default(name):
    print('nothing done with ' + name)     
    
something_to_do={  
    3: do_something,        
    4: do_something_else
    }        
            
n = input ("Define number of actors: ")
count = 0
names = []

for count in range(n):
    print("Define name for actor {}:".format(count+1))
    name = raw_input ()
    names.append(name)
    
for name in names:
    try:
        something_to_do[len(name)](name)
    except KeyError:
        default(name)

Runs like this:

Define number of actors: 3
Define name for actor 1: bob
Define name for actor 2: tony
Define name for actor 3: alice
some thing 1 done with bob
something 2 done with tony
nothing done with alice

You can also use .get method rather than try/except for a shorter version:

>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm-install-peers worked for me.

npm install -g npm-install-peers

How to import image (.svg, .png ) in a React Component

You can use require as well to render images like

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}

Show SOME invisible/whitespace characters in Eclipse

Navigate to Window > Preferences > General > Editors > Text Editors

Click on the CheckBox "Show whitespace characters".

enter image description here

Thats all.!!!

Difference between a theta join, equijoin and natural join

@outis's answer is good: concise and correct as regards relations.

However, the situation is slightly more complicated as regards SQL.

Consider the usual suppliers and parts database but implemented in SQL:

SELECT * FROM S NATURAL JOIN SP;

would return a resultset** with columns

SNO, SNAME, STATUS, CITY, PNO, QTY

The join is performed on the column with the same name in both tables, SNO. Note that the resultset has six columns and only contains one column for SNO.

Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S and SP are required):

SELECT * FROM S JOIN SP ON S.SNO = SP.SNO;

The resultset will have seven columns, including two columns for SNO. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:

SNO, SNAME, STATUS, CITY, SNO, PNO, QTY

or perhaps this

S.SNO, SNAME, STATUS, CITY, SP.SNO, PNO, QTY

In other words, NATURAL JOIN in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT to SELECT DISTINCT yourself).


** I don't quite know what the result of SELECT * FROM table_expression; is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.

Check if list contains element that contains a string and get that element

It is possible to combine Any, Where, First and FirstOrDefault; or just place the predicate in any of those methods depending on what is needed.

You should probably avoid using First unless you want to have an exception thrown when no match is found. FirstOrDefault is usually the better option as long as you know it will return the type's default if no match is found (string's default is null, int is 0, bool is false, etc).

using System.Collections.Generic;
using System.Linq;


bool exists;
string firstMatch;
IEnumerable<string> matchingList;

var myList = new List<string>() { "foo", "bar", "foobar" };

exists = myList.Any(x => x.Contains("o"));
// exists => true

firstMatch = myList.FirstOrDefault(x => x.Contains("o"));
firstMatch = myList.First(x => x.Contains("o"));
// firstMatch => "foo"

firstMatch = myList.First(x => x.Contains("dark side"));
// throws exception because no element contains "dark side"

firstMatch = myList.FirstOrDefault(x => x.Contains("dark side"));
// firstMatch => null

matchingList = myList.Where(x => x.Contains("o")); 
// matchingList => { "foo", "foobar" }

Test this code @ https://rextester.com/TXDL57489

Android RatingBar change star colors

A bit late answer but i hope it will help some folks.

<RatingBar
         android:id="@+id/rating"
         style="@style/Base.Widget.AppCompat.RatingBar.Small"
         android:theme="@style/WhiteRatingStar"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/profil_name"
         android:layout_centerHorizontal="true"
         android:layout_marginLeft="@dimen/dimen_4"
         android:rating="3" />

And here is what the WhiteRatingStar looks like

<style name="WhiteRatingStar" parent="Base.Widget.AppCompat.RatingBar.Small">
     <item name="colorAccent">@android:color/white</item>
</style>

With this the stars will be coloured in white for example.

How do I remove blank pages coming between two chapters in Appendix?

If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.

Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself

How to get object length

You may use something like Lodash lib and _.toLength(object) should give you the length of your object

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

Passing an array to a query using a WHERE clause

Use:

select id from galleries where id in (1, 2, 5);

A simple for each loop will work.

Flavius/AvatarKava's way is better, but make sure that none of the array values contain commas.

Setting the selected value on a Django forms.ChoiceField

I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.

Flask ImportError: No Module Named Flask

my answer just for any users that use Visual Studio Flesk Web project :

Just Right Click on "Python Environment" and Click to "Add Environment"

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

For self-containing Maven project I usually installing all external jar dependencies into project's repository. For SQL Server JDBC driver you can do:

  • download JDBC driver from https://www.microsoft.com/en-us/download/confirmation.aspx?id=11774
  • create folder local-repo in your Maven project
  • temporary copy sqljdbc42.jar into local-repo folder
  • in local-repo folder run mvn deploy:deploy-file -Dfile=sqljdbc42.jar -DartifactId=sqljdbc42 -DgroupId=com.microsoft.sqlserver -DgeneratePom=true -Dpackaging=jar -Dversion=6.0.7507.100 -Durl=file://. to deploy JAR into local repository (stored together with your code in SCM)
  • sqljdbc42.jar and downloaded files can be deleted
  • modify your's pom.xml and add reference to project's local repository: xml <repositories> <repository> <id>parent-local-repository</id> <name>Parent Local repository</name> <layout>default</layout> <url>file://${basedir}/local-repo</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> Now you can run your project everywhere without any additional configurations or installations.

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

Is there a C++ decompiler?

You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.

If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

Maven 3 warnings about build.plugins.plugin.version

Run like:

  $ mvn help:describe -DartifactId=maven-war-plugin -DgroupId=org.apache.maven.plugins

for plug-in that have no version. You get output:

Name: Maven WAR Plugin
Description: Builds a Web Application Archive (WAR) file from the project
  output and its dependencies.
Group Id: org.apache.maven.plugins
Artifact Id: maven-war-plugin
Version: 2.2
Goal Prefix: war

Use version that shown in output.

UPDATE If you want to select among list of versions, use http://search.maven.org/ or http://mvnrepository.com/ Note that your favorite Java IDE must have Maven package search dialog. Just check docs.

SUPER UPDATE I also use:

$ mvn dependency:tree
$ mvn dependency:list
$ mvn dependency:resolve
$ mvn dependency:resolve-plugins  # <-- THIS

Recently I discover how to get latest version for plug-in (or library) so no longer needs for googling or visiting Maven Central:

$ mvn versions:display-dependency-updates
$ mvn versions:display-plugin-updates     # <-- THIS

How to Find the Default Charset/Encoding in Java?

The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:

  • Charset.defaultCharset() is not caching the determined character set in Java 5.
  • Setting the system property "file.encoding" and invoking Charset.defaultCharset() again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset() defaults to "UTF-8".
  • The OutputStreamWriter is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset() if the system property "file.encoding" has been changed at runtime.

As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset() API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

How to use a switch case 'or' in PHP

Try with these following examples in this article : http://phpswitch.com/

Possible Switch Cases :

(i). A simple switch statement

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

Example :

switch($bar)
{
    case 4:
        echo "This is not the number you're looking for.\n";
        $foo = 92;
}

(ii). Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:

Example :

case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iii). Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Example :

case 2:

case 3:
case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iv). Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Example :

switch(true)
{
    case (strlen($foo) > 30):
        $error = "The value provided is too long.";
    $valid = false;
    break;

    case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
        $error = "The value must be alphanumeric.";
    $valid = false;
    break;

    default:
    $valid = true;
    break;
}

i think this may help you to resolve your problem.

Why is NULL undeclared?

Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

There are problems with using 0 (and hence NULL). For example:

void f(int);
void f(void*);

f(0); // Ambiguous. Calls f(int).

The next version of C++ (C++0x) includes nullptr to fix this.

f(nullptr); // Calls f(void*).

Maven Installation OSX Error Unsupported major.minor version 51.0

The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

In my case my JDK installation is jdk1.8.0_40, make sure you type yours.

Then you can use maven commands.

Regards!

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Create a separate JavaScript function that can be called to close the dialog using the specific object id, and place the function outside of $(document).ready() like this:

function closeDialogWindow() { 
$('#dialogWindow').dialog('close');
}

NOTE: The function must be declared outside of $(document).ready() so jQuery doesn't try to trigger the close event on the dialog before it is created in the DOM.

Best way to store data locally in .NET (C#)

My first inclination is an access database. The .mdb files are stored locally, and can be encrypted if that is deemed necessary. Though XML or JSON would also work for many scenarios. Flat files I would only use for read only, non-search (forward read only) information. I tend to prefer csv format to set width.

Computational complexity of Fibonacci Sequence

You can expand it and have a visulization

     T(n) = T(n-1) + T(n-2) <
     T(n-1) + T(n-1) 

     = 2*T(n-1)   
     = 2*2*T(n-2)
     = 2*2*2*T(n-3)
     ....
     = 2^i*T(n-i)
     ...
     ==> O(2^n)

Force uninstall of Visual Studio

This is an odd solution, but it worked for me.

I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.

I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.

Segmentation fault on large array sizes

In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.

Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.

This will allocate in the BSS segment, which is a part of the heap:

static int c[1000000];
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate in the DATA segment, which is a part of the heap too:

int c[1000000] = {};
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate at some unspecified location in the heap:

int main()
{
   int* c = new int[1000000];
   cout << "done\n";
   return 0;
}

Taking multiple inputs from user in python

In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.

items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]

print items

Registry key Error: Java version has value '1.8', but '1.7' is required

My solution for this problem came after reading and trying all of the above.

In my case I tried to downgrade Java to use printouts in Apache ActiveMQ. After uninstalling all Java versions and cleaning the registry I was getting the same error

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.7', but '1.8' is required."

In my case I needed to go to environment variables, edit path, open the javapath location (C:\ProgramData\Oracle\Java\javapath) and there it was - three files (java.exe, javaw.exe, javaws.exe) that remained from the JRE8 version.

After establishing this fact I simply switched them with the same files from C:\Windows\SysWOW64 directory (those were from the JRE7 version) and it all worked perfectly.

Could not insert new outlet connection: Could not find any information for the class named

I solved this problem by programmatically creating the Labels and Textfields, and then Command-Dragged from the little empty circles on the left of the code to the components on the Storyboard. To illustrate my point: I wrote @IBOutlet weak var HelloLabel: UILabel!, and then pressed Command and dragged the code into the component on the storyboard.

Button text toggle in jquery

Use an if/else statement.. or ternary if you understand it

$(".pushme").click(function () {
    var $el = $(this);
    $el.text($el.text() == "DON'T PUSH ME" ? "PUSH ME": "DON'T PUSH ME");
});

http://jsfiddle.net/dFZyv/

.gitignore is ignored by Git

I had this same problem. I believe the issue was a CR vs. CR+LF discrepancy. I stashed things in my .gitignore using CMD (on Windows 7) and the following command:

Bad:

echo "file_to_be_ignored.py" >> .gitignore<br>
echo "*~" >> .gitignore

Etc.

The issue was that this command does not place the correct end-of-line marker for Git to recognize the newlines (either CR or CR+LF when Git expects the other). I solved the problem by manually replacing each newline in Vim (Vim to the rescue!) and it worked perfectly.

Try editing your .gitignore in Notepad++ or Vim (ideally). Even if the file looks like it's formatted correctly, try replacing the newlines. It sounds weird, I know, but it worked for me. :D

Pretty-print an entire Pandas Series / DataFrame

No need to hack settings. There is a simple way:

print(df.to_string())

Hiding the address bar of a browser (popup)

This is how I do it for popups, though it is only working with IE11, not Chrome- haven't tested in Firefox.

window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');

Retrieving the last record in each group - MySQL

Solution by sub query fiddle Link

select * from messages where id in
(select max(id) from messages group by Name)

Solution By join condition fiddle link

select m1.* from messages m1 
left outer join messages m2 
on ( m1.id<m2.id and m1.name=m2.name )
where m2.id is null

Reason for this post is to give fiddle link only. Same SQL is already provided in other answers.

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

Python popen command. Wait until the command is finished

I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.

Convert Iterable to Stream using Java 8 JDK

I would like to suggest using JOOL library, it hides spliterator magic behind the Seq.seq(iterable) call and also provides a whole bunch of additional useful functionality.

javascript: pause setTimeout();

You could wrap window.setTimeout like this, which I think is similar to what you were suggesting in the question:

var Timer = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
};

var timer = new Timer(function() {
    alert("Done!");
}, 1000);

timer.pause();
// Do some stuff...
timer.resume();

Command not found when using sudo

It seems that linux will say "command not found" even if you explicitly give the path to the file.

[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
sudo: /tmp/uid.sh: command not found
1
[veeam@jsandbox ~]$ chmod +x /tmp/uid.sh
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
0

It's a somewhat misleading error, however it's probably technically correct. A file is not a command until its executable, and so cannot be found.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.

Main file with environment variables definition:

$ ls -la /etc/environment 
-r-xr-xr-x  1 root  wheel  369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh

set -e

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"

launchctl setenv JAVA_HOME      /usr/local/jdk1.7
launchctl setenv MAVEN_HOME     /opt/local/share/java/maven3

if [ -x /usr/libexec/path_helper ]; then
    export PATH=""
    eval `/usr/libexec/path_helper -s`
    launchctl setenv PATH $PATH
fi

osascript -e 'tell app "Dock" to quit'

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"

Service definition to load environment variables for user applications (terminal, IDE, ...):

$ ls -la /Library/LaunchAgents/environment.user.plist
-rw-------  1 root  wheel  504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment.user</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

The same service definition for root user applications:

$ ls -la /Library/LaunchDaemons/environment.plist
-rw-------  1 root  wheel  499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

And finally we should register these services:

$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist

What we get:

  1. The only place to declare system environment variables: /etc/environment
  2. Instant auto-update of environment variables after modification of /etc/environment file - just relaunch your application

Issues / problems:

In order your env variables were correctly taken by applications after system reboot you will need:

  • either login twice: login => logout => login
  • or close & re-open applications manually, where env variables should be taken
  • or do NOT use feature "Reopen windows when logging back".

This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".

But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

How to convert numbers to words without using num2word library?

Your first statement logic is incorrect. Unless Number is 1 or smaller, that statement is always True; 200 is greater than 1 as well.

Use and instead, and include 1 in the acceptable values:

if (Number >= 1) and (Number <= 19):

You could use chaining as well:

if 1 <= Number <= 19:

For numbers of 20 or larger, use divmod() to get both the number of tens and the remainder:

tens, remainder = divmod(Number, 10)

Demo:

>>> divmod(42, 10)
(4, 2)

then use those values to build your number from the parts:

return num2words2[tens - 2] + '-' + num2words1[below_ten]

Don't forget to account for cases when the number is above 20 and doesn't have a remainder from the divmod operation:

return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]

All put together:

def number(Number):
    if 0 <= Number <= 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, remainder = divmod(Number, 10)
        return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
    else:
        print('Number out of implemented range of numbers.')

Sql connection-string for localhost server

Choose a database name in Initial Catalog

Data Source=HARIHARAN-PC\SQLEXPRESS;Initial Catalog=your database name;Integrated Security=True" ;

see more

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Check object empty

I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.

To check for Collection be empty or null

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

or use Apache Commons CollectionUtils.isEmpty()

To check if Map is empty or null

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

or use Apache Commons MapUtils.isEmpty()

To check for String empty or null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

or use Apache Commons StringUtils.isBlank()

To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

pip cannot install anything

The explanation is in your logs:

Could not fetch URL https://pypi.python.org/simple/yolk/: HTTP Error 503: Service Unavailable

Notice the HTTP Error 503: Service Unavailable. It seems the site was down when you were trying to do this.

It's good to know that HTTP 5xx errors are server side errors, so you can know the problem was not in your local network but in the remote network.

It means try again later ;-) (and cross fingers...) (It works for me now btw.)

View stored procedure/function definition in MySQL

You can use table proc in database mysql:

mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;

Note that you must have a grant for select to mysql.proc:

mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

adb uninstall failed

Open your application Manifest and check the application's package first.

After that, be sure that your device is set into debugger mode.

Check if ADB can interact with your device:

adb devices

If your device is listed, then run:

adb uninstall PACKAGE_WRITTEN_IN_MANIFEST

Hashset vs Treeset

Basing on lovely visual answer on Maps by @shevchyk here is my take:

+------------------------------------------------------------------------------+
¦   Property   ¦       HashSet       ¦      TreeSet      ¦     LinkedHashSet   ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦  no guarantee order ¦ sorted according  ¦                     ¦
¦   Order      ¦ will remain constant¦ to the natural    ¦    insertion-order  ¦
¦              ¦      over time      ¦    ordering       ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Add/remove   ¦        O(1)         ¦     O(log(n))     ¦        O(1)         ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦   NavigableSet    ¦                     ¦
¦  Interfaces  ¦         Set         ¦       Set         ¦         Set         ¦
¦              ¦                     ¦    SortedSet      ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦    not allowed    ¦                     ¦
¦  Null values ¦       allowed       ¦ 1st element only  ¦      allowed        ¦
¦              ¦                     ¦     in Java 7     ¦                     ¦
¦--------------+---------------------------------------------------------------¦
¦              ¦   Fail-fast behavior of an iterator cannot be guaranteed      ¦
¦   Fail-fast  ¦ impossible to make any hard guarantees in the presence of     ¦
¦   behavior   ¦           unsynchronized concurrent modification              ¦
¦--------------+---------------------------------------------------------------¦
¦      Is      ¦                                                               ¦
¦ synchronized ¦              implementation is not synchronized               ¦
+------------------------------------------------------------------------------+

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

Getting SyntaxError for print with keyword argument end=' '

How about this:

#Only for use in Python 2.6.0a2 and later
from __future__ import print_function

This allows you to use the Python 3.0 style print function without having to hand-edit all occurrences of print :)

ReactJS SyntheticEvent stopPropagation() only works with React events?

Update: You can now <Elem onClick={ proxy => proxy.stopPropagation() } />

Maven Jacoco Configuration - Exclude classes/packages from report not working

Here is the working sample in pom.xml file.

    <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>


        <executions>
            <execution>
                <id>prepare-agent</id>
                <goals>
                    <goal>prepare-agent</goal>
                </goals>
            </execution>
            <execution>
                <id>post-unit-test</id>
                <phase>test</phase>
                <goals>
                    <goal>report</goal>
                </goals>

            </execution>

            <execution>
                <id>default-check</id>
                <goals>
                    <goal>check</goal>
                </goals>

            </execution>
        </executions>
        <configuration>
            <dataFile>target/jacoco.exec</dataFile>
            <!-- Sets the output directory for the code coverage report. -->
            <outputDirectory>target/jacoco-ut</outputDirectory>
            <rules>
                <rule implementation="org.jacoco.maven.RuleConfiguration">
                    <element>PACKAGE</element>
                    <limits>
                        <limit implementation="org.jacoco.report.check.Limit">
                            <counter>COMPLEXITY</counter>
                            <value>COVEREDRATIO</value>
                            <minimum>0.00</minimum>
                        </limit>
                    </limits>
                </rule>
            </rules>
            <excludes>
                <exclude>com/pfj/fleet/dao/model/**/*</exclude>
            </excludes>
            <systemPropertyVariables>

                <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
            </systemPropertyVariables>
        </configuration>
    </plugin>

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Append key/value pair to hash with << in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

How to add a Java Properties file to my Java Project in Eclipse

  1. Right click on the folder within your project in eclipse where you want to create property file
  2. New->Other->in the search filter type file and in the consecutive window give the name of the file with .properties extension

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

retrieve links from web page using python and BeautifulSoup

Here's a short snippet using the SoupStrainer class in BeautifulSoup:

import httplib2
from bs4 import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')

for link in BeautifulSoup(response, parse_only=SoupStrainer('a')):
    if link.has_attr('href'):
        print(link['href'])

The BeautifulSoup documentation is actually quite good, and covers a number of typical scenarios:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

Edit: Note that I used the SoupStrainer class because it's a bit more efficient (memory and speed wise), if you know what you're parsing in advance.

How to exclude a directory in find . command

I was using find to provide a list of files for xgettext, and wanted to omit a specific directory and its contents. I tried many permutations of -path combined with -prune but was unable to fully exclude the directory which I wanted gone.

Although I was able to ignore the contents of the directory which I wanted ignored, find then returned the directory itself as one of the results, which caused xgettext to crash as a result (doesn't accept directories; only files).

My solution was to simply use grep -v to skip the directory that I didn't want in the results:

find /project/directory -iname '*.php' -or -iname '*.phtml' | grep -iv '/some/directory' | xargs xgettext

Whether or not there is an argument for find that will work 100%, I cannot say for certain. Using grep was a quick and easy solution after some headache.

When does a cookie with expiration time 'At end of session' expire?

Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!

On iOS with Safari they expire whenever you switch apps!

On Android with Chrome they don't expire when you close the browser.

On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.

Freely convert between List<T> and IEnumerable<T>

To prevent duplication in memory, resharper is suggesting this:

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myList as List<string>() ?? myEnumerable.ToList();

.ToList() returns a new immutable list. So changes to listAgain does not effect myList in @Tamas Czinege answer. This is correct in most instances for least two reasons: This helps prevent changes in one area effecting the other area (loose coupling), and it is very readable, since we shouldn't be designing code with compiler concerns.

But there are certain instances, like being in a tight loop or working on an embedded or low memory system, where compiler considerations should be taken into consideration.

Why did I get the compile error "Use of unassigned local variable"?

Local variables aren't initialized. You have to manually initialize them.

Members are initialized, for example:

public class X
{
    private int _tmpCnt; // This WILL initialize to zero
    ...
}

But local variables are not:

public static void SomeMethod()
{
    int tmpCnt;  // This is not initialized and must be assigned before used.

    ...
}

So your code must be:

int tmpCnt = 0;  
if (name == "Dude")  
   tmpCnt++;  

So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.

How can I get file extensions with JavaScript?

function extension(fname) {
  var pos = fname.lastIndexOf(".");
  var strlen = fname.length;
  if (pos != -1 && strlen != pos + 1) {
    var ext = fname.split(".");
    var len = ext.length;
    var extension = ext[len - 1].toLowerCase();
  } else {
    extension = "No extension found";
  }
  return extension;
}

//usage

extension('file.jpeg')

always returns the extension lower cas so you can check it on field change works for:

file.JpEg

file (no extension)

file. (noextension)

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

problem with php mail 'From' header

The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.

If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.

C.

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml contains the necessary slf4j dependencies, e.g.:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>

Why I've got no crontab entry on OS X when using vim?

I've never had this problem, but I create a ~/.crontab file and edit that (which allows me to back it up, Time Machine or otherwise), then run

crontab ~/.crontab

Has worked for me for 20+ years across many flavors of unix.

Changing the browser zoom level

as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>

how to rotate a bitmap 90 degrees

Short extension for Kotlin

fun Bitmap.rotate(degrees: Float): Bitmap {
    val matrix = Matrix().apply { postRotate(degrees) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

And usage:

val rotatedBitmap = bitmap.rotate(90f)

Compile to a stand-alone executable (.exe) in Visual Studio

I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.

But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.

Delete dynamically-generated table row using jQuery

  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});

This works perfectly, take not of document.body

Is the NOLOCK (Sql Server hint) bad practice?

I agree with some comments about NOLOCK hint and especially with those saying "use it when it's appropriate". If the application written poorly and is using concurrency inappropriate way – that may cause the lock escalation. Highly transactional table also are getting locked all the time due to their nature. Having good index coverage won't help with retrieving the data, but setting ISOLATION LEVEL to READ UNCOMMITTED does. Also I believe that using NOLOCK hint is safe in many cases when the nature of changes is predictable. For example – in manufacturing when jobs with travellers are going through different processes with lots of inserts of measurements, you can safely execute query against the finished job with NOLOCK hint and this way avoid collision with other sessions that put PROMOTED or EXCLUSIVE locks on the table/page. The data you access in this case is static, but it may reside in a very transactional table with hundreds of millions of records and thousands updates/inserts per minute. Cheers

Is it possible only to declare a variable without assigning any value in Python?

I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just

foo = None

which will assign the value None to the variable foo.

EDIT: What you really seem to want to do is just this:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.

EDIT: below is comment by JFS (posted here to show the code)

Unrelated to the OP's question but the above code can be rewritten as:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

NOTE: if some_condition() raises an exception then found is unbound.
NOTE: if len(sequence) == 0 then item is unbound.

The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case. Preferable way:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

Or

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)

Preventing iframe caching in browser

Have you tried adding the various HTTP Header options for no-cache to the iframe page?

How to get the URL of the current page in C#

I guess its enough to return absolute path..

 Path.GetFileName( Request.Url.AbsolutePath )

using System.IO;

How to set the background image of a html 5 canvas to .png image

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

<!DOCTYPE HTML>
<html><head>
  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
  </style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  ctx.strokeRect(140,60,40,40);
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();
</script>
</body></html>

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

Perl: function to trim string leading and trailing whitespace

One option is Text::Trim:

use Text::Trim;
print trim("  example  ");

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

The accepted answer is great, but here's the short answer:

<key>CFBundleIconFiles</key>
<array>
    <string>[email protected]</string>
    <string>icon.png</string>
    <string>Icon-Small.png</string>
    <string>[email protected]</string>
    <string>Default.png</string>
    <string>[email protected]</string>
    <string>icon-72.png</string>
    <string>[email protected]</string>
    <string>Icon-Small-50.png</string>
    <string>[email protected]</string>
    <string>Default-Landscape.png</string>
    <string>[email protected]</string>
    <string>Default-Portrait.png</string>
    <string>[email protected]</string>

New icons below here

    <string>icon-40.png</string>
    <string>[email protected]</string>
    <string>icon-60.png</string>
    <string>[email protected]</string>
    <string>icon-76.png</string>
    <string>[email protected]</string>
</array>

Found this here by searching for "The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format." in Google.